babylon.max.js 2.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655
  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 (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. /**
  22. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  23. */
  24. MathTools.WithinEpsilon = function (a, b, epsilon) {
  25. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  26. var num = a - b;
  27. return -epsilon <= num && num <= epsilon;
  28. };
  29. /**
  30. * Returns a string : the upper case translation of the number i to hexadecimal.
  31. */
  32. MathTools.ToHex = function (i) {
  33. var str = i.toString(16);
  34. if (i <= 15) {
  35. return ("0" + str).toUpperCase();
  36. }
  37. return str.toUpperCase();
  38. };
  39. /**
  40. * Returns -1 if value is negative and +1 is value is positive.
  41. * Returns the value itself if it's equal to zero.
  42. */
  43. MathTools.Sign = function (value) {
  44. value = +value; // convert to a number
  45. if (value === 0 || isNaN(value))
  46. return value;
  47. return value > 0 ? 1 : -1;
  48. };
  49. /**
  50. * Returns the value itself if it's between min and max.
  51. * Returns min if the value is lower than min.
  52. * Returns max if the value is greater than max.
  53. */
  54. MathTools.Clamp = function (value, min, max) {
  55. if (min === void 0) { min = 0; }
  56. if (max === void 0) { max = 1; }
  57. return Math.min(max, Math.max(min, value));
  58. };
  59. return MathTools;
  60. }());
  61. BABYLON.MathTools = MathTools;
  62. var Color3 = (function () {
  63. /**
  64. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  65. */
  66. function Color3(r, g, b) {
  67. if (r === void 0) { r = 0; }
  68. if (g === void 0) { g = 0; }
  69. if (b === void 0) { b = 0; }
  70. this.r = r;
  71. this.g = g;
  72. this.b = b;
  73. }
  74. /**
  75. * Returns a string with the Color3 current values.
  76. */
  77. Color3.prototype.toString = function () {
  78. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  79. };
  80. /**
  81. * Returns the string "Color3".
  82. */
  83. Color3.prototype.getClassName = function () {
  84. return "Color3";
  85. };
  86. /**
  87. * Returns the Color3 hash code.
  88. */
  89. Color3.prototype.getHashCode = function () {
  90. var hash = this.r || 0;
  91. hash = (hash * 397) ^ (this.g || 0);
  92. hash = (hash * 397) ^ (this.b || 0);
  93. return hash;
  94. };
  95. // Operators
  96. /**
  97. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  98. * Returns the Color3.
  99. */
  100. Color3.prototype.toArray = function (array, index) {
  101. if (index === undefined) {
  102. index = 0;
  103. }
  104. array[index] = this.r;
  105. array[index + 1] = this.g;
  106. array[index + 2] = this.b;
  107. return this;
  108. };
  109. /**
  110. * Returns a new Color4 object from the current Color3 and the passed alpha.
  111. */
  112. Color3.prototype.toColor4 = function (alpha) {
  113. if (alpha === void 0) { alpha = 1; }
  114. return new Color4(this.r, this.g, this.b, alpha);
  115. };
  116. /**
  117. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  118. */
  119. Color3.prototype.asArray = function () {
  120. var result = [];
  121. this.toArray(result, 0);
  122. return result;
  123. };
  124. /**
  125. * Returns the luminance value (float).
  126. */
  127. Color3.prototype.toLuminance = function () {
  128. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  129. };
  130. /**
  131. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  132. * Returns this new object.
  133. */
  134. Color3.prototype.multiply = function (otherColor) {
  135. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  136. };
  137. /**
  138. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  139. * Returns the current Color3.
  140. */
  141. Color3.prototype.multiplyToRef = function (otherColor, result) {
  142. result.r = this.r * otherColor.r;
  143. result.g = this.g * otherColor.g;
  144. result.b = this.b * otherColor.b;
  145. return this;
  146. };
  147. /**
  148. * Boolean : True if the rgb values are equal to the passed ones.
  149. */
  150. Color3.prototype.equals = function (otherColor) {
  151. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  152. };
  153. /**
  154. * Boolean : True if the rgb values are equal to the passed ones.
  155. */
  156. Color3.prototype.equalsFloats = function (r, g, b) {
  157. return this.r === r && this.g === g && this.b === b;
  158. };
  159. /**
  160. * Multiplies in place each rgb value by scale.
  161. * Returns the updated Color3.
  162. */
  163. Color3.prototype.scale = function (scale) {
  164. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  165. };
  166. /**
  167. * Multiplies the rgb values by scale and stores the result into "result".
  168. * Returns the unmodified current Color3.
  169. */
  170. Color3.prototype.scaleToRef = function (scale, result) {
  171. result.r = this.r * scale;
  172. result.g = this.g * scale;
  173. result.b = this.b * scale;
  174. return this;
  175. };
  176. /**
  177. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  178. */
  179. Color3.prototype.add = function (otherColor) {
  180. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  181. };
  182. /**
  183. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  184. * Returns the unmodified current Color3.
  185. */
  186. Color3.prototype.addToRef = function (otherColor, result) {
  187. result.r = this.r + otherColor.r;
  188. result.g = this.g + otherColor.g;
  189. result.b = this.b + otherColor.b;
  190. return this;
  191. };
  192. /**
  193. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  194. */
  195. Color3.prototype.subtract = function (otherColor) {
  196. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  197. };
  198. /**
  199. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  200. * Returns the unmodified current Color3.
  201. */
  202. Color3.prototype.subtractToRef = function (otherColor, result) {
  203. result.r = this.r - otherColor.r;
  204. result.g = this.g - otherColor.g;
  205. result.b = this.b - otherColor.b;
  206. return this;
  207. };
  208. /**
  209. * Returns a new Color3 copied the current one.
  210. */
  211. Color3.prototype.clone = function () {
  212. return new Color3(this.r, this.g, this.b);
  213. };
  214. /**
  215. * Copies the rgb values from the source in the current Color3.
  216. * Returns the updated Color3.
  217. */
  218. Color3.prototype.copyFrom = function (source) {
  219. this.r = source.r;
  220. this.g = source.g;
  221. this.b = source.b;
  222. return this;
  223. };
  224. /**
  225. * Updates the Color3 rgb values from the passed floats.
  226. * Returns the Color3.
  227. */
  228. Color3.prototype.copyFromFloats = function (r, g, b) {
  229. this.r = r;
  230. this.g = g;
  231. this.b = b;
  232. return this;
  233. };
  234. /**
  235. * Returns the Color3 hexadecimal code as a string.
  236. */
  237. Color3.prototype.toHexString = function () {
  238. var intR = (this.r * 255) | 0;
  239. var intG = (this.g * 255) | 0;
  240. var intB = (this.b * 255) | 0;
  241. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  242. };
  243. /**
  244. * Returns a new Color3 converted to linear space.
  245. */
  246. Color3.prototype.toLinearSpace = function () {
  247. var convertedColor = new Color3();
  248. this.toLinearSpaceToRef(convertedColor);
  249. return convertedColor;
  250. };
  251. /**
  252. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  253. * Returns the unmodified Color3.
  254. */
  255. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  256. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  257. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  258. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  259. return this;
  260. };
  261. /**
  262. * Returns a new Color3 converted to gamma space.
  263. */
  264. Color3.prototype.toGammaSpace = function () {
  265. var convertedColor = new Color3();
  266. this.toGammaSpaceToRef(convertedColor);
  267. return convertedColor;
  268. };
  269. /**
  270. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  271. * Returns the unmodified Color3.
  272. */
  273. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  274. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  275. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  276. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  277. return this;
  278. };
  279. // Statics
  280. /**
  281. * Creates a new Color3 from the string containing valid hexadecimal values.
  282. */
  283. Color3.FromHexString = function (hex) {
  284. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  285. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  286. return new Color3(0, 0, 0);
  287. }
  288. var r = parseInt(hex.substring(1, 3), 16);
  289. var g = parseInt(hex.substring(3, 5), 16);
  290. var b = parseInt(hex.substring(5, 7), 16);
  291. return Color3.FromInts(r, g, b);
  292. };
  293. /**
  294. * Creates a new Vector3 from the startind index of the passed array.
  295. */
  296. Color3.FromArray = function (array, offset) {
  297. if (offset === void 0) { offset = 0; }
  298. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  299. };
  300. /**
  301. * Creates a new Color3 from integer values ( < 256).
  302. */
  303. Color3.FromInts = function (r, g, b) {
  304. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  305. };
  306. /**
  307. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  308. */
  309. Color3.Lerp = function (start, end, amount) {
  310. var r = start.r + ((end.r - start.r) * amount);
  311. var g = start.g + ((end.g - start.g) * amount);
  312. var b = start.b + ((end.b - start.b) * amount);
  313. return new Color3(r, g, b);
  314. };
  315. Color3.Red = function () { return new Color3(1, 0, 0); };
  316. Color3.Green = function () { return new Color3(0, 1, 0); };
  317. Color3.Blue = function () { return new Color3(0, 0, 1); };
  318. Color3.Black = function () { return new Color3(0, 0, 0); };
  319. Color3.White = function () { return new Color3(1, 1, 1); };
  320. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  321. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  322. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  323. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  324. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  325. return Color3;
  326. }());
  327. BABYLON.Color3 = Color3;
  328. var Color4 = (function () {
  329. /**
  330. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  331. */
  332. function Color4(r, g, b, a) {
  333. this.r = r;
  334. this.g = g;
  335. this.b = b;
  336. this.a = a;
  337. }
  338. // Operators
  339. /**
  340. * Adds in place the passed Color4 values to the current Color4.
  341. * Returns the updated Color4.
  342. */
  343. Color4.prototype.addInPlace = function (right) {
  344. this.r += right.r;
  345. this.g += right.g;
  346. this.b += right.b;
  347. this.a += right.a;
  348. return this;
  349. };
  350. /**
  351. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  352. */
  353. Color4.prototype.asArray = function () {
  354. var result = [];
  355. this.toArray(result, 0);
  356. return result;
  357. };
  358. /**
  359. * Stores from the starting index in the passed array the Color4 successive values.
  360. * Returns the Color4.
  361. */
  362. Color4.prototype.toArray = function (array, index) {
  363. if (index === undefined) {
  364. index = 0;
  365. }
  366. array[index] = this.r;
  367. array[index + 1] = this.g;
  368. array[index + 2] = this.b;
  369. array[index + 3] = this.a;
  370. return this;
  371. };
  372. /**
  373. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  374. */
  375. Color4.prototype.add = function (right) {
  376. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  377. };
  378. /**
  379. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  380. */
  381. Color4.prototype.subtract = function (right) {
  382. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  383. };
  384. /**
  385. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  386. * Returns the Color4.
  387. */
  388. Color4.prototype.subtractToRef = function (right, result) {
  389. result.r = this.r - right.r;
  390. result.g = this.g - right.g;
  391. result.b = this.b - right.b;
  392. result.a = this.a - right.a;
  393. return this;
  394. };
  395. /**
  396. * Creates a new Color4 with the current Color4 values multiplied by scale.
  397. */
  398. Color4.prototype.scale = function (scale) {
  399. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  400. };
  401. /**
  402. * Multiplies the current Color4 values by scale and stores the result in "result".
  403. * Returns the Color4.
  404. */
  405. Color4.prototype.scaleToRef = function (scale, result) {
  406. result.r = this.r * scale;
  407. result.g = this.g * scale;
  408. result.b = this.b * scale;
  409. result.a = this.a * scale;
  410. return this;
  411. };
  412. /**
  413. * Multipy an RGBA Color4 value by another and return a new Color4 object
  414. * @param color The Color4 (RGBA) value to multiply by
  415. * @returns A new Color4.
  416. */
  417. Color4.prototype.multiply = function (color) {
  418. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  419. };
  420. /**
  421. * Multipy an RGBA Color4 value by another and push the result in a reference value
  422. * @param color The Color4 (RGBA) value to multiply by
  423. * @param result The Color4 (RGBA) to fill the result in
  424. * @returns the result Color4.
  425. */
  426. Color4.prototype.multiplyToRef = function (color, result) {
  427. result.r = this.r * color.r;
  428. result.g = this.g * color.g;
  429. result.b = this.b * color.b;
  430. result.a = this.a * color.a;
  431. return result;
  432. };
  433. /**
  434. * Returns a string with the Color4 values.
  435. */
  436. Color4.prototype.toString = function () {
  437. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  438. };
  439. /**
  440. * Returns the string "Color4"
  441. */
  442. Color4.prototype.getClassName = function () {
  443. return "Color4";
  444. };
  445. /**
  446. * Return the Color4 hash code as a number.
  447. */
  448. Color4.prototype.getHashCode = function () {
  449. var hash = this.r || 0;
  450. hash = (hash * 397) ^ (this.g || 0);
  451. hash = (hash * 397) ^ (this.b || 0);
  452. hash = (hash * 397) ^ (this.a || 0);
  453. return hash;
  454. };
  455. /**
  456. * Creates a new Color4 copied from the current one.
  457. */
  458. Color4.prototype.clone = function () {
  459. return new Color4(this.r, this.g, this.b, this.a);
  460. };
  461. /**
  462. * Copies the passed Color4 values into the current one.
  463. * Returns the updated Color4.
  464. */
  465. Color4.prototype.copyFrom = function (source) {
  466. this.r = source.r;
  467. this.g = source.g;
  468. this.b = source.b;
  469. this.a = source.a;
  470. return this;
  471. };
  472. /**
  473. * Returns a string containing the hexadecimal Color4 code.
  474. */
  475. Color4.prototype.toHexString = function () {
  476. var intR = (this.r * 255) | 0;
  477. var intG = (this.g * 255) | 0;
  478. var intB = (this.b * 255) | 0;
  479. var intA = (this.a * 255) | 0;
  480. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  481. };
  482. // Statics
  483. /**
  484. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  485. */
  486. Color4.FromHexString = function (hex) {
  487. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  488. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  489. return new Color4(0.0, 0.0, 0.0, 0.0);
  490. }
  491. var r = parseInt(hex.substring(1, 3), 16);
  492. var g = parseInt(hex.substring(3, 5), 16);
  493. var b = parseInt(hex.substring(5, 7), 16);
  494. var a = parseInt(hex.substring(7, 9), 16);
  495. return Color4.FromInts(r, g, b, a);
  496. };
  497. /**
  498. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  499. */
  500. Color4.Lerp = function (left, right, amount) {
  501. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  502. Color4.LerpToRef(left, right, amount, result);
  503. return result;
  504. };
  505. /**
  506. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  507. */
  508. Color4.LerpToRef = function (left, right, amount, result) {
  509. result.r = left.r + (right.r - left.r) * amount;
  510. result.g = left.g + (right.g - left.g) * amount;
  511. result.b = left.b + (right.b - left.b) * amount;
  512. result.a = left.a + (right.a - left.a) * amount;
  513. };
  514. /**
  515. * Creates a new Color4 from the starting index element of the passed array.
  516. */
  517. Color4.FromArray = function (array, offset) {
  518. if (offset === void 0) { offset = 0; }
  519. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  520. };
  521. /**
  522. * Creates a new Color4 from the passed integers ( < 256 ).
  523. */
  524. Color4.FromInts = function (r, g, b, a) {
  525. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  526. };
  527. Color4.CheckColors4 = function (colors, count) {
  528. // Check if color3 was used
  529. if (colors.length === count * 3) {
  530. var colors4 = [];
  531. for (var index = 0; index < colors.length; index += 3) {
  532. var newIndex = (index / 3) * 4;
  533. colors4[newIndex] = colors[index];
  534. colors4[newIndex + 1] = colors[index + 1];
  535. colors4[newIndex + 2] = colors[index + 2];
  536. colors4[newIndex + 3] = 1.0;
  537. }
  538. return colors4;
  539. }
  540. return colors;
  541. };
  542. return Color4;
  543. }());
  544. BABYLON.Color4 = Color4;
  545. var Vector2 = (function () {
  546. /**
  547. * Creates a new Vector2 from the passed x and y coordinates.
  548. */
  549. function Vector2(x, y) {
  550. this.x = x;
  551. this.y = y;
  552. }
  553. /**
  554. * Returns a string with the Vector2 coordinates.
  555. */
  556. Vector2.prototype.toString = function () {
  557. return "{X: " + this.x + " Y:" + this.y + "}";
  558. };
  559. /**
  560. * Returns the string "Vector2"
  561. */
  562. Vector2.prototype.getClassName = function () {
  563. return "Vector2";
  564. };
  565. /**
  566. * Returns the Vector2 hash code as a number.
  567. */
  568. Vector2.prototype.getHashCode = function () {
  569. var hash = this.x || 0;
  570. hash = (hash * 397) ^ (this.y || 0);
  571. return hash;
  572. };
  573. // Operators
  574. /**
  575. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  576. * Returns the Vector2.
  577. */
  578. Vector2.prototype.toArray = function (array, index) {
  579. if (index === void 0) { index = 0; }
  580. array[index] = this.x;
  581. array[index + 1] = this.y;
  582. return this;
  583. };
  584. /**
  585. * Returns a new array with 2 elements : the Vector2 coordinates.
  586. */
  587. Vector2.prototype.asArray = function () {
  588. var result = [];
  589. this.toArray(result, 0);
  590. return result;
  591. };
  592. /**
  593. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  594. * Returns the updated Vector2.
  595. */
  596. Vector2.prototype.copyFrom = function (source) {
  597. this.x = source.x;
  598. this.y = source.y;
  599. return this;
  600. };
  601. /**
  602. * Sets the Vector2 coordinates with the passed floats.
  603. * Returns the updated Vector2.
  604. */
  605. Vector2.prototype.copyFromFloats = function (x, y) {
  606. this.x = x;
  607. this.y = y;
  608. return this;
  609. };
  610. /**
  611. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  612. */
  613. Vector2.prototype.add = function (otherVector) {
  614. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  615. };
  616. /**
  617. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  618. * Returns the Vector2.
  619. */
  620. Vector2.prototype.addToRef = function (otherVector, result) {
  621. result.x = this.x + otherVector.x;
  622. result.y = this.y + otherVector.y;
  623. return this;
  624. };
  625. /**
  626. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  627. * Returns the updated Vector2.
  628. */
  629. Vector2.prototype.addInPlace = function (otherVector) {
  630. this.x += otherVector.x;
  631. this.y += otherVector.y;
  632. return this;
  633. };
  634. /**
  635. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  636. */
  637. Vector2.prototype.addVector3 = function (otherVector) {
  638. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  639. };
  640. /**
  641. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  642. */
  643. Vector2.prototype.subtract = function (otherVector) {
  644. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  645. };
  646. /**
  647. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  648. * Returns the Vector2.
  649. */
  650. Vector2.prototype.subtractToRef = function (otherVector, result) {
  651. result.x = this.x - otherVector.x;
  652. result.y = this.y - otherVector.y;
  653. return this;
  654. };
  655. /**
  656. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  657. * Returns the updated Vector2.
  658. */
  659. Vector2.prototype.subtractInPlace = function (otherVector) {
  660. this.x -= otherVector.x;
  661. this.y -= otherVector.y;
  662. return this;
  663. };
  664. /**
  665. * Multiplies in place the current Vector2 coordinates by the passed ones.
  666. * Returns the updated Vector2.
  667. */
  668. Vector2.prototype.multiplyInPlace = function (otherVector) {
  669. this.x *= otherVector.x;
  670. this.y *= otherVector.y;
  671. return this;
  672. };
  673. /**
  674. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  675. */
  676. Vector2.prototype.multiply = function (otherVector) {
  677. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  678. };
  679. /**
  680. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  681. * Returns the Vector2.
  682. */
  683. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  684. result.x = this.x * otherVector.x;
  685. result.y = this.y * otherVector.y;
  686. return this;
  687. };
  688. /**
  689. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  690. */
  691. Vector2.prototype.multiplyByFloats = function (x, y) {
  692. return new Vector2(this.x * x, this.y * y);
  693. };
  694. /**
  695. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  696. */
  697. Vector2.prototype.divide = function (otherVector) {
  698. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  699. };
  700. /**
  701. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  702. * Returns the Vector2.
  703. */
  704. Vector2.prototype.divideToRef = function (otherVector, result) {
  705. result.x = this.x / otherVector.x;
  706. result.y = this.y / otherVector.y;
  707. return this;
  708. };
  709. /**
  710. * Returns a new Vector2 with current Vector2 negated coordinates.
  711. */
  712. Vector2.prototype.negate = function () {
  713. return new Vector2(-this.x, -this.y);
  714. };
  715. /**
  716. * Multiply the Vector2 coordinates by scale.
  717. * Returns the updated Vector2.
  718. */
  719. Vector2.prototype.scaleInPlace = function (scale) {
  720. this.x *= scale;
  721. this.y *= scale;
  722. return this;
  723. };
  724. /**
  725. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  726. */
  727. Vector2.prototype.scale = function (scale) {
  728. return new Vector2(this.x * scale, this.y * scale);
  729. };
  730. /**
  731. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  732. */
  733. Vector2.prototype.equals = function (otherVector) {
  734. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  735. };
  736. /**
  737. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  738. */
  739. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  740. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  741. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  742. };
  743. // Properties
  744. /**
  745. * Returns the vector length (float).
  746. */
  747. Vector2.prototype.length = function () {
  748. return Math.sqrt(this.x * this.x + this.y * this.y);
  749. };
  750. /**
  751. * Returns the vector squared length (float);
  752. */
  753. Vector2.prototype.lengthSquared = function () {
  754. return (this.x * this.x + this.y * this.y);
  755. };
  756. // Methods
  757. /**
  758. * Normalize the vector.
  759. * Returns the updated Vector2.
  760. */
  761. Vector2.prototype.normalize = function () {
  762. var len = this.length();
  763. if (len === 0)
  764. return this;
  765. var num = 1.0 / len;
  766. this.x *= num;
  767. this.y *= num;
  768. return this;
  769. };
  770. /**
  771. * Returns a new Vector2 copied from the Vector2.
  772. */
  773. Vector2.prototype.clone = function () {
  774. return new Vector2(this.x, this.y);
  775. };
  776. // Statics
  777. /**
  778. * Returns a new Vector2(0, 0)
  779. */
  780. Vector2.Zero = function () {
  781. return new Vector2(0, 0);
  782. };
  783. /**
  784. * Returns a new Vector2 set from the passed index element of the passed array or Float32Array.
  785. */
  786. Vector2.FromArray = function (array, offset) {
  787. if (offset === void 0) { offset = 0; }
  788. return new Vector2(array[offset], array[offset + 1]);
  789. };
  790. /**
  791. * Sets "result" from the passed index element of the passed array or Float32Array.
  792. * Returns the Vector2.
  793. */
  794. Vector2.FromArrayToRef = function (array, offset, result) {
  795. result.x = array[offset];
  796. result.y = array[offset + 1];
  797. };
  798. /**
  799. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  800. */
  801. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  802. var squared = amount * amount;
  803. var cubed = amount * squared;
  804. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  805. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  806. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  807. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  808. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  809. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  810. return new Vector2(x, y);
  811. };
  812. /**
  813. * 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".
  814. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  815. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  816. */
  817. Vector2.Clamp = function (value, min, max) {
  818. var x = value.x;
  819. x = (x > max.x) ? max.x : x;
  820. x = (x < min.x) ? min.x : x;
  821. var y = value.y;
  822. y = (y > max.y) ? max.y : y;
  823. y = (y < min.y) ? min.y : y;
  824. return new Vector2(x, y);
  825. };
  826. /**
  827. * Returns a new Vecto2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  828. */
  829. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  830. var squared = amount * amount;
  831. var cubed = amount * squared;
  832. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  833. var part2 = (-2.0 * cubed) + (3.0 * squared);
  834. var part3 = (cubed - (2.0 * squared)) + amount;
  835. var part4 = cubed - squared;
  836. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  837. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  838. return new Vector2(x, y);
  839. };
  840. /**
  841. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  842. */
  843. Vector2.Lerp = function (start, end, amount) {
  844. var x = start.x + ((end.x - start.x) * amount);
  845. var y = start.y + ((end.y - start.y) * amount);
  846. return new Vector2(x, y);
  847. };
  848. /**
  849. * Returns the dot product (float) of the vector "left" and the vector "right".
  850. */
  851. Vector2.Dot = function (left, right) {
  852. return left.x * right.x + left.y * right.y;
  853. };
  854. /**
  855. * Returns a new Vector2 equal to the normalized passed vector.
  856. */
  857. Vector2.Normalize = function (vector) {
  858. var newVector = vector.clone();
  859. newVector.normalize();
  860. return newVector;
  861. };
  862. /**
  863. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  864. */
  865. Vector2.Minimize = function (left, right) {
  866. var x = (left.x < right.x) ? left.x : right.x;
  867. var y = (left.y < right.y) ? left.y : right.y;
  868. return new Vector2(x, y);
  869. };
  870. /**
  871. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  872. */
  873. Vector2.Maximize = function (left, right) {
  874. var x = (left.x > right.x) ? left.x : right.x;
  875. var y = (left.y > right.y) ? left.y : right.y;
  876. return new Vector2(x, y);
  877. };
  878. /**
  879. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  880. */
  881. Vector2.Transform = function (vector, transformation) {
  882. var r = Vector2.Zero();
  883. Vector2.TransformToRef(vector, transformation, r);
  884. return r;
  885. };
  886. /**
  887. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  888. */
  889. Vector2.TransformToRef = function (vector, transformation, result) {
  890. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  891. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  892. result.x = x;
  893. result.y = y;
  894. };
  895. /**
  896. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  897. */
  898. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  899. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  900. var sign = a < 0 ? -1 : 1;
  901. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  902. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  903. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  904. };
  905. /**
  906. * Returns the distance (float) between the vectors "value1" and "value2".
  907. */
  908. Vector2.Distance = function (value1, value2) {
  909. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  910. };
  911. /**
  912. * Returns the squared distance (float) between the vectors "value1" and "value2".
  913. */
  914. Vector2.DistanceSquared = function (value1, value2) {
  915. var x = value1.x - value2.x;
  916. var y = value1.y - value2.y;
  917. return (x * x) + (y * y);
  918. };
  919. /**
  920. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  921. */
  922. Vector2.Center = function (value1, value2) {
  923. var center = value1.add(value2);
  924. center.scaleInPlace(0.5);
  925. return center;
  926. };
  927. /**
  928. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  929. */
  930. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  931. var l2 = Vector2.DistanceSquared(segA, segB);
  932. if (l2 === 0.0) {
  933. return Vector2.Distance(p, segA);
  934. }
  935. var v = segB.subtract(segA);
  936. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  937. var proj = segA.add(v.multiplyByFloats(t, t));
  938. return Vector2.Distance(p, proj);
  939. };
  940. return Vector2;
  941. }());
  942. BABYLON.Vector2 = Vector2;
  943. var Vector3 = (function () {
  944. /**
  945. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  946. * A Vector3 is the main object used in 3D geometry.
  947. * It can represent etiher the coordinates of a point the space, either a direction.
  948. */
  949. function Vector3(x, y, z) {
  950. this.x = x;
  951. this.y = y;
  952. this.z = z;
  953. }
  954. /**
  955. * Returns a string with the Vector3 coordinates.
  956. */
  957. Vector3.prototype.toString = function () {
  958. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  959. };
  960. /**
  961. * Returns the string "Vector3"
  962. */
  963. Vector3.prototype.getClassName = function () {
  964. return "Vector3";
  965. };
  966. /**
  967. * Returns the Vector hash code.
  968. */
  969. Vector3.prototype.getHashCode = function () {
  970. var hash = this.x || 0;
  971. hash = (hash * 397) ^ (this.y || 0);
  972. hash = (hash * 397) ^ (this.z || 0);
  973. return hash;
  974. };
  975. // Operators
  976. /**
  977. * Returns a new array with three elements : the coordinates the Vector3.
  978. */
  979. Vector3.prototype.asArray = function () {
  980. var result = [];
  981. this.toArray(result, 0);
  982. return result;
  983. };
  984. /**
  985. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  986. * Returns the Vector3.
  987. */
  988. Vector3.prototype.toArray = function (array, index) {
  989. if (index === void 0) { index = 0; }
  990. array[index] = this.x;
  991. array[index + 1] = this.y;
  992. array[index + 2] = this.z;
  993. return this;
  994. };
  995. /**
  996. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  997. */
  998. Vector3.prototype.toQuaternion = function () {
  999. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1000. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1001. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1002. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1003. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1004. var cosy = Math.cos(this.y * 0.5);
  1005. var siny = Math.sin(this.y * 0.5);
  1006. result.x = coszMinusx * siny;
  1007. result.y = -sinzMinusx * siny;
  1008. result.z = sinxPlusz * cosy;
  1009. result.w = cosxPlusz * cosy;
  1010. return result;
  1011. };
  1012. /**
  1013. * Adds the passed vector to the current Vector3.
  1014. * Returns the updated Vector3.
  1015. */
  1016. Vector3.prototype.addInPlace = function (otherVector) {
  1017. this.x += otherVector.x;
  1018. this.y += otherVector.y;
  1019. this.z += otherVector.z;
  1020. return this;
  1021. };
  1022. /**
  1023. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1024. */
  1025. Vector3.prototype.add = function (otherVector) {
  1026. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1027. };
  1028. /**
  1029. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1030. * Returns the current Vector3.
  1031. */
  1032. Vector3.prototype.addToRef = function (otherVector, result) {
  1033. result.x = this.x + otherVector.x;
  1034. result.y = this.y + otherVector.y;
  1035. result.z = this.z + otherVector.z;
  1036. return this;
  1037. };
  1038. /**
  1039. * Subtract the passed vector from the current Vector3.
  1040. * Returns the updated Vector3.
  1041. */
  1042. Vector3.prototype.subtractInPlace = function (otherVector) {
  1043. this.x -= otherVector.x;
  1044. this.y -= otherVector.y;
  1045. this.z -= otherVector.z;
  1046. return this;
  1047. };
  1048. /**
  1049. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1050. */
  1051. Vector3.prototype.subtract = function (otherVector) {
  1052. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1053. };
  1054. /**
  1055. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1056. * Returns the current Vector3.
  1057. */
  1058. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1059. result.x = this.x - otherVector.x;
  1060. result.y = this.y - otherVector.y;
  1061. result.z = this.z - otherVector.z;
  1062. return this;
  1063. };
  1064. /**
  1065. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1066. */
  1067. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1068. return new Vector3(this.x - x, this.y - y, this.z - z);
  1069. };
  1070. /**
  1071. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1072. * Returns the current Vector3.
  1073. */
  1074. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1075. result.x = this.x - x;
  1076. result.y = this.y - y;
  1077. result.z = this.z - z;
  1078. return this;
  1079. };
  1080. /**
  1081. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1082. */
  1083. Vector3.prototype.negate = function () {
  1084. return new Vector3(-this.x, -this.y, -this.z);
  1085. };
  1086. /**
  1087. * Multiplies the Vector3 coordinates by the float "scale".
  1088. * Returns the updated Vector3.
  1089. */
  1090. Vector3.prototype.scaleInPlace = function (scale) {
  1091. this.x *= scale;
  1092. this.y *= scale;
  1093. this.z *= scale;
  1094. return this;
  1095. };
  1096. /**
  1097. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1098. */
  1099. Vector3.prototype.scale = function (scale) {
  1100. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1101. };
  1102. /**
  1103. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1104. * Returns the current Vector3.
  1105. */
  1106. Vector3.prototype.scaleToRef = function (scale, result) {
  1107. result.x = this.x * scale;
  1108. result.y = this.y * scale;
  1109. result.z = this.z * scale;
  1110. return this;
  1111. };
  1112. /**
  1113. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1114. */
  1115. Vector3.prototype.equals = function (otherVector) {
  1116. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1117. };
  1118. /**
  1119. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1120. */
  1121. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1122. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1123. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1124. };
  1125. /**
  1126. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1127. */
  1128. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1129. return this.x === x && this.y === y && this.z === z;
  1130. };
  1131. /**
  1132. * Muliplies the current Vector3 coordinates by the passed ones.
  1133. * Returns the updated Vector3.
  1134. */
  1135. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1136. this.x *= otherVector.x;
  1137. this.y *= otherVector.y;
  1138. this.z *= otherVector.z;
  1139. return this;
  1140. };
  1141. /**
  1142. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1143. */
  1144. Vector3.prototype.multiply = function (otherVector) {
  1145. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1146. };
  1147. /**
  1148. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1149. * Returns the current Vector3.
  1150. */
  1151. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1152. result.x = this.x * otherVector.x;
  1153. result.y = this.y * otherVector.y;
  1154. result.z = this.z * otherVector.z;
  1155. return this;
  1156. };
  1157. /**
  1158. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1159. */
  1160. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1161. return new Vector3(this.x * x, this.y * y, this.z * z);
  1162. };
  1163. /**
  1164. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1165. */
  1166. Vector3.prototype.divide = function (otherVector) {
  1167. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1168. };
  1169. /**
  1170. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1171. * Returns the current Vector3.
  1172. */
  1173. Vector3.prototype.divideToRef = function (otherVector, result) {
  1174. result.x = this.x / otherVector.x;
  1175. result.y = this.y / otherVector.y;
  1176. result.z = this.z / otherVector.z;
  1177. return this;
  1178. };
  1179. /**
  1180. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1181. * Returns the updated Vector3.
  1182. */
  1183. Vector3.prototype.MinimizeInPlace = function (other) {
  1184. if (other.x < this.x)
  1185. this.x = other.x;
  1186. if (other.y < this.y)
  1187. this.y = other.y;
  1188. if (other.z < this.z)
  1189. this.z = other.z;
  1190. return this;
  1191. };
  1192. /**
  1193. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1194. * Returns the updated Vector3.
  1195. */
  1196. Vector3.prototype.MaximizeInPlace = function (other) {
  1197. if (other.x > this.x)
  1198. this.x = other.x;
  1199. if (other.y > this.y)
  1200. this.y = other.y;
  1201. if (other.z > this.z)
  1202. this.z = other.z;
  1203. return this;
  1204. };
  1205. // Properties
  1206. /**
  1207. * Returns the length of the Vector3 (float).
  1208. */
  1209. Vector3.prototype.length = function () {
  1210. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1211. };
  1212. /**
  1213. * Returns the squared length of the Vector3 (float).
  1214. */
  1215. Vector3.prototype.lengthSquared = function () {
  1216. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1217. };
  1218. // Methods
  1219. /**
  1220. * Normalize the current Vector3.
  1221. * Returns the updated Vector3.
  1222. */
  1223. Vector3.prototype.normalize = function () {
  1224. var len = this.length();
  1225. if (len === 0 || len === 1.0)
  1226. return this;
  1227. var num = 1.0 / len;
  1228. this.x *= num;
  1229. this.y *= num;
  1230. this.z *= num;
  1231. return this;
  1232. };
  1233. /**
  1234. * Returns a new Vector3 copied from the current Vector3.
  1235. */
  1236. Vector3.prototype.clone = function () {
  1237. return new Vector3(this.x, this.y, this.z);
  1238. };
  1239. /**
  1240. * Copies the passed vector coordinates to the current Vector3 ones.
  1241. * Returns the updated Vector3.
  1242. */
  1243. Vector3.prototype.copyFrom = function (source) {
  1244. this.x = source.x;
  1245. this.y = source.y;
  1246. this.z = source.z;
  1247. return this;
  1248. };
  1249. /**
  1250. * Copies the passed floats to the current Vector3 coordinates.
  1251. * Returns the updated Vector3.
  1252. */
  1253. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1254. this.x = x;
  1255. this.y = y;
  1256. this.z = z;
  1257. return this;
  1258. };
  1259. // Statics
  1260. /**
  1261. *
  1262. */
  1263. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1264. var d0 = Vector3.Dot(vector0, axis) - size;
  1265. var d1 = Vector3.Dot(vector1, axis) - size;
  1266. var s = d0 / (d0 - d1);
  1267. return s;
  1268. };
  1269. /**
  1270. * Returns a new Vector3 set from the index "offset" of the passed array or Float32Array.
  1271. */
  1272. Vector3.FromArray = function (array, offset) {
  1273. if (!offset) {
  1274. offset = 0;
  1275. }
  1276. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1277. };
  1278. /**
  1279. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1280. */
  1281. Vector3.FromFloatArray = function (array, offset) {
  1282. if (!offset) {
  1283. offset = 0;
  1284. }
  1285. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1286. };
  1287. /**
  1288. * Sets the passed vector "result" with the element values from the index "offset" of the passed array or Float32Array.
  1289. */
  1290. Vector3.FromArrayToRef = function (array, offset, result) {
  1291. result.x = array[offset];
  1292. result.y = array[offset + 1];
  1293. result.z = array[offset + 2];
  1294. };
  1295. /**
  1296. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1297. */
  1298. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1299. result.x = array[offset];
  1300. result.y = array[offset + 1];
  1301. result.z = array[offset + 2];
  1302. };
  1303. /**
  1304. * Sets the passed vector "result" with the passed floats.
  1305. */
  1306. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1307. result.x = x;
  1308. result.y = y;
  1309. result.z = z;
  1310. };
  1311. /**
  1312. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1313. */
  1314. Vector3.Zero = function () {
  1315. return new Vector3(0.0, 0.0, 0.0);
  1316. };
  1317. /**
  1318. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1319. */
  1320. Vector3.Up = function () {
  1321. return new Vector3(0.0, 1.0, 0.0);
  1322. };
  1323. /**
  1324. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1325. */
  1326. Vector3.Forward = function () {
  1327. return new Vector3(0.0, 0.0, 1.0);
  1328. };
  1329. /**
  1330. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1331. */
  1332. Vector3.Right = function () {
  1333. return new Vector3(1.0, 0.0, 0.0);
  1334. };
  1335. /**
  1336. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1337. */
  1338. Vector3.Left = function () {
  1339. return new Vector3(-1.0, 0.0, 0.0);
  1340. };
  1341. /**
  1342. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1343. * This method computes tranformed coordinates only, not transformed direction vectors.
  1344. */
  1345. Vector3.TransformCoordinates = function (vector, transformation) {
  1346. var result = Vector3.Zero();
  1347. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1348. return result;
  1349. };
  1350. /**
  1351. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1352. * This method computes tranformed coordinates only, not transformed direction vectors.
  1353. */
  1354. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1355. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1356. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1357. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1358. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1359. result.x = x / w;
  1360. result.y = y / w;
  1361. result.z = z / w;
  1362. };
  1363. /**
  1364. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1365. * This method computes tranformed coordinates only, not transformed direction vectors.
  1366. */
  1367. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1368. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1369. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1370. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1371. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1372. result.x = rx / rw;
  1373. result.y = ry / rw;
  1374. result.z = rz / rw;
  1375. };
  1376. /**
  1377. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1378. * This methods computes transformed normalized direction vectors only.
  1379. */
  1380. Vector3.TransformNormal = function (vector, transformation) {
  1381. var result = Vector3.Zero();
  1382. Vector3.TransformNormalToRef(vector, transformation, result);
  1383. return result;
  1384. };
  1385. /**
  1386. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1387. * This methods computes transformed normalized direction vectors only.
  1388. */
  1389. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1390. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1391. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1392. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1393. result.x = x;
  1394. result.y = y;
  1395. result.z = z;
  1396. };
  1397. /**
  1398. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1399. * This methods computes transformed normalized direction vectors only.
  1400. */
  1401. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1402. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1403. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1404. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1405. };
  1406. /**
  1407. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1408. */
  1409. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1410. var squared = amount * amount;
  1411. var cubed = amount * squared;
  1412. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1413. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1414. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1415. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1416. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1417. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1418. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1419. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1420. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1421. return new Vector3(x, y, z);
  1422. };
  1423. /**
  1424. * 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".
  1425. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1426. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1427. */
  1428. Vector3.Clamp = function (value, min, max) {
  1429. var x = value.x;
  1430. x = (x > max.x) ? max.x : x;
  1431. x = (x < min.x) ? min.x : x;
  1432. var y = value.y;
  1433. y = (y > max.y) ? max.y : y;
  1434. y = (y < min.y) ? min.y : y;
  1435. var z = value.z;
  1436. z = (z > max.z) ? max.z : z;
  1437. z = (z < min.z) ? min.z : z;
  1438. return new Vector3(x, y, z);
  1439. };
  1440. /**
  1441. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1442. */
  1443. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1444. var squared = amount * amount;
  1445. var cubed = amount * squared;
  1446. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1447. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1448. var part3 = (cubed - (2.0 * squared)) + amount;
  1449. var part4 = cubed - squared;
  1450. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1451. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1452. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1453. return new Vector3(x, y, z);
  1454. };
  1455. /**
  1456. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1457. */
  1458. Vector3.Lerp = function (start, end, amount) {
  1459. var result = new Vector3(0, 0, 0);
  1460. Vector3.LerpToRef(start, end, amount, result);
  1461. return result;
  1462. };
  1463. /**
  1464. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1465. */
  1466. Vector3.LerpToRef = function (start, end, amount, result) {
  1467. result.x = start.x + ((end.x - start.x) * amount);
  1468. result.y = start.y + ((end.y - start.y) * amount);
  1469. result.z = start.z + ((end.z - start.z) * amount);
  1470. };
  1471. /**
  1472. * Returns the dot product (float) between the vectors "left" and "right".
  1473. */
  1474. Vector3.Dot = function (left, right) {
  1475. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1476. };
  1477. /**
  1478. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1479. * The cross product is then orthogonal to both "left" and "right".
  1480. */
  1481. Vector3.Cross = function (left, right) {
  1482. var result = Vector3.Zero();
  1483. Vector3.CrossToRef(left, right, result);
  1484. return result;
  1485. };
  1486. /**
  1487. * Sets the passed vector "result" with the cross product of "left" and "right".
  1488. * The cross product is then orthogonal to both "left" and "right".
  1489. */
  1490. Vector3.CrossToRef = function (left, right, result) {
  1491. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1492. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1493. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1494. result.copyFrom(MathTmp.Vector3[0]);
  1495. };
  1496. /**
  1497. * Returns a new Vector3 as the normalization of the passed vector.
  1498. */
  1499. Vector3.Normalize = function (vector) {
  1500. var result = Vector3.Zero();
  1501. Vector3.NormalizeToRef(vector, result);
  1502. return result;
  1503. };
  1504. /**
  1505. * Sets the passed vector "result" with the normalization of the passed first vector.
  1506. */
  1507. Vector3.NormalizeToRef = function (vector, result) {
  1508. result.copyFrom(vector);
  1509. result.normalize();
  1510. };
  1511. Vector3.Project = function (vector, world, transform, viewport) {
  1512. var cw = viewport.width;
  1513. var ch = viewport.height;
  1514. var cx = viewport.x;
  1515. var cy = viewport.y;
  1516. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1517. 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);
  1518. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1519. world.multiplyToRef(transform, matrix);
  1520. matrix.multiplyToRef(viewportMatrix, matrix);
  1521. return Vector3.TransformCoordinates(vector, matrix);
  1522. };
  1523. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1524. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1525. world.multiplyToRef(transform, matrix);
  1526. matrix.invert();
  1527. source.x = source.x / viewportWidth * 2 - 1;
  1528. source.y = -(source.y / viewportHeight * 2 - 1);
  1529. var vector = Vector3.TransformCoordinates(source, matrix);
  1530. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1531. if (MathTools.WithinEpsilon(num, 1.0)) {
  1532. vector = vector.scale(1.0 / num);
  1533. }
  1534. return vector;
  1535. };
  1536. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1537. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1538. world.multiplyToRef(view, matrix);
  1539. matrix.multiplyToRef(projection, matrix);
  1540. matrix.invert();
  1541. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1542. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1543. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1544. if (MathTools.WithinEpsilon(num, 1.0)) {
  1545. vector = vector.scale(1.0 / num);
  1546. }
  1547. return vector;
  1548. };
  1549. Vector3.Minimize = function (left, right) {
  1550. var min = left.clone();
  1551. min.MinimizeInPlace(right);
  1552. return min;
  1553. };
  1554. Vector3.Maximize = function (left, right) {
  1555. var max = left.clone();
  1556. max.MaximizeInPlace(right);
  1557. return max;
  1558. };
  1559. /**
  1560. * Returns the distance (float) between the vectors "value1" and "value2".
  1561. */
  1562. Vector3.Distance = function (value1, value2) {
  1563. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1564. };
  1565. /**
  1566. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1567. */
  1568. Vector3.DistanceSquared = function (value1, value2) {
  1569. var x = value1.x - value2.x;
  1570. var y = value1.y - value2.y;
  1571. var z = value1.z - value2.z;
  1572. return (x * x) + (y * y) + (z * z);
  1573. };
  1574. /**
  1575. * Returns a new Vector3 located at the center between "value1" and "value2".
  1576. */
  1577. Vector3.Center = function (value1, value2) {
  1578. var center = value1.add(value2);
  1579. center.scaleInPlace(0.5);
  1580. return center;
  1581. };
  1582. /**
  1583. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1584. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1585. * to something in order to rotate it from its local system to the given target system.
  1586. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1587. * Returns a new Vector3.
  1588. */
  1589. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1590. var rotation = Vector3.Zero();
  1591. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1592. return rotation;
  1593. };
  1594. /**
  1595. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1596. */
  1597. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1598. var quat = MathTmp.Quaternion[0];
  1599. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1600. quat.toEulerAnglesToRef(ref);
  1601. };
  1602. return Vector3;
  1603. }());
  1604. BABYLON.Vector3 = Vector3;
  1605. //Vector4 class created for EulerAngle class conversion to Quaternion
  1606. var Vector4 = (function () {
  1607. /**
  1608. * Creates a Vector4 object from the passed floats.
  1609. */
  1610. function Vector4(x, y, z, w) {
  1611. this.x = x;
  1612. this.y = y;
  1613. this.z = z;
  1614. this.w = w;
  1615. }
  1616. /**
  1617. * Returns the string with the Vector4 coordinates.
  1618. */
  1619. Vector4.prototype.toString = function () {
  1620. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1621. };
  1622. /**
  1623. * Returns the string "Vector4".
  1624. */
  1625. Vector4.prototype.getClassName = function () {
  1626. return "Vector4";
  1627. };
  1628. /**
  1629. * Returns the Vector4 hash code.
  1630. */
  1631. Vector4.prototype.getHashCode = function () {
  1632. var hash = this.x || 0;
  1633. hash = (hash * 397) ^ (this.y || 0);
  1634. hash = (hash * 397) ^ (this.z || 0);
  1635. hash = (hash * 397) ^ (this.w || 0);
  1636. return hash;
  1637. };
  1638. // Operators
  1639. /**
  1640. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1641. */
  1642. Vector4.prototype.asArray = function () {
  1643. var result = [];
  1644. this.toArray(result, 0);
  1645. return result;
  1646. };
  1647. /**
  1648. * Populates the passed array from the passed index with the Vector4 coordinates.
  1649. * Returns the Vector4.
  1650. */
  1651. Vector4.prototype.toArray = function (array, index) {
  1652. if (index === undefined) {
  1653. index = 0;
  1654. }
  1655. array[index] = this.x;
  1656. array[index + 1] = this.y;
  1657. array[index + 2] = this.z;
  1658. array[index + 3] = this.w;
  1659. return this;
  1660. };
  1661. /**
  1662. * Adds the passed vector to the current Vector4.
  1663. * Returns the updated Vector4.
  1664. */
  1665. Vector4.prototype.addInPlace = function (otherVector) {
  1666. this.x += otherVector.x;
  1667. this.y += otherVector.y;
  1668. this.z += otherVector.z;
  1669. this.w += otherVector.w;
  1670. return this;
  1671. };
  1672. /**
  1673. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1674. */
  1675. Vector4.prototype.add = function (otherVector) {
  1676. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1677. };
  1678. /**
  1679. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1680. * Returns the current Vector4.
  1681. */
  1682. Vector4.prototype.addToRef = function (otherVector, result) {
  1683. result.x = this.x + otherVector.x;
  1684. result.y = this.y + otherVector.y;
  1685. result.z = this.z + otherVector.z;
  1686. result.w = this.w + otherVector.w;
  1687. return this;
  1688. };
  1689. /**
  1690. * Subtract in place the passed vector from the current Vector4.
  1691. * Returns the updated Vector4.
  1692. */
  1693. Vector4.prototype.subtractInPlace = function (otherVector) {
  1694. this.x -= otherVector.x;
  1695. this.y -= otherVector.y;
  1696. this.z -= otherVector.z;
  1697. this.w -= otherVector.w;
  1698. return this;
  1699. };
  1700. /**
  1701. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1702. */
  1703. Vector4.prototype.subtract = function (otherVector) {
  1704. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1705. };
  1706. /**
  1707. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1708. * Returns the current Vector4.
  1709. */
  1710. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1711. result.x = this.x - otherVector.x;
  1712. result.y = this.y - otherVector.y;
  1713. result.z = this.z - otherVector.z;
  1714. result.w = this.w - otherVector.w;
  1715. return this;
  1716. };
  1717. /**
  1718. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1719. */
  1720. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1721. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1722. };
  1723. /**
  1724. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1725. * Returns the current Vector4.
  1726. */
  1727. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1728. result.x = this.x - x;
  1729. result.y = this.y - y;
  1730. result.z = this.z - z;
  1731. result.w = this.w - w;
  1732. return this;
  1733. };
  1734. /**
  1735. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1736. */
  1737. Vector4.prototype.negate = function () {
  1738. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1739. };
  1740. /**
  1741. * Multiplies the current Vector4 coordinates by scale (float).
  1742. * Returns the updated Vector4.
  1743. */
  1744. Vector4.prototype.scaleInPlace = function (scale) {
  1745. this.x *= scale;
  1746. this.y *= scale;
  1747. this.z *= scale;
  1748. this.w *= scale;
  1749. return this;
  1750. };
  1751. /**
  1752. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1753. */
  1754. Vector4.prototype.scale = function (scale) {
  1755. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1756. };
  1757. /**
  1758. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1759. * Returns the current Vector4.
  1760. */
  1761. Vector4.prototype.scaleToRef = function (scale, result) {
  1762. result.x = this.x * scale;
  1763. result.y = this.y * scale;
  1764. result.z = this.z * scale;
  1765. result.w = this.w * scale;
  1766. return this;
  1767. };
  1768. /**
  1769. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1770. */
  1771. Vector4.prototype.equals = function (otherVector) {
  1772. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1773. };
  1774. /**
  1775. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1776. */
  1777. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1778. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1779. return otherVector
  1780. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1781. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1782. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1783. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1784. };
  1785. /**
  1786. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1787. */
  1788. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1789. return this.x === x && this.y === y && this.z === z && this.w === w;
  1790. };
  1791. /**
  1792. * Multiplies in place the current Vector4 by the passed one.
  1793. * Returns the updated Vector4.
  1794. */
  1795. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1796. this.x *= otherVector.x;
  1797. this.y *= otherVector.y;
  1798. this.z *= otherVector.z;
  1799. this.w *= otherVector.w;
  1800. return this;
  1801. };
  1802. /**
  1803. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1804. */
  1805. Vector4.prototype.multiply = function (otherVector) {
  1806. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1807. };
  1808. /**
  1809. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1810. * Returns the current Vector4.
  1811. */
  1812. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1813. result.x = this.x * otherVector.x;
  1814. result.y = this.y * otherVector.y;
  1815. result.z = this.z * otherVector.z;
  1816. result.w = this.w * otherVector.w;
  1817. return this;
  1818. };
  1819. /**
  1820. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1821. */
  1822. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1823. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1824. };
  1825. /**
  1826. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1827. */
  1828. Vector4.prototype.divide = function (otherVector) {
  1829. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1830. };
  1831. /**
  1832. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1833. * Returns the current Vector4.
  1834. */
  1835. Vector4.prototype.divideToRef = function (otherVector, result) {
  1836. result.x = this.x / otherVector.x;
  1837. result.y = this.y / otherVector.y;
  1838. result.z = this.z / otherVector.z;
  1839. result.w = this.w / otherVector.w;
  1840. return this;
  1841. };
  1842. /**
  1843. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1844. */
  1845. Vector4.prototype.MinimizeInPlace = function (other) {
  1846. if (other.x < this.x)
  1847. this.x = other.x;
  1848. if (other.y < this.y)
  1849. this.y = other.y;
  1850. if (other.z < this.z)
  1851. this.z = other.z;
  1852. if (other.w < this.w)
  1853. this.w = other.w;
  1854. return this;
  1855. };
  1856. /**
  1857. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1858. */
  1859. Vector4.prototype.MaximizeInPlace = function (other) {
  1860. if (other.x > this.x)
  1861. this.x = other.x;
  1862. if (other.y > this.y)
  1863. this.y = other.y;
  1864. if (other.z > this.z)
  1865. this.z = other.z;
  1866. if (other.w > this.w)
  1867. this.w = other.w;
  1868. return this;
  1869. };
  1870. // Properties
  1871. /**
  1872. * Returns the Vector4 length (float).
  1873. */
  1874. Vector4.prototype.length = function () {
  1875. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1876. };
  1877. /**
  1878. * Returns the Vector4 squared length (float).
  1879. */
  1880. Vector4.prototype.lengthSquared = function () {
  1881. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1882. };
  1883. // Methods
  1884. /**
  1885. * Normalizes in place the Vector4.
  1886. * Returns the updated Vector4.
  1887. */
  1888. Vector4.prototype.normalize = function () {
  1889. var len = this.length();
  1890. if (len === 0)
  1891. return this;
  1892. var num = 1.0 / len;
  1893. this.x *= num;
  1894. this.y *= num;
  1895. this.z *= num;
  1896. this.w *= num;
  1897. return this;
  1898. };
  1899. /**
  1900. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1901. */
  1902. Vector4.prototype.toVector3 = function () {
  1903. return new Vector3(this.x, this.y, this.z);
  1904. };
  1905. /**
  1906. * Returns a new Vector4 copied from the current one.
  1907. */
  1908. Vector4.prototype.clone = function () {
  1909. return new Vector4(this.x, this.y, this.z, this.w);
  1910. };
  1911. /**
  1912. * Updates the current Vector4 with the passed one coordinates.
  1913. * Returns the updated Vector4.
  1914. */
  1915. Vector4.prototype.copyFrom = function (source) {
  1916. this.x = source.x;
  1917. this.y = source.y;
  1918. this.z = source.z;
  1919. this.w = source.w;
  1920. return this;
  1921. };
  1922. /**
  1923. * Updates the current Vector4 coordinates with the passed floats.
  1924. * Returns the updated Vector4.
  1925. */
  1926. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1927. this.x = x;
  1928. this.y = y;
  1929. this.z = z;
  1930. this.w = w;
  1931. return this;
  1932. };
  1933. // Statics
  1934. /**
  1935. * Returns a new Vector4 set from the starting index of the passed array.
  1936. */
  1937. Vector4.FromArray = function (array, offset) {
  1938. if (!offset) {
  1939. offset = 0;
  1940. }
  1941. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1942. };
  1943. /**
  1944. * Updates the passed vector "result" from the starting index of the passed array.
  1945. */
  1946. Vector4.FromArrayToRef = function (array, offset, result) {
  1947. result.x = array[offset];
  1948. result.y = array[offset + 1];
  1949. result.z = array[offset + 2];
  1950. result.w = array[offset + 3];
  1951. };
  1952. /**
  1953. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  1954. */
  1955. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1956. result.x = array[offset];
  1957. result.y = array[offset + 1];
  1958. result.z = array[offset + 2];
  1959. result.w = array[offset + 3];
  1960. };
  1961. /**
  1962. * Updates the passed vector "result" coordinates from the passed floats.
  1963. */
  1964. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1965. result.x = x;
  1966. result.y = y;
  1967. result.z = z;
  1968. result.w = w;
  1969. };
  1970. /**
  1971. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  1972. */
  1973. Vector4.Zero = function () {
  1974. return new Vector4(0.0, 0.0, 0.0, 0.0);
  1975. };
  1976. /**
  1977. * Returns a new normalized Vector4 from the passed one.
  1978. */
  1979. Vector4.Normalize = function (vector) {
  1980. var result = Vector4.Zero();
  1981. Vector4.NormalizeToRef(vector, result);
  1982. return result;
  1983. };
  1984. /**
  1985. * Updates the passed vector "result" from the normalization of the passed one.
  1986. */
  1987. Vector4.NormalizeToRef = function (vector, result) {
  1988. result.copyFrom(vector);
  1989. result.normalize();
  1990. };
  1991. Vector4.Minimize = function (left, right) {
  1992. var min = left.clone();
  1993. min.MinimizeInPlace(right);
  1994. return min;
  1995. };
  1996. Vector4.Maximize = function (left, right) {
  1997. var max = left.clone();
  1998. max.MaximizeInPlace(right);
  1999. return max;
  2000. };
  2001. /**
  2002. * Returns the distance (float) between the vectors "value1" and "value2".
  2003. */
  2004. Vector4.Distance = function (value1, value2) {
  2005. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2006. };
  2007. Vector4.DistanceSquared = function (value1, value2) {
  2008. var x = value1.x - value2.x;
  2009. var y = value1.y - value2.y;
  2010. var z = value1.z - value2.z;
  2011. var w = value1.w - value2.w;
  2012. return (x * x) + (y * y) + (z * z) + (w * w);
  2013. };
  2014. /**
  2015. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2016. */
  2017. Vector4.Center = function (value1, value2) {
  2018. var center = value1.add(value2);
  2019. center.scaleInPlace(0.5);
  2020. return center;
  2021. };
  2022. return Vector4;
  2023. }());
  2024. BABYLON.Vector4 = Vector4;
  2025. var Size = (function () {
  2026. /**
  2027. * Creates a Size object from the passed width and height (floats).
  2028. */
  2029. function Size(width, height) {
  2030. this.width = width;
  2031. this.height = height;
  2032. }
  2033. // Returns a string with the Size width and height.
  2034. Size.prototype.toString = function () {
  2035. return "{W: " + this.width + ", H: " + this.height + "}";
  2036. };
  2037. /**
  2038. * Returns the string "Size"
  2039. */
  2040. Size.prototype.getClassName = function () {
  2041. return "Size";
  2042. };
  2043. /**
  2044. * Returns the Size hash code.
  2045. */
  2046. Size.prototype.getHashCode = function () {
  2047. var hash = this.width || 0;
  2048. hash = (hash * 397) ^ (this.height || 0);
  2049. return hash;
  2050. };
  2051. /**
  2052. * Updates the current size from the passed one.
  2053. * Returns the updated Size.
  2054. */
  2055. Size.prototype.copyFrom = function (src) {
  2056. this.width = src.width;
  2057. this.height = src.height;
  2058. };
  2059. /**
  2060. * Updates in place the current Size from the passed floats.
  2061. * Returns the updated Size.
  2062. */
  2063. Size.prototype.copyFromFloats = function (width, height) {
  2064. this.width = width;
  2065. this.height = height;
  2066. return this;
  2067. };
  2068. /**
  2069. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2070. */
  2071. Size.prototype.multiplyByFloats = function (w, h) {
  2072. return new Size(this.width * w, this.height * h);
  2073. };
  2074. /**
  2075. * Returns a new Size copied from the passed one.
  2076. */
  2077. Size.prototype.clone = function () {
  2078. return new Size(this.width, this.height);
  2079. };
  2080. /**
  2081. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2082. */
  2083. Size.prototype.equals = function (other) {
  2084. if (!other) {
  2085. return false;
  2086. }
  2087. return (this.width === other.width) && (this.height === other.height);
  2088. };
  2089. Object.defineProperty(Size.prototype, "surface", {
  2090. /**
  2091. * Returns the surface of the Size : width * height (float).
  2092. */
  2093. get: function () {
  2094. return this.width * this.height;
  2095. },
  2096. enumerable: true,
  2097. configurable: true
  2098. });
  2099. /**
  2100. * Returns a new Size set to (0.0, 0.0)
  2101. */
  2102. Size.Zero = function () {
  2103. return new Size(0.0, 0.0);
  2104. };
  2105. /**
  2106. * Returns a new Size set as the addition result of the current Size and the passed one.
  2107. */
  2108. Size.prototype.add = function (otherSize) {
  2109. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2110. return r;
  2111. };
  2112. /**
  2113. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2114. */
  2115. Size.prototype.subtract = function (otherSize) {
  2116. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2117. return r;
  2118. };
  2119. /**
  2120. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2121. */
  2122. Size.Lerp = function (start, end, amount) {
  2123. var w = start.width + ((end.width - start.width) * amount);
  2124. var h = start.height + ((end.height - start.height) * amount);
  2125. return new Size(w, h);
  2126. };
  2127. return Size;
  2128. }());
  2129. BABYLON.Size = Size;
  2130. var Quaternion = (function () {
  2131. /**
  2132. * Creates a new Quaternion from the passed floats.
  2133. */
  2134. function Quaternion(x, y, z, w) {
  2135. if (x === void 0) { x = 0.0; }
  2136. if (y === void 0) { y = 0.0; }
  2137. if (z === void 0) { z = 0.0; }
  2138. if (w === void 0) { w = 1.0; }
  2139. this.x = x;
  2140. this.y = y;
  2141. this.z = z;
  2142. this.w = w;
  2143. }
  2144. /**
  2145. * Returns a string with the Quaternion coordinates.
  2146. */
  2147. Quaternion.prototype.toString = function () {
  2148. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2149. };
  2150. /**
  2151. * Returns the string "Quaternion".
  2152. */
  2153. Quaternion.prototype.getClassName = function () {
  2154. return "Quaternion";
  2155. };
  2156. /**
  2157. * Returns the Quaternion hash code.
  2158. */
  2159. Quaternion.prototype.getHashCode = function () {
  2160. var hash = this.x || 0;
  2161. hash = (hash * 397) ^ (this.y || 0);
  2162. hash = (hash * 397) ^ (this.z || 0);
  2163. hash = (hash * 397) ^ (this.w || 0);
  2164. return hash;
  2165. };
  2166. /**
  2167. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2168. */
  2169. Quaternion.prototype.asArray = function () {
  2170. return [this.x, this.y, this.z, this.w];
  2171. };
  2172. /**
  2173. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2174. */
  2175. Quaternion.prototype.equals = function (otherQuaternion) {
  2176. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2177. };
  2178. /**
  2179. * Returns a new Quaternion copied from the current one.
  2180. */
  2181. Quaternion.prototype.clone = function () {
  2182. return new Quaternion(this.x, this.y, this.z, this.w);
  2183. };
  2184. /**
  2185. * Updates the current Quaternion from the passed one coordinates.
  2186. * Returns the updated Quaterion.
  2187. */
  2188. Quaternion.prototype.copyFrom = function (other) {
  2189. this.x = other.x;
  2190. this.y = other.y;
  2191. this.z = other.z;
  2192. this.w = other.w;
  2193. return this;
  2194. };
  2195. /**
  2196. * Updates the current Quaternion from the passed float coordinates.
  2197. * Returns the updated Quaterion.
  2198. */
  2199. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2200. this.x = x;
  2201. this.y = y;
  2202. this.z = z;
  2203. this.w = w;
  2204. return this;
  2205. };
  2206. /**
  2207. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2208. */
  2209. Quaternion.prototype.add = function (other) {
  2210. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2211. };
  2212. /**
  2213. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2214. */
  2215. Quaternion.prototype.subtract = function (other) {
  2216. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2217. };
  2218. /**
  2219. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2220. */
  2221. Quaternion.prototype.scale = function (value) {
  2222. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2223. };
  2224. /**
  2225. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2226. */
  2227. Quaternion.prototype.multiply = function (q1) {
  2228. var result = new Quaternion(0, 0, 0, 1.0);
  2229. this.multiplyToRef(q1, result);
  2230. return result;
  2231. };
  2232. /**
  2233. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2234. * Returns the current Quaternion.
  2235. */
  2236. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2237. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2238. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2239. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2240. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2241. result.copyFromFloats(x, y, z, w);
  2242. return this;
  2243. };
  2244. /**
  2245. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2246. * Returns the updated Quaternion.
  2247. */
  2248. Quaternion.prototype.multiplyInPlace = function (q1) {
  2249. this.multiplyToRef(q1, this);
  2250. return this;
  2251. };
  2252. /**
  2253. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2254. * Returns the current Quaternion.
  2255. */
  2256. Quaternion.prototype.conjugateToRef = function (ref) {
  2257. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2258. return this;
  2259. };
  2260. /**
  2261. * Conjugates in place the current Quaternion.
  2262. * Returns the updated Quaternion.
  2263. */
  2264. Quaternion.prototype.conjugateInPlace = function () {
  2265. this.x *= -1;
  2266. this.y *= -1;
  2267. this.z *= -1;
  2268. return this;
  2269. };
  2270. /**
  2271. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2272. */
  2273. Quaternion.prototype.conjugate = function () {
  2274. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2275. return result;
  2276. };
  2277. /**
  2278. * Returns the Quaternion length (float).
  2279. */
  2280. Quaternion.prototype.length = function () {
  2281. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2282. };
  2283. /**
  2284. * Normalize in place the current Quaternion.
  2285. * Returns the updated Quaternion.
  2286. */
  2287. Quaternion.prototype.normalize = function () {
  2288. var length = 1.0 / this.length();
  2289. this.x *= length;
  2290. this.y *= length;
  2291. this.z *= length;
  2292. this.w *= length;
  2293. return this;
  2294. };
  2295. /**
  2296. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2297. */
  2298. Quaternion.prototype.toEulerAngles = function (order) {
  2299. if (order === void 0) { order = "YZX"; }
  2300. var result = Vector3.Zero();
  2301. this.toEulerAnglesToRef(result, order);
  2302. return result;
  2303. };
  2304. /**
  2305. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2306. * Returns the current Quaternion.
  2307. */
  2308. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2309. if (order === void 0) { order = "YZX"; }
  2310. var qz = this.z;
  2311. var qx = this.x;
  2312. var qy = this.y;
  2313. var qw = this.w;
  2314. var sqw = qw * qw;
  2315. var sqz = qz * qz;
  2316. var sqx = qx * qx;
  2317. var sqy = qy * qy;
  2318. var zAxisY = qy * qz - qx * qw;
  2319. var limit = .4999999;
  2320. if (zAxisY < -limit) {
  2321. result.y = 2 * Math.atan2(qy, qw);
  2322. result.x = Math.PI / 2;
  2323. result.z = 0;
  2324. }
  2325. else if (zAxisY > limit) {
  2326. result.y = 2 * Math.atan2(qy, qw);
  2327. result.x = -Math.PI / 2;
  2328. result.z = 0;
  2329. }
  2330. else {
  2331. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2332. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2333. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2334. }
  2335. return this;
  2336. };
  2337. /**
  2338. * Updates the passed rotation matrix with the current Quaternion values.
  2339. * Returns the current Quaternion.
  2340. */
  2341. Quaternion.prototype.toRotationMatrix = function (result) {
  2342. var xx = this.x * this.x;
  2343. var yy = this.y * this.y;
  2344. var zz = this.z * this.z;
  2345. var xy = this.x * this.y;
  2346. var zw = this.z * this.w;
  2347. var zx = this.z * this.x;
  2348. var yw = this.y * this.w;
  2349. var yz = this.y * this.z;
  2350. var xw = this.x * this.w;
  2351. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2352. result.m[1] = 2.0 * (xy + zw);
  2353. result.m[2] = 2.0 * (zx - yw);
  2354. result.m[3] = 0;
  2355. result.m[4] = 2.0 * (xy - zw);
  2356. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2357. result.m[6] = 2.0 * (yz + xw);
  2358. result.m[7] = 0;
  2359. result.m[8] = 2.0 * (zx + yw);
  2360. result.m[9] = 2.0 * (yz - xw);
  2361. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2362. result.m[11] = 0;
  2363. result.m[12] = 0;
  2364. result.m[13] = 0;
  2365. result.m[14] = 0;
  2366. result.m[15] = 1.0;
  2367. return this;
  2368. };
  2369. /**
  2370. * Updates the current Quaternion from the passed rotation matrix values.
  2371. * Returns the updated Quaternion.
  2372. */
  2373. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2374. Quaternion.FromRotationMatrixToRef(matrix, this);
  2375. return this;
  2376. };
  2377. // Statics
  2378. /**
  2379. * Returns a new Quaternion set from the passed rotation matrix values.
  2380. */
  2381. Quaternion.FromRotationMatrix = function (matrix) {
  2382. var result = new Quaternion();
  2383. Quaternion.FromRotationMatrixToRef(matrix, result);
  2384. return result;
  2385. };
  2386. /**
  2387. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2388. */
  2389. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2390. var data = matrix.m;
  2391. var m11 = data[0], m12 = data[4], m13 = data[8];
  2392. var m21 = data[1], m22 = data[5], m23 = data[9];
  2393. var m31 = data[2], m32 = data[6], m33 = data[10];
  2394. var trace = m11 + m22 + m33;
  2395. var s;
  2396. if (trace > 0) {
  2397. s = 0.5 / Math.sqrt(trace + 1.0);
  2398. result.w = 0.25 / s;
  2399. result.x = (m32 - m23) * s;
  2400. result.y = (m13 - m31) * s;
  2401. result.z = (m21 - m12) * s;
  2402. }
  2403. else if (m11 > m22 && m11 > m33) {
  2404. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2405. result.w = (m32 - m23) / s;
  2406. result.x = 0.25 * s;
  2407. result.y = (m12 + m21) / s;
  2408. result.z = (m13 + m31) / s;
  2409. }
  2410. else if (m22 > m33) {
  2411. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2412. result.w = (m13 - m31) / s;
  2413. result.x = (m12 + m21) / s;
  2414. result.y = 0.25 * s;
  2415. result.z = (m23 + m32) / s;
  2416. }
  2417. else {
  2418. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2419. result.w = (m21 - m12) / s;
  2420. result.x = (m13 + m31) / s;
  2421. result.y = (m23 + m32) / s;
  2422. result.z = 0.25 * s;
  2423. }
  2424. };
  2425. /**
  2426. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2427. */
  2428. Quaternion.Zero = function () {
  2429. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2430. };
  2431. /**
  2432. * Returns a new Quaternion as the inverted current Quaternion.
  2433. */
  2434. Quaternion.Inverse = function (q) {
  2435. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2436. };
  2437. /**
  2438. * Returns the identity Quaternion.
  2439. */
  2440. Quaternion.Identity = function () {
  2441. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2442. };
  2443. /**
  2444. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2445. */
  2446. Quaternion.RotationAxis = function (axis, angle) {
  2447. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2448. };
  2449. /**
  2450. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2451. */
  2452. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2453. var sin = Math.sin(angle / 2);
  2454. axis.normalize();
  2455. result.w = Math.cos(angle / 2);
  2456. result.x = axis.x * sin;
  2457. result.y = axis.y * sin;
  2458. result.z = axis.z * sin;
  2459. return result;
  2460. };
  2461. /**
  2462. * Retuns a new Quaternion set from the starting index of the passed array.
  2463. */
  2464. Quaternion.FromArray = function (array, offset) {
  2465. if (!offset) {
  2466. offset = 0;
  2467. }
  2468. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2469. };
  2470. /**
  2471. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2472. */
  2473. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2474. var q = new Quaternion();
  2475. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2476. return q;
  2477. };
  2478. /**
  2479. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2480. */
  2481. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2482. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2483. var halfRoll = roll * 0.5;
  2484. var halfPitch = pitch * 0.5;
  2485. var halfYaw = yaw * 0.5;
  2486. var sinRoll = Math.sin(halfRoll);
  2487. var cosRoll = Math.cos(halfRoll);
  2488. var sinPitch = Math.sin(halfPitch);
  2489. var cosPitch = Math.cos(halfPitch);
  2490. var sinYaw = Math.sin(halfYaw);
  2491. var cosYaw = Math.cos(halfYaw);
  2492. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2493. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2494. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2495. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2496. };
  2497. /**
  2498. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2499. */
  2500. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2501. var result = new Quaternion();
  2502. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2503. return result;
  2504. };
  2505. /**
  2506. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2507. */
  2508. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2509. // Produces a quaternion from Euler angles in the z-x-z orientation
  2510. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2511. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2512. var halfBeta = beta * 0.5;
  2513. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2514. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2515. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2516. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2517. };
  2518. /**
  2519. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2520. * cf to Vector3.RotationFromAxis() documentation.
  2521. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2522. */
  2523. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2524. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2525. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2526. return quat;
  2527. };
  2528. /**
  2529. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2530. * cf to Vector3.RotationFromAxis() documentation.
  2531. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2532. */
  2533. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2534. var rotMat = MathTmp.Matrix[0];
  2535. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2536. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2537. };
  2538. Quaternion.Slerp = function (left, right, amount) {
  2539. var result = Quaternion.Identity();
  2540. Quaternion.SlerpToRef(left, right, amount, result);
  2541. return result;
  2542. };
  2543. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2544. var num2;
  2545. var num3;
  2546. var num = amount;
  2547. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2548. var flag = false;
  2549. if (num4 < 0) {
  2550. flag = true;
  2551. num4 = -num4;
  2552. }
  2553. if (num4 > 0.999999) {
  2554. num3 = 1 - num;
  2555. num2 = flag ? -num : num;
  2556. }
  2557. else {
  2558. var num5 = Math.acos(num4);
  2559. var num6 = (1.0 / Math.sin(num5));
  2560. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2561. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2562. }
  2563. result.x = (num3 * left.x) + (num2 * right.x);
  2564. result.y = (num3 * left.y) + (num2 * right.y);
  2565. result.z = (num3 * left.z) + (num2 * right.z);
  2566. result.w = (num3 * left.w) + (num2 * right.w);
  2567. };
  2568. return Quaternion;
  2569. }());
  2570. BABYLON.Quaternion = Quaternion;
  2571. var Matrix = (function () {
  2572. function Matrix() {
  2573. this.m = new Float32Array(16);
  2574. }
  2575. // Properties
  2576. /**
  2577. * Boolean : True is the matrix is the identity matrix
  2578. */
  2579. Matrix.prototype.isIdentity = function () {
  2580. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2581. return false;
  2582. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2583. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2584. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2585. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2586. return false;
  2587. return true;
  2588. };
  2589. /**
  2590. * Returns the matrix determinant (float).
  2591. */
  2592. Matrix.prototype.determinant = function () {
  2593. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2594. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2595. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2596. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2597. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2598. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2599. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2600. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2601. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2602. };
  2603. // Methods
  2604. /**
  2605. * Returns the matrix underlying array.
  2606. */
  2607. Matrix.prototype.toArray = function () {
  2608. return this.m;
  2609. };
  2610. /**
  2611. * Returns the matrix underlying array.
  2612. */
  2613. Matrix.prototype.asArray = function () {
  2614. return this.toArray();
  2615. };
  2616. /**
  2617. * Inverts in place the Matrix.
  2618. * Returns the Matrix inverted.
  2619. */
  2620. Matrix.prototype.invert = function () {
  2621. this.invertToRef(this);
  2622. return this;
  2623. };
  2624. /**
  2625. * Sets all the matrix elements to zero.
  2626. * Returns the Matrix.
  2627. */
  2628. Matrix.prototype.reset = function () {
  2629. for (var index = 0; index < 16; index++) {
  2630. this.m[index] = 0.0;
  2631. }
  2632. return this;
  2633. };
  2634. /**
  2635. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2636. */
  2637. Matrix.prototype.add = function (other) {
  2638. var result = new Matrix();
  2639. this.addToRef(other, result);
  2640. return result;
  2641. };
  2642. /**
  2643. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2644. * Returns the Matrix.
  2645. */
  2646. Matrix.prototype.addToRef = function (other, result) {
  2647. for (var index = 0; index < 16; index++) {
  2648. result.m[index] = this.m[index] + other.m[index];
  2649. }
  2650. return this;
  2651. };
  2652. /**
  2653. * Adds in place the passed matrix to the current Matrix.
  2654. * Returns the updated Matrix.
  2655. */
  2656. Matrix.prototype.addToSelf = function (other) {
  2657. for (var index = 0; index < 16; index++) {
  2658. this.m[index] += other.m[index];
  2659. }
  2660. return this;
  2661. };
  2662. /**
  2663. * Sets the passed matrix with the current inverted Matrix.
  2664. * Returns the unmodified current Matrix.
  2665. */
  2666. Matrix.prototype.invertToRef = function (other) {
  2667. var l1 = this.m[0];
  2668. var l2 = this.m[1];
  2669. var l3 = this.m[2];
  2670. var l4 = this.m[3];
  2671. var l5 = this.m[4];
  2672. var l6 = this.m[5];
  2673. var l7 = this.m[6];
  2674. var l8 = this.m[7];
  2675. var l9 = this.m[8];
  2676. var l10 = this.m[9];
  2677. var l11 = this.m[10];
  2678. var l12 = this.m[11];
  2679. var l13 = this.m[12];
  2680. var l14 = this.m[13];
  2681. var l15 = this.m[14];
  2682. var l16 = this.m[15];
  2683. var l17 = (l11 * l16) - (l12 * l15);
  2684. var l18 = (l10 * l16) - (l12 * l14);
  2685. var l19 = (l10 * l15) - (l11 * l14);
  2686. var l20 = (l9 * l16) - (l12 * l13);
  2687. var l21 = (l9 * l15) - (l11 * l13);
  2688. var l22 = (l9 * l14) - (l10 * l13);
  2689. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2690. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2691. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2692. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2693. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2694. var l28 = (l7 * l16) - (l8 * l15);
  2695. var l29 = (l6 * l16) - (l8 * l14);
  2696. var l30 = (l6 * l15) - (l7 * l14);
  2697. var l31 = (l5 * l16) - (l8 * l13);
  2698. var l32 = (l5 * l15) - (l7 * l13);
  2699. var l33 = (l5 * l14) - (l6 * l13);
  2700. var l34 = (l7 * l12) - (l8 * l11);
  2701. var l35 = (l6 * l12) - (l8 * l10);
  2702. var l36 = (l6 * l11) - (l7 * l10);
  2703. var l37 = (l5 * l12) - (l8 * l9);
  2704. var l38 = (l5 * l11) - (l7 * l9);
  2705. var l39 = (l5 * l10) - (l6 * l9);
  2706. other.m[0] = l23 * l27;
  2707. other.m[4] = l24 * l27;
  2708. other.m[8] = l25 * l27;
  2709. other.m[12] = l26 * l27;
  2710. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2711. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2712. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2713. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2714. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2715. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2716. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2717. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2718. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2719. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2720. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2721. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2722. return this;
  2723. };
  2724. /**
  2725. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2726. * Returns the updated Matrix.
  2727. */
  2728. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2729. this.m[12] = x;
  2730. this.m[13] = y;
  2731. this.m[14] = z;
  2732. return this;
  2733. };
  2734. /**
  2735. * Inserts the translation vector in the current Matrix.
  2736. * Returns the updated Matrix.
  2737. */
  2738. Matrix.prototype.setTranslation = function (vector3) {
  2739. this.m[12] = vector3.x;
  2740. this.m[13] = vector3.y;
  2741. this.m[14] = vector3.z;
  2742. return this;
  2743. };
  2744. /**
  2745. * Returns a new Vector3 as the extracted translation from the Matrix.
  2746. */
  2747. Matrix.prototype.getTranslation = function () {
  2748. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2749. };
  2750. /**
  2751. * Fill a Vector3 with the extracted translation from the Matrix.
  2752. */
  2753. Matrix.prototype.getTranslationToRef = function (result) {
  2754. result.x = this.m[12];
  2755. result.y = this.m[13];
  2756. result.z = this.m[14];
  2757. return this;
  2758. };
  2759. /**
  2760. * Remove rotation and scaling part from the Matrix.
  2761. * Returns the updated Matrix.
  2762. */
  2763. Matrix.prototype.removeRotationAndScaling = function () {
  2764. this.setRowFromFloats(0, 1, 0, 0, 0);
  2765. this.setRowFromFloats(1, 0, 1, 0, 0);
  2766. this.setRowFromFloats(2, 0, 0, 1, 0);
  2767. return this;
  2768. };
  2769. /**
  2770. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2771. */
  2772. Matrix.prototype.multiply = function (other) {
  2773. var result = new Matrix();
  2774. this.multiplyToRef(other, result);
  2775. return result;
  2776. };
  2777. /**
  2778. * Updates the current Matrix from the passed one values.
  2779. * Returns the updated Matrix.
  2780. */
  2781. Matrix.prototype.copyFrom = function (other) {
  2782. for (var index = 0; index < 16; index++) {
  2783. this.m[index] = other.m[index];
  2784. }
  2785. return this;
  2786. };
  2787. /**
  2788. * Populates the passed array from the starting index with the Matrix values.
  2789. * Returns the Matrix.
  2790. */
  2791. Matrix.prototype.copyToArray = function (array, offset) {
  2792. if (offset === void 0) { offset = 0; }
  2793. for (var index = 0; index < 16; index++) {
  2794. array[offset + index] = this.m[index];
  2795. }
  2796. return this;
  2797. };
  2798. /**
  2799. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2800. */
  2801. Matrix.prototype.multiplyToRef = function (other, result) {
  2802. this.multiplyToArray(other, result.m, 0);
  2803. return this;
  2804. };
  2805. /**
  2806. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2807. */
  2808. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2809. var tm0 = this.m[0];
  2810. var tm1 = this.m[1];
  2811. var tm2 = this.m[2];
  2812. var tm3 = this.m[3];
  2813. var tm4 = this.m[4];
  2814. var tm5 = this.m[5];
  2815. var tm6 = this.m[6];
  2816. var tm7 = this.m[7];
  2817. var tm8 = this.m[8];
  2818. var tm9 = this.m[9];
  2819. var tm10 = this.m[10];
  2820. var tm11 = this.m[11];
  2821. var tm12 = this.m[12];
  2822. var tm13 = this.m[13];
  2823. var tm14 = this.m[14];
  2824. var tm15 = this.m[15];
  2825. var om0 = other.m[0];
  2826. var om1 = other.m[1];
  2827. var om2 = other.m[2];
  2828. var om3 = other.m[3];
  2829. var om4 = other.m[4];
  2830. var om5 = other.m[5];
  2831. var om6 = other.m[6];
  2832. var om7 = other.m[7];
  2833. var om8 = other.m[8];
  2834. var om9 = other.m[9];
  2835. var om10 = other.m[10];
  2836. var om11 = other.m[11];
  2837. var om12 = other.m[12];
  2838. var om13 = other.m[13];
  2839. var om14 = other.m[14];
  2840. var om15 = other.m[15];
  2841. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2842. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2843. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2844. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2845. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2846. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2847. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2848. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2849. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2850. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2851. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  2852. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  2853. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  2854. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  2855. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  2856. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  2857. return this;
  2858. };
  2859. /**
  2860. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  2861. */
  2862. Matrix.prototype.equals = function (value) {
  2863. return value &&
  2864. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  2865. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  2866. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  2867. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  2868. };
  2869. /**
  2870. * Returns a new Matrix from the current Matrix.
  2871. */
  2872. Matrix.prototype.clone = function () {
  2873. 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]);
  2874. };
  2875. /**
  2876. * Returns the string "Matrix"
  2877. */
  2878. Matrix.prototype.getClassName = function () {
  2879. return "Matrix";
  2880. };
  2881. /**
  2882. * Returns the Matrix hash code.
  2883. */
  2884. Matrix.prototype.getHashCode = function () {
  2885. var hash = this.m[0] || 0;
  2886. for (var i = 1; i < 16; i++) {
  2887. hash = (hash * 397) ^ (this.m[i] || 0);
  2888. }
  2889. return hash;
  2890. };
  2891. /**
  2892. * Decomposes the current Matrix into :
  2893. * - a scale vector3 passed as a reference to update,
  2894. * - a rotation quaternion passed as a reference to update,
  2895. * - a translation vector3 passed as a reference to update.
  2896. * Returns the boolean `true`.
  2897. */
  2898. Matrix.prototype.decompose = function (scale, rotation, translation) {
  2899. translation.x = this.m[12];
  2900. translation.y = this.m[13];
  2901. translation.z = this.m[14];
  2902. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  2903. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  2904. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  2905. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  2906. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  2907. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  2908. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  2909. rotation.x = 0;
  2910. rotation.y = 0;
  2911. rotation.z = 0;
  2912. rotation.w = 1;
  2913. return false;
  2914. }
  2915. 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]);
  2916. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  2917. return true;
  2918. };
  2919. /**
  2920. * Returns a new Matrix as the extracted rotation matrix from the current one.
  2921. */
  2922. Matrix.prototype.getRotationMatrix = function () {
  2923. var result = Matrix.Identity();
  2924. this.getRotationMatrixToRef(result);
  2925. return result;
  2926. };
  2927. /**
  2928. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  2929. * Returns the current Matrix.
  2930. */
  2931. Matrix.prototype.getRotationMatrixToRef = function (result) {
  2932. var m = this.m;
  2933. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  2934. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  2935. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  2936. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  2937. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  2938. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  2939. 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);
  2940. return this;
  2941. };
  2942. // Statics
  2943. /**
  2944. * Returns a new Matrix set from the starting index of the passed array.
  2945. */
  2946. Matrix.FromArray = function (array, offset) {
  2947. var result = new Matrix();
  2948. if (!offset) {
  2949. offset = 0;
  2950. }
  2951. Matrix.FromArrayToRef(array, offset, result);
  2952. return result;
  2953. };
  2954. /**
  2955. * Sets the passed "result" matrix from the starting index of the passed array.
  2956. */
  2957. Matrix.FromArrayToRef = function (array, offset, result) {
  2958. for (var index = 0; index < 16; index++) {
  2959. result.m[index] = array[index + offset];
  2960. }
  2961. };
  2962. /**
  2963. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  2964. */
  2965. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2966. for (var index = 0; index < 16; index++) {
  2967. result.m[index] = array[index + offset] * scale;
  2968. }
  2969. };
  2970. /**
  2971. * Sets the passed matrix "result" with the 16 passed floats.
  2972. */
  2973. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2974. result.m[0] = initialM11;
  2975. result.m[1] = initialM12;
  2976. result.m[2] = initialM13;
  2977. result.m[3] = initialM14;
  2978. result.m[4] = initialM21;
  2979. result.m[5] = initialM22;
  2980. result.m[6] = initialM23;
  2981. result.m[7] = initialM24;
  2982. result.m[8] = initialM31;
  2983. result.m[9] = initialM32;
  2984. result.m[10] = initialM33;
  2985. result.m[11] = initialM34;
  2986. result.m[12] = initialM41;
  2987. result.m[13] = initialM42;
  2988. result.m[14] = initialM43;
  2989. result.m[15] = initialM44;
  2990. };
  2991. /**
  2992. * Returns the index-th row of the current matrix as a new Vector4.
  2993. */
  2994. Matrix.prototype.getRow = function (index) {
  2995. if (index < 0 || index > 3) {
  2996. return null;
  2997. }
  2998. var i = index * 4;
  2999. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3000. };
  3001. /**
  3002. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3003. * Returns the updated Matrix.
  3004. */
  3005. Matrix.prototype.setRow = function (index, row) {
  3006. if (index < 0 || index > 3) {
  3007. return this;
  3008. }
  3009. var i = index * 4;
  3010. this.m[i + 0] = row.x;
  3011. this.m[i + 1] = row.y;
  3012. this.m[i + 2] = row.z;
  3013. this.m[i + 3] = row.w;
  3014. return this;
  3015. };
  3016. /**
  3017. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3018. * Returns the updated Matrix.
  3019. */
  3020. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3021. if (index < 0 || index > 3) {
  3022. return this;
  3023. }
  3024. var i = index * 4;
  3025. this.m[i + 0] = x;
  3026. this.m[i + 1] = y;
  3027. this.m[i + 2] = z;
  3028. this.m[i + 3] = w;
  3029. return this;
  3030. };
  3031. /**
  3032. * Returns a new Matrix set from the 16 passed floats.
  3033. */
  3034. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3035. var result = new Matrix();
  3036. result.m[0] = initialM11;
  3037. result.m[1] = initialM12;
  3038. result.m[2] = initialM13;
  3039. result.m[3] = initialM14;
  3040. result.m[4] = initialM21;
  3041. result.m[5] = initialM22;
  3042. result.m[6] = initialM23;
  3043. result.m[7] = initialM24;
  3044. result.m[8] = initialM31;
  3045. result.m[9] = initialM32;
  3046. result.m[10] = initialM33;
  3047. result.m[11] = initialM34;
  3048. result.m[12] = initialM41;
  3049. result.m[13] = initialM42;
  3050. result.m[14] = initialM43;
  3051. result.m[15] = initialM44;
  3052. return result;
  3053. };
  3054. /**
  3055. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3056. */
  3057. Matrix.Compose = function (scale, rotation, translation) {
  3058. var result = Matrix.Identity();
  3059. Matrix.ComposeToRef(scale, rotation, translation, result);
  3060. return result;
  3061. };
  3062. /**
  3063. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3064. */
  3065. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3066. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3067. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3068. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3069. result.setTranslation(translation);
  3070. };
  3071. /**
  3072. * Returns a new indentity Matrix.
  3073. */
  3074. Matrix.Identity = function () {
  3075. 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);
  3076. };
  3077. /**
  3078. * Sets the passed "result" as an identity matrix.
  3079. */
  3080. Matrix.IdentityToRef = function (result) {
  3081. 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);
  3082. };
  3083. /**
  3084. * Returns a new zero Matrix.
  3085. */
  3086. Matrix.Zero = function () {
  3087. 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);
  3088. };
  3089. /**
  3090. * Returns a new rotation matrix for "angle" radians around the X axis.
  3091. */
  3092. Matrix.RotationX = function (angle) {
  3093. var result = new Matrix();
  3094. Matrix.RotationXToRef(angle, result);
  3095. return result;
  3096. };
  3097. /**
  3098. * Returns a new Matrix as the passed inverted one.
  3099. */
  3100. Matrix.Invert = function (source) {
  3101. var result = new Matrix();
  3102. source.invertToRef(result);
  3103. return result;
  3104. };
  3105. /**
  3106. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3107. */
  3108. Matrix.RotationXToRef = function (angle, result) {
  3109. var s = Math.sin(angle);
  3110. var c = Math.cos(angle);
  3111. result.m[0] = 1.0;
  3112. result.m[15] = 1.0;
  3113. result.m[5] = c;
  3114. result.m[10] = c;
  3115. result.m[9] = -s;
  3116. result.m[6] = s;
  3117. result.m[1] = 0.0;
  3118. result.m[2] = 0.0;
  3119. result.m[3] = 0.0;
  3120. result.m[4] = 0.0;
  3121. result.m[7] = 0.0;
  3122. result.m[8] = 0.0;
  3123. result.m[11] = 0.0;
  3124. result.m[12] = 0.0;
  3125. result.m[13] = 0.0;
  3126. result.m[14] = 0.0;
  3127. };
  3128. /**
  3129. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3130. */
  3131. Matrix.RotationY = function (angle) {
  3132. var result = new Matrix();
  3133. Matrix.RotationYToRef(angle, result);
  3134. return result;
  3135. };
  3136. /**
  3137. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3138. */
  3139. Matrix.RotationYToRef = function (angle, result) {
  3140. var s = Math.sin(angle);
  3141. var c = Math.cos(angle);
  3142. result.m[5] = 1.0;
  3143. result.m[15] = 1.0;
  3144. result.m[0] = c;
  3145. result.m[2] = -s;
  3146. result.m[8] = s;
  3147. result.m[10] = c;
  3148. result.m[1] = 0.0;
  3149. result.m[3] = 0.0;
  3150. result.m[4] = 0.0;
  3151. result.m[6] = 0.0;
  3152. result.m[7] = 0.0;
  3153. result.m[9] = 0.0;
  3154. result.m[11] = 0.0;
  3155. result.m[12] = 0.0;
  3156. result.m[13] = 0.0;
  3157. result.m[14] = 0.0;
  3158. };
  3159. /**
  3160. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3161. */
  3162. Matrix.RotationZ = function (angle) {
  3163. var result = new Matrix();
  3164. Matrix.RotationZToRef(angle, result);
  3165. return result;
  3166. };
  3167. /**
  3168. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3169. */
  3170. Matrix.RotationZToRef = function (angle, result) {
  3171. var s = Math.sin(angle);
  3172. var c = Math.cos(angle);
  3173. result.m[10] = 1.0;
  3174. result.m[15] = 1.0;
  3175. result.m[0] = c;
  3176. result.m[1] = s;
  3177. result.m[4] = -s;
  3178. result.m[5] = c;
  3179. result.m[2] = 0.0;
  3180. result.m[3] = 0.0;
  3181. result.m[6] = 0.0;
  3182. result.m[7] = 0.0;
  3183. result.m[8] = 0.0;
  3184. result.m[9] = 0.0;
  3185. result.m[11] = 0.0;
  3186. result.m[12] = 0.0;
  3187. result.m[13] = 0.0;
  3188. result.m[14] = 0.0;
  3189. };
  3190. /**
  3191. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3192. */
  3193. Matrix.RotationAxis = function (axis, angle) {
  3194. var result = Matrix.Zero();
  3195. Matrix.RotationAxisToRef(axis, angle, result);
  3196. return result;
  3197. };
  3198. /**
  3199. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3200. */
  3201. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3202. var s = Math.sin(-angle);
  3203. var c = Math.cos(-angle);
  3204. var c1 = 1 - c;
  3205. axis.normalize();
  3206. result.m[0] = (axis.x * axis.x) * c1 + c;
  3207. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3208. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3209. result.m[3] = 0.0;
  3210. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3211. result.m[5] = (axis.y * axis.y) * c1 + c;
  3212. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3213. result.m[7] = 0.0;
  3214. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3215. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3216. result.m[10] = (axis.z * axis.z) * c1 + c;
  3217. result.m[11] = 0.0;
  3218. result.m[15] = 1.0;
  3219. };
  3220. /**
  3221. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3222. */
  3223. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3224. var result = new Matrix();
  3225. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3226. return result;
  3227. };
  3228. /**
  3229. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3230. */
  3231. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3232. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3233. this._tempQuaternion.toRotationMatrix(result);
  3234. };
  3235. /**
  3236. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3237. */
  3238. Matrix.Scaling = function (x, y, z) {
  3239. var result = Matrix.Zero();
  3240. Matrix.ScalingToRef(x, y, z, result);
  3241. return result;
  3242. };
  3243. /**
  3244. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3245. */
  3246. Matrix.ScalingToRef = function (x, y, z, result) {
  3247. result.m[0] = x;
  3248. result.m[1] = 0.0;
  3249. result.m[2] = 0.0;
  3250. result.m[3] = 0.0;
  3251. result.m[4] = 0.0;
  3252. result.m[5] = y;
  3253. result.m[6] = 0.0;
  3254. result.m[7] = 0.0;
  3255. result.m[8] = 0.0;
  3256. result.m[9] = 0.0;
  3257. result.m[10] = z;
  3258. result.m[11] = 0.0;
  3259. result.m[12] = 0.0;
  3260. result.m[13] = 0.0;
  3261. result.m[14] = 0.0;
  3262. result.m[15] = 1.0;
  3263. };
  3264. /**
  3265. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3266. */
  3267. Matrix.Translation = function (x, y, z) {
  3268. var result = Matrix.Identity();
  3269. Matrix.TranslationToRef(x, y, z, result);
  3270. return result;
  3271. };
  3272. /**
  3273. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3274. */
  3275. Matrix.TranslationToRef = function (x, y, z, result) {
  3276. 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);
  3277. };
  3278. /**
  3279. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3280. */
  3281. Matrix.Lerp = function (startValue, endValue, gradient) {
  3282. var result = Matrix.Zero();
  3283. for (var index = 0; index < 16; index++) {
  3284. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3285. }
  3286. return result;
  3287. };
  3288. /**
  3289. * Returns a new Matrix whose values are computed by :
  3290. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3291. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3292. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3293. */
  3294. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3295. var startScale = new Vector3(0, 0, 0);
  3296. var startRotation = new Quaternion();
  3297. var startTranslation = new Vector3(0, 0, 0);
  3298. startValue.decompose(startScale, startRotation, startTranslation);
  3299. var endScale = new Vector3(0, 0, 0);
  3300. var endRotation = new Quaternion();
  3301. var endTranslation = new Vector3(0, 0, 0);
  3302. endValue.decompose(endScale, endRotation, endTranslation);
  3303. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3304. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3305. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3306. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3307. };
  3308. /**
  3309. * 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".
  3310. * This methods works for a Left-Handed system.
  3311. */
  3312. Matrix.LookAtLH = function (eye, target, up) {
  3313. var result = Matrix.Zero();
  3314. Matrix.LookAtLHToRef(eye, target, up, result);
  3315. return result;
  3316. };
  3317. /**
  3318. * 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".
  3319. * This methods works for a Left-Handed system.
  3320. */
  3321. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3322. // Z axis
  3323. target.subtractToRef(eye, this._zAxis);
  3324. this._zAxis.normalize();
  3325. // X axis
  3326. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3327. if (this._xAxis.lengthSquared() === 0) {
  3328. this._xAxis.x = 1.0;
  3329. }
  3330. else {
  3331. this._xAxis.normalize();
  3332. }
  3333. // Y axis
  3334. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3335. this._yAxis.normalize();
  3336. // Eye angles
  3337. var ex = -Vector3.Dot(this._xAxis, eye);
  3338. var ey = -Vector3.Dot(this._yAxis, eye);
  3339. var ez = -Vector3.Dot(this._zAxis, eye);
  3340. 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);
  3341. };
  3342. /**
  3343. * 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".
  3344. * This methods works for a Right-Handed system.
  3345. */
  3346. Matrix.LookAtRH = function (eye, target, up) {
  3347. var result = Matrix.Zero();
  3348. Matrix.LookAtRHToRef(eye, target, up, result);
  3349. return result;
  3350. };
  3351. /**
  3352. * 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".
  3353. * This methods works for a Left-Handed system.
  3354. */
  3355. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3356. // Z axis
  3357. eye.subtractToRef(target, this._zAxis);
  3358. this._zAxis.normalize();
  3359. // X axis
  3360. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3361. if (this._xAxis.lengthSquared() === 0) {
  3362. this._xAxis.x = 1.0;
  3363. }
  3364. else {
  3365. this._xAxis.normalize();
  3366. }
  3367. // Y axis
  3368. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3369. this._yAxis.normalize();
  3370. // Eye angles
  3371. var ex = -Vector3.Dot(this._xAxis, eye);
  3372. var ey = -Vector3.Dot(this._yAxis, eye);
  3373. var ez = -Vector3.Dot(this._zAxis, eye);
  3374. 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);
  3375. };
  3376. /**
  3377. * 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.
  3378. */
  3379. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3380. var matrix = Matrix.Zero();
  3381. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3382. return matrix;
  3383. };
  3384. /**
  3385. * 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.
  3386. */
  3387. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3388. var n = znear;
  3389. var f = zfar;
  3390. var a = 2.0 / width;
  3391. var b = 2.0 / height;
  3392. var c = 2.0 / (f - n);
  3393. var d = -(f + n) / (f - n);
  3394. 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);
  3395. };
  3396. /**
  3397. * 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.
  3398. */
  3399. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3400. var matrix = Matrix.Zero();
  3401. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3402. return matrix;
  3403. };
  3404. /**
  3405. * 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.
  3406. */
  3407. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3408. var n = znear;
  3409. var f = zfar;
  3410. var a = 2.0 / (right - left);
  3411. var b = 2.0 / (top - bottom);
  3412. var c = 2.0 / (f - n);
  3413. var d = -(f + n) / (f - n);
  3414. var i0 = (left + right) / (left - right);
  3415. var i1 = (top + bottom) / (bottom - top);
  3416. 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);
  3417. };
  3418. /**
  3419. * 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.
  3420. */
  3421. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3422. var matrix = Matrix.Zero();
  3423. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3424. return matrix;
  3425. };
  3426. /**
  3427. * 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.
  3428. */
  3429. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3430. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3431. result.m[10] *= -1.0;
  3432. };
  3433. /**
  3434. * 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.
  3435. */
  3436. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3437. var matrix = Matrix.Zero();
  3438. var n = znear;
  3439. var f = zfar;
  3440. var a = 2.0 * n / width;
  3441. var b = 2.0 * n / height;
  3442. var c = (f + n) / (f - n);
  3443. var d = -2.0 * f * n / (f - n);
  3444. 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);
  3445. return matrix;
  3446. };
  3447. /**
  3448. * 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.
  3449. */
  3450. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3451. var matrix = Matrix.Zero();
  3452. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3453. return matrix;
  3454. };
  3455. /**
  3456. * 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.
  3457. */
  3458. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3459. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3460. var n = znear;
  3461. var f = zfar;
  3462. var t = 1.0 / (Math.tan(fov * 0.5));
  3463. var a = isVerticalFovFixed ? (t / aspect) : t;
  3464. var b = isVerticalFovFixed ? t : (t * aspect);
  3465. var c = (f + n) / (f - n);
  3466. var d = -2.0 * f * n / (f - n);
  3467. 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);
  3468. };
  3469. /**
  3470. * 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.
  3471. */
  3472. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3473. var matrix = Matrix.Zero();
  3474. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3475. return matrix;
  3476. };
  3477. /**
  3478. * 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.
  3479. */
  3480. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3481. //alternatively this could be expressed as:
  3482. // m = PerspectiveFovLHToRef
  3483. // m[10] *= -1.0;
  3484. // m[11] *= -1.0;
  3485. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3486. var n = znear;
  3487. var f = zfar;
  3488. var t = 1.0 / (Math.tan(fov * 0.5));
  3489. var a = isVerticalFovFixed ? (t / aspect) : t;
  3490. var b = isVerticalFovFixed ? t : (t * aspect);
  3491. var c = -(f + n) / (f - n);
  3492. var d = -2 * f * n / (f - n);
  3493. 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);
  3494. };
  3495. /**
  3496. * 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.
  3497. */
  3498. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  3499. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3500. //left handed
  3501. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3502. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3503. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3504. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3505. var xScale = 2.0 / (leftTan + rightTan);
  3506. var yScale = 2.0 / (upTan + downTan);
  3507. result.m[0] = xScale;
  3508. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3509. result.m[5] = yScale;
  3510. result.m[6] = result.m[7] = 0.0;
  3511. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  3512. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  3513. result.m[10] = -(znear + zfar) / (zfar - znear);
  3514. // result.m[10] = -zfar / (znear - zfar);
  3515. result.m[11] = 1.0;
  3516. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3517. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3518. // result.m[14] = (znear * zfar) / (znear - zfar);
  3519. };
  3520. /**
  3521. * Returns the final transformation matrix : world * view * projection * viewport
  3522. */
  3523. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3524. var cw = viewport.width;
  3525. var ch = viewport.height;
  3526. var cx = viewport.x;
  3527. var cy = viewport.y;
  3528. 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);
  3529. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3530. };
  3531. /**
  3532. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3533. */
  3534. Matrix.GetAsMatrix2x2 = function (matrix) {
  3535. return new Float32Array([
  3536. matrix.m[0], matrix.m[1],
  3537. matrix.m[4], matrix.m[5]
  3538. ]);
  3539. };
  3540. /**
  3541. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3542. */
  3543. Matrix.GetAsMatrix3x3 = function (matrix) {
  3544. return new Float32Array([
  3545. matrix.m[0], matrix.m[1], matrix.m[2],
  3546. matrix.m[4], matrix.m[5], matrix.m[6],
  3547. matrix.m[8], matrix.m[9], matrix.m[10]
  3548. ]);
  3549. };
  3550. /**
  3551. * Compute the transpose of the passed Matrix.
  3552. * Returns a new Matrix.
  3553. */
  3554. Matrix.Transpose = function (matrix) {
  3555. var result = new Matrix();
  3556. result.m[0] = matrix.m[0];
  3557. result.m[1] = matrix.m[4];
  3558. result.m[2] = matrix.m[8];
  3559. result.m[3] = matrix.m[12];
  3560. result.m[4] = matrix.m[1];
  3561. result.m[5] = matrix.m[5];
  3562. result.m[6] = matrix.m[9];
  3563. result.m[7] = matrix.m[13];
  3564. result.m[8] = matrix.m[2];
  3565. result.m[9] = matrix.m[6];
  3566. result.m[10] = matrix.m[10];
  3567. result.m[11] = matrix.m[14];
  3568. result.m[12] = matrix.m[3];
  3569. result.m[13] = matrix.m[7];
  3570. result.m[14] = matrix.m[11];
  3571. result.m[15] = matrix.m[15];
  3572. return result;
  3573. };
  3574. /**
  3575. * Returns a new Matrix as the reflection matrix across the passed plane.
  3576. */
  3577. Matrix.Reflection = function (plane) {
  3578. var matrix = new Matrix();
  3579. Matrix.ReflectionToRef(plane, matrix);
  3580. return matrix;
  3581. };
  3582. /**
  3583. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3584. */
  3585. Matrix.ReflectionToRef = function (plane, result) {
  3586. plane.normalize();
  3587. var x = plane.normal.x;
  3588. var y = plane.normal.y;
  3589. var z = plane.normal.z;
  3590. var temp = -2 * x;
  3591. var temp2 = -2 * y;
  3592. var temp3 = -2 * z;
  3593. result.m[0] = (temp * x) + 1;
  3594. result.m[1] = temp2 * x;
  3595. result.m[2] = temp3 * x;
  3596. result.m[3] = 0.0;
  3597. result.m[4] = temp * y;
  3598. result.m[5] = (temp2 * y) + 1;
  3599. result.m[6] = temp3 * y;
  3600. result.m[7] = 0.0;
  3601. result.m[8] = temp * z;
  3602. result.m[9] = temp2 * z;
  3603. result.m[10] = (temp3 * z) + 1;
  3604. result.m[11] = 0.0;
  3605. result.m[12] = temp * plane.d;
  3606. result.m[13] = temp2 * plane.d;
  3607. result.m[14] = temp3 * plane.d;
  3608. result.m[15] = 1.0;
  3609. };
  3610. /**
  3611. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3612. */
  3613. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  3614. mat.m[0] = xaxis.x;
  3615. mat.m[1] = xaxis.y;
  3616. mat.m[2] = xaxis.z;
  3617. mat.m[3] = 0.0;
  3618. mat.m[4] = yaxis.x;
  3619. mat.m[5] = yaxis.y;
  3620. mat.m[6] = yaxis.z;
  3621. mat.m[7] = 0.0;
  3622. mat.m[8] = zaxis.x;
  3623. mat.m[9] = zaxis.y;
  3624. mat.m[10] = zaxis.z;
  3625. mat.m[11] = 0.0;
  3626. mat.m[12] = 0.0;
  3627. mat.m[13] = 0.0;
  3628. mat.m[14] = 0.0;
  3629. mat.m[15] = 1.0;
  3630. };
  3631. /**
  3632. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3633. */
  3634. Matrix.FromQuaternionToRef = function (quat, result) {
  3635. var xx = quat.x * quat.x;
  3636. var yy = quat.y * quat.y;
  3637. var zz = quat.z * quat.z;
  3638. var xy = quat.x * quat.y;
  3639. var zw = quat.z * quat.w;
  3640. var zx = quat.z * quat.x;
  3641. var yw = quat.y * quat.w;
  3642. var yz = quat.y * quat.z;
  3643. var xw = quat.x * quat.w;
  3644. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3645. result.m[1] = 2.0 * (xy + zw);
  3646. result.m[2] = 2.0 * (zx - yw);
  3647. result.m[3] = 0.0;
  3648. result.m[4] = 2.0 * (xy - zw);
  3649. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3650. result.m[6] = 2.0 * (yz + xw);
  3651. result.m[7] = 0.0;
  3652. result.m[8] = 2.0 * (zx + yw);
  3653. result.m[9] = 2.0 * (yz - xw);
  3654. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3655. result.m[11] = 0.0;
  3656. result.m[12] = 0.0;
  3657. result.m[13] = 0.0;
  3658. result.m[14] = 0.0;
  3659. result.m[15] = 1.0;
  3660. };
  3661. return Matrix;
  3662. }());
  3663. Matrix._tempQuaternion = new Quaternion();
  3664. Matrix._xAxis = Vector3.Zero();
  3665. Matrix._yAxis = Vector3.Zero();
  3666. Matrix._zAxis = Vector3.Zero();
  3667. BABYLON.Matrix = Matrix;
  3668. var Plane = (function () {
  3669. /**
  3670. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3671. */
  3672. function Plane(a, b, c, d) {
  3673. this.normal = new Vector3(a, b, c);
  3674. this.d = d;
  3675. }
  3676. /**
  3677. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3678. */
  3679. Plane.prototype.asArray = function () {
  3680. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3681. };
  3682. // Methods
  3683. /**
  3684. * Returns a new plane copied from the current Plane.
  3685. */
  3686. Plane.prototype.clone = function () {
  3687. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3688. };
  3689. /**
  3690. * Returns the string "Plane".
  3691. */
  3692. Plane.prototype.getClassName = function () {
  3693. return "Plane";
  3694. };
  3695. /**
  3696. * Returns the Plane hash code.
  3697. */
  3698. Plane.prototype.getHashCode = function () {
  3699. var hash = this.normal.getHashCode();
  3700. hash = (hash * 397) ^ (this.d || 0);
  3701. return hash;
  3702. };
  3703. /**
  3704. * Normalize the current Plane in place.
  3705. * Returns the updated Plane.
  3706. */
  3707. Plane.prototype.normalize = function () {
  3708. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3709. var magnitude = 0.0;
  3710. if (norm !== 0) {
  3711. magnitude = 1.0 / norm;
  3712. }
  3713. this.normal.x *= magnitude;
  3714. this.normal.y *= magnitude;
  3715. this.normal.z *= magnitude;
  3716. this.d *= magnitude;
  3717. return this;
  3718. };
  3719. /**
  3720. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3721. */
  3722. Plane.prototype.transform = function (transformation) {
  3723. var transposedMatrix = Matrix.Transpose(transformation);
  3724. var x = this.normal.x;
  3725. var y = this.normal.y;
  3726. var z = this.normal.z;
  3727. var d = this.d;
  3728. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3729. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3730. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3731. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3732. return new Plane(normalX, normalY, normalZ, finalD);
  3733. };
  3734. /**
  3735. * Returns the dot product (float) of the point coordinates and the plane normal.
  3736. */
  3737. Plane.prototype.dotCoordinate = function (point) {
  3738. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3739. };
  3740. /**
  3741. * Updates the current Plane from the plane defined by the three passed points.
  3742. * Returns the updated Plane.
  3743. */
  3744. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3745. var x1 = point2.x - point1.x;
  3746. var y1 = point2.y - point1.y;
  3747. var z1 = point2.z - point1.z;
  3748. var x2 = point3.x - point1.x;
  3749. var y2 = point3.y - point1.y;
  3750. var z2 = point3.z - point1.z;
  3751. var yz = (y1 * z2) - (z1 * y2);
  3752. var xz = (z1 * x2) - (x1 * z2);
  3753. var xy = (x1 * y2) - (y1 * x2);
  3754. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3755. var invPyth;
  3756. if (pyth !== 0) {
  3757. invPyth = 1.0 / pyth;
  3758. }
  3759. else {
  3760. invPyth = 0.0;
  3761. }
  3762. this.normal.x = yz * invPyth;
  3763. this.normal.y = xz * invPyth;
  3764. this.normal.z = xy * invPyth;
  3765. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3766. return this;
  3767. };
  3768. /**
  3769. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3770. */
  3771. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3772. var dot = Vector3.Dot(this.normal, direction);
  3773. return (dot <= epsilon);
  3774. };
  3775. /**
  3776. * Returns the signed distance (float) from the passed point to the Plane.
  3777. */
  3778. Plane.prototype.signedDistanceTo = function (point) {
  3779. return Vector3.Dot(point, this.normal) + this.d;
  3780. };
  3781. // Statics
  3782. /**
  3783. * Returns a new Plane from the passed array.
  3784. */
  3785. Plane.FromArray = function (array) {
  3786. return new Plane(array[0], array[1], array[2], array[3]);
  3787. };
  3788. /**
  3789. * Returns a new Plane defined by the three passed points.
  3790. */
  3791. Plane.FromPoints = function (point1, point2, point3) {
  3792. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3793. result.copyFromPoints(point1, point2, point3);
  3794. return result;
  3795. };
  3796. /**
  3797. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3798. * Note : the vector "normal" is updated because normalized.
  3799. */
  3800. Plane.FromPositionAndNormal = function (origin, normal) {
  3801. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3802. normal.normalize();
  3803. result.normal = normal;
  3804. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3805. return result;
  3806. };
  3807. /**
  3808. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3809. */
  3810. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3811. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3812. return Vector3.Dot(point, normal) + d;
  3813. };
  3814. return Plane;
  3815. }());
  3816. BABYLON.Plane = Plane;
  3817. var Viewport = (function () {
  3818. /**
  3819. * Creates a Viewport object located at (x, y) and sized (width, height).
  3820. */
  3821. function Viewport(x, y, width, height) {
  3822. this.x = x;
  3823. this.y = y;
  3824. this.width = width;
  3825. this.height = height;
  3826. }
  3827. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3828. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3829. };
  3830. /**
  3831. * Returns a new Viewport copied from the current one.
  3832. */
  3833. Viewport.prototype.clone = function () {
  3834. return new Viewport(this.x, this.y, this.width, this.height);
  3835. };
  3836. return Viewport;
  3837. }());
  3838. BABYLON.Viewport = Viewport;
  3839. var Frustum = (function () {
  3840. function Frustum() {
  3841. }
  3842. /**
  3843. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  3844. */
  3845. Frustum.GetPlanes = function (transform) {
  3846. var frustumPlanes = [];
  3847. for (var index = 0; index < 6; index++) {
  3848. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  3849. }
  3850. Frustum.GetPlanesToRef(transform, frustumPlanes);
  3851. return frustumPlanes;
  3852. };
  3853. /**
  3854. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  3855. */
  3856. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  3857. // Near
  3858. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  3859. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  3860. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  3861. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  3862. frustumPlanes[0].normalize();
  3863. // Far
  3864. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  3865. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  3866. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  3867. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  3868. frustumPlanes[1].normalize();
  3869. // Left
  3870. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  3871. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  3872. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  3873. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  3874. frustumPlanes[2].normalize();
  3875. // Right
  3876. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  3877. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  3878. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  3879. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  3880. frustumPlanes[3].normalize();
  3881. // Top
  3882. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  3883. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  3884. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  3885. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  3886. frustumPlanes[4].normalize();
  3887. // Bottom
  3888. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  3889. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  3890. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  3891. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  3892. frustumPlanes[5].normalize();
  3893. };
  3894. return Frustum;
  3895. }());
  3896. BABYLON.Frustum = Frustum;
  3897. var Space;
  3898. (function (Space) {
  3899. Space[Space["LOCAL"] = 0] = "LOCAL";
  3900. Space[Space["WORLD"] = 1] = "WORLD";
  3901. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  3902. var Axis = (function () {
  3903. function Axis() {
  3904. }
  3905. return Axis;
  3906. }());
  3907. Axis.X = new Vector3(1.0, 0.0, 0.0);
  3908. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  3909. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  3910. BABYLON.Axis = Axis;
  3911. ;
  3912. var BezierCurve = (function () {
  3913. function BezierCurve() {
  3914. }
  3915. /**
  3916. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  3917. */
  3918. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  3919. // Extract X (which is equal to time here)
  3920. var f0 = 1 - 3 * x2 + 3 * x1;
  3921. var f1 = 3 * x2 - 6 * x1;
  3922. var f2 = 3 * x1;
  3923. var refinedT = t;
  3924. for (var i = 0; i < 5; i++) {
  3925. var refinedT2 = refinedT * refinedT;
  3926. var refinedT3 = refinedT2 * refinedT;
  3927. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  3928. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  3929. refinedT -= (x - t) * slope;
  3930. refinedT = Math.min(1, Math.max(0, refinedT));
  3931. }
  3932. // Resolve cubic bezier for the given x
  3933. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  3934. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  3935. Math.pow(refinedT, 3);
  3936. };
  3937. return BezierCurve;
  3938. }());
  3939. BABYLON.BezierCurve = BezierCurve;
  3940. var Orientation;
  3941. (function (Orientation) {
  3942. Orientation[Orientation["CW"] = 0] = "CW";
  3943. Orientation[Orientation["CCW"] = 1] = "CCW";
  3944. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  3945. var Angle = (function () {
  3946. /**
  3947. * Creates an Angle object of "radians" radians (float).
  3948. */
  3949. function Angle(radians) {
  3950. var _this = this;
  3951. /**
  3952. * Returns the Angle value in degrees (float).
  3953. */
  3954. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  3955. /**
  3956. * Returns the Angle value in radians (float).
  3957. */
  3958. this.radians = function () { return _this._radians; };
  3959. this._radians = radians;
  3960. if (this._radians < 0.0)
  3961. this._radians += (2.0 * Math.PI);
  3962. }
  3963. /**
  3964. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  3965. */
  3966. Angle.BetweenTwoPoints = function (a, b) {
  3967. var delta = b.subtract(a);
  3968. var theta = Math.atan2(delta.y, delta.x);
  3969. return new Angle(theta);
  3970. };
  3971. /**
  3972. * Returns a new Angle object from the passed float in radians.
  3973. */
  3974. Angle.FromRadians = function (radians) {
  3975. return new Angle(radians);
  3976. };
  3977. /**
  3978. * Returns a new Angle object from the passed float in degrees.
  3979. */
  3980. Angle.FromDegrees = function (degrees) {
  3981. return new Angle(degrees * Math.PI / 180.0);
  3982. };
  3983. return Angle;
  3984. }());
  3985. BABYLON.Angle = Angle;
  3986. var Arc2 = (function () {
  3987. /**
  3988. * Creates an Arc object from the three passed points : start, middle and end.
  3989. */
  3990. function Arc2(startPoint, midPoint, endPoint) {
  3991. this.startPoint = startPoint;
  3992. this.midPoint = midPoint;
  3993. this.endPoint = endPoint;
  3994. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  3995. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  3996. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  3997. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  3998. 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);
  3999. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4000. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4001. var a1 = this.startAngle.degrees();
  4002. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4003. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4004. // angles correction
  4005. if (a2 - a1 > +180.0)
  4006. a2 -= 360.0;
  4007. if (a2 - a1 < -180.0)
  4008. a2 += 360.0;
  4009. if (a3 - a2 > +180.0)
  4010. a3 -= 360.0;
  4011. if (a3 - a2 < -180.0)
  4012. a3 += 360.0;
  4013. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4014. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4015. }
  4016. return Arc2;
  4017. }());
  4018. BABYLON.Arc2 = Arc2;
  4019. var Path2 = (function () {
  4020. /**
  4021. * Creates a Path2 object from the starting 2D coordinates x and y.
  4022. */
  4023. function Path2(x, y) {
  4024. this._points = new Array();
  4025. this._length = 0.0;
  4026. this.closed = false;
  4027. this._points.push(new Vector2(x, y));
  4028. }
  4029. /**
  4030. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4031. * Returns the updated Path2.
  4032. */
  4033. Path2.prototype.addLineTo = function (x, y) {
  4034. if (closed) {
  4035. //Tools.Error("cannot add lines to closed paths");
  4036. return this;
  4037. }
  4038. var newPoint = new Vector2(x, y);
  4039. var previousPoint = this._points[this._points.length - 1];
  4040. this._points.push(newPoint);
  4041. this._length += newPoint.subtract(previousPoint).length();
  4042. return this;
  4043. };
  4044. /**
  4045. * 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.
  4046. * Returns the updated Path2.
  4047. */
  4048. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4049. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4050. if (closed) {
  4051. //Tools.Error("cannot add arcs to closed paths");
  4052. return this;
  4053. }
  4054. var startPoint = this._points[this._points.length - 1];
  4055. var midPoint = new Vector2(midX, midY);
  4056. var endPoint = new Vector2(endX, endY);
  4057. var arc = new Arc2(startPoint, midPoint, endPoint);
  4058. var increment = arc.angle.radians() / numberOfSegments;
  4059. if (arc.orientation === Orientation.CW)
  4060. increment *= -1;
  4061. var currentAngle = arc.startAngle.radians() + increment;
  4062. for (var i = 0; i < numberOfSegments; i++) {
  4063. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4064. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4065. this.addLineTo(x, y);
  4066. currentAngle += increment;
  4067. }
  4068. return this;
  4069. };
  4070. /**
  4071. * Closes the Path2.
  4072. * Returns the Path2.
  4073. */
  4074. Path2.prototype.close = function () {
  4075. this.closed = true;
  4076. return this;
  4077. };
  4078. /**
  4079. * Returns the Path2 total length (float).
  4080. */
  4081. Path2.prototype.length = function () {
  4082. var result = this._length;
  4083. if (!this.closed) {
  4084. var lastPoint = this._points[this._points.length - 1];
  4085. var firstPoint = this._points[0];
  4086. result += (firstPoint.subtract(lastPoint).length());
  4087. }
  4088. return result;
  4089. };
  4090. /**
  4091. * Returns the Path2 internal array of points.
  4092. */
  4093. Path2.prototype.getPoints = function () {
  4094. return this._points;
  4095. };
  4096. /**
  4097. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4098. */
  4099. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4100. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4101. //Tools.Error("normalized length position should be between 0 and 1.");
  4102. return Vector2.Zero();
  4103. }
  4104. var lengthPosition = normalizedLengthPosition * this.length();
  4105. var previousOffset = 0;
  4106. for (var i = 0; i < this._points.length; i++) {
  4107. var j = (i + 1) % this._points.length;
  4108. var a = this._points[i];
  4109. var b = this._points[j];
  4110. var bToA = b.subtract(a);
  4111. var nextOffset = (bToA.length() + previousOffset);
  4112. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4113. var dir = bToA.normalize();
  4114. var localOffset = lengthPosition - previousOffset;
  4115. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4116. }
  4117. previousOffset = nextOffset;
  4118. }
  4119. //Tools.Error("internal error");
  4120. return Vector2.Zero();
  4121. };
  4122. /**
  4123. * Returns a new Path2 starting at the coordinates (x, y).
  4124. */
  4125. Path2.StartingAt = function (x, y) {
  4126. return new Path2(x, y);
  4127. };
  4128. return Path2;
  4129. }());
  4130. BABYLON.Path2 = Path2;
  4131. var Path3D = (function () {
  4132. /**
  4133. * new Path3D(path, normal, raw)
  4134. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4135. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4136. * path : an array of Vector3, the curve axis of the Path3D
  4137. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4138. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4139. */
  4140. function Path3D(path, firstNormal, raw) {
  4141. this.path = path;
  4142. this._curve = new Array();
  4143. this._distances = new Array();
  4144. this._tangents = new Array();
  4145. this._normals = new Array();
  4146. this._binormals = new Array();
  4147. for (var p = 0; p < path.length; p++) {
  4148. this._curve[p] = path[p].clone(); // hard copy
  4149. }
  4150. this._raw = raw || false;
  4151. this._compute(firstNormal);
  4152. }
  4153. /**
  4154. * Returns the Path3D array of successive Vector3 designing its curve.
  4155. */
  4156. Path3D.prototype.getCurve = function () {
  4157. return this._curve;
  4158. };
  4159. /**
  4160. * Returns an array populated with tangent vectors on each Path3D curve point.
  4161. */
  4162. Path3D.prototype.getTangents = function () {
  4163. return this._tangents;
  4164. };
  4165. /**
  4166. * Returns an array populated with normal vectors on each Path3D curve point.
  4167. */
  4168. Path3D.prototype.getNormals = function () {
  4169. return this._normals;
  4170. };
  4171. /**
  4172. * Returns an array populated with binormal vectors on each Path3D curve point.
  4173. */
  4174. Path3D.prototype.getBinormals = function () {
  4175. return this._binormals;
  4176. };
  4177. /**
  4178. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4179. */
  4180. Path3D.prototype.getDistances = function () {
  4181. return this._distances;
  4182. };
  4183. /**
  4184. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4185. * Returns the same object updated.
  4186. */
  4187. Path3D.prototype.update = function (path, firstNormal) {
  4188. for (var p = 0; p < path.length; p++) {
  4189. this._curve[p].x = path[p].x;
  4190. this._curve[p].y = path[p].y;
  4191. this._curve[p].z = path[p].z;
  4192. }
  4193. this._compute(firstNormal);
  4194. return this;
  4195. };
  4196. // private function compute() : computes tangents, normals and binormals
  4197. Path3D.prototype._compute = function (firstNormal) {
  4198. var l = this._curve.length;
  4199. // first and last tangents
  4200. this._tangents[0] = this._getFirstNonNullVector(0);
  4201. if (!this._raw) {
  4202. this._tangents[0].normalize();
  4203. }
  4204. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4205. if (!this._raw) {
  4206. this._tangents[l - 1].normalize();
  4207. }
  4208. // normals and binormals at first point : arbitrary vector with _normalVector()
  4209. var tg0 = this._tangents[0];
  4210. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4211. this._normals[0] = pp0;
  4212. if (!this._raw) {
  4213. this._normals[0].normalize();
  4214. }
  4215. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4216. if (!this._raw) {
  4217. this._binormals[0].normalize();
  4218. }
  4219. this._distances[0] = 0.0;
  4220. // normals and binormals : next points
  4221. var prev; // previous vector (segment)
  4222. var cur; // current vector (segment)
  4223. var curTang; // current tangent
  4224. // previous normal
  4225. var prevBinor; // previous binormal
  4226. for (var i = 1; i < l; i++) {
  4227. // tangents
  4228. prev = this._getLastNonNullVector(i);
  4229. if (i < l - 1) {
  4230. cur = this._getFirstNonNullVector(i);
  4231. this._tangents[i] = prev.add(cur);
  4232. this._tangents[i].normalize();
  4233. }
  4234. this._distances[i] = this._distances[i - 1] + prev.length();
  4235. // normals and binormals
  4236. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4237. curTang = this._tangents[i];
  4238. prevBinor = this._binormals[i - 1];
  4239. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4240. if (!this._raw) {
  4241. this._normals[i].normalize();
  4242. }
  4243. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4244. if (!this._raw) {
  4245. this._binormals[i].normalize();
  4246. }
  4247. }
  4248. };
  4249. // private function getFirstNonNullVector(index)
  4250. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4251. Path3D.prototype._getFirstNonNullVector = function (index) {
  4252. var i = 1;
  4253. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4254. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4255. i++;
  4256. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4257. }
  4258. return nNVector;
  4259. };
  4260. // private function getLastNonNullVector(index)
  4261. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4262. Path3D.prototype._getLastNonNullVector = function (index) {
  4263. var i = 1;
  4264. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4265. while (nLVector.length() === 0 && index > i + 1) {
  4266. i++;
  4267. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4268. }
  4269. return nLVector;
  4270. };
  4271. // private function normalVector(v0, vt, va) :
  4272. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4273. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4274. Path3D.prototype._normalVector = function (v0, vt, va) {
  4275. var normal0;
  4276. var tgl = vt.length();
  4277. if (tgl === 0.0) {
  4278. tgl = 1.0;
  4279. }
  4280. if (va === undefined || va === null) {
  4281. var point;
  4282. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4283. point = new Vector3(0.0, -1.0, 0.0);
  4284. }
  4285. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4286. point = new Vector3(1.0, 0.0, 0.0);
  4287. }
  4288. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4289. point = new Vector3(0.0, 0.0, 1.0);
  4290. }
  4291. normal0 = Vector3.Cross(vt, point);
  4292. }
  4293. else {
  4294. normal0 = Vector3.Cross(vt, va);
  4295. Vector3.CrossToRef(normal0, vt, normal0);
  4296. }
  4297. normal0.normalize();
  4298. return normal0;
  4299. };
  4300. return Path3D;
  4301. }());
  4302. BABYLON.Path3D = Path3D;
  4303. var Curve3 = (function () {
  4304. /**
  4305. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4306. * A Curve3 is designed from a series of successive Vector3.
  4307. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4308. */
  4309. function Curve3(points) {
  4310. this._length = 0.0;
  4311. this._points = points;
  4312. this._length = this._computeLength(points);
  4313. }
  4314. /**
  4315. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4316. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4317. * @param v1 (Vector3) the control point
  4318. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4319. * @param nbPoints (integer) the wanted number of points in the curve
  4320. */
  4321. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4322. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4323. var bez = new Array();
  4324. var equation = function (t, val0, val1, val2) {
  4325. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4326. return res;
  4327. };
  4328. for (var i = 0; i <= nbPoints; i++) {
  4329. 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)));
  4330. }
  4331. return new Curve3(bez);
  4332. };
  4333. /**
  4334. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4335. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4336. * @param v1 (Vector3) the first control point
  4337. * @param v2 (Vector3) the second control point
  4338. * @param v3 (Vector3) the end point of the Cubic Bezier
  4339. * @param nbPoints (integer) the wanted number of points in the curve
  4340. */
  4341. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4342. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4343. var bez = new Array();
  4344. var equation = function (t, val0, val1, val2, val3) {
  4345. 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;
  4346. return res;
  4347. };
  4348. for (var i = 0; i <= nbPoints; i++) {
  4349. 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)));
  4350. }
  4351. return new Curve3(bez);
  4352. };
  4353. /**
  4354. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4355. * @param p1 (Vector3) the origin point of the Hermite Spline
  4356. * @param t1 (Vector3) the tangent vector at the origin point
  4357. * @param p2 (Vector3) the end point of the Hermite Spline
  4358. * @param t2 (Vector3) the tangent vector at the end point
  4359. * @param nbPoints (integer) the wanted number of points in the curve
  4360. */
  4361. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4362. var hermite = new Array();
  4363. var step = 1.0 / nbPoints;
  4364. for (var i = 0; i <= nbPoints; i++) {
  4365. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4366. }
  4367. return new Curve3(hermite);
  4368. };
  4369. /**
  4370. * Returns a Curve3 object along a CatmullRom Spline curve :
  4371. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4372. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4373. */
  4374. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4375. var totalPoints = new Array();
  4376. totalPoints.push(points[0].clone());
  4377. Array.prototype.push.apply(totalPoints, points);
  4378. totalPoints.push(points[points.length - 1].clone());
  4379. var catmullRom = new Array();
  4380. var step = 1.0 / nbPoints;
  4381. for (var i = 0; i < totalPoints.length - 3; i++) {
  4382. var amount = 0.0;
  4383. for (var c = 0; c < nbPoints; c++) {
  4384. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4385. amount += step;
  4386. }
  4387. }
  4388. i--;
  4389. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4390. return new Curve3(catmullRom);
  4391. };
  4392. /**
  4393. * Returns the Curve3 stored array of successive Vector3
  4394. */
  4395. Curve3.prototype.getPoints = function () {
  4396. return this._points;
  4397. };
  4398. /**
  4399. * Returns the computed length (float) of the curve.
  4400. */
  4401. Curve3.prototype.length = function () {
  4402. return this._length;
  4403. };
  4404. /**
  4405. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4406. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4407. * curveA and curveB keep unchanged.
  4408. */
  4409. Curve3.prototype.continue = function (curve) {
  4410. var lastPoint = this._points[this._points.length - 1];
  4411. var continuedPoints = this._points.slice();
  4412. var curvePoints = curve.getPoints();
  4413. for (var i = 1; i < curvePoints.length; i++) {
  4414. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4415. }
  4416. var continuedCurve = new Curve3(continuedPoints);
  4417. return continuedCurve;
  4418. };
  4419. Curve3.prototype._computeLength = function (path) {
  4420. var l = 0;
  4421. for (var i = 1; i < path.length; i++) {
  4422. l += (path[i].subtract(path[i - 1])).length();
  4423. }
  4424. return l;
  4425. };
  4426. return Curve3;
  4427. }());
  4428. BABYLON.Curve3 = Curve3;
  4429. // SphericalHarmonics
  4430. var SphericalHarmonics = (function () {
  4431. function SphericalHarmonics() {
  4432. this.L00 = Vector3.Zero();
  4433. this.L1_1 = Vector3.Zero();
  4434. this.L10 = Vector3.Zero();
  4435. this.L11 = Vector3.Zero();
  4436. this.L2_2 = Vector3.Zero();
  4437. this.L2_1 = Vector3.Zero();
  4438. this.L20 = Vector3.Zero();
  4439. this.L21 = Vector3.Zero();
  4440. this.L22 = Vector3.Zero();
  4441. }
  4442. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4443. var colorVector = new Vector3(color.r, color.g, color.b);
  4444. var c = colorVector.scale(deltaSolidAngle);
  4445. this.L00 = this.L00.add(c.scale(0.282095));
  4446. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4447. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4448. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4449. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4450. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4451. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4452. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4453. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4454. };
  4455. SphericalHarmonics.prototype.scale = function (scale) {
  4456. this.L00 = this.L00.scale(scale);
  4457. this.L1_1 = this.L1_1.scale(scale);
  4458. this.L10 = this.L10.scale(scale);
  4459. this.L11 = this.L11.scale(scale);
  4460. this.L2_2 = this.L2_2.scale(scale);
  4461. this.L2_1 = this.L2_1.scale(scale);
  4462. this.L20 = this.L20.scale(scale);
  4463. this.L21 = this.L21.scale(scale);
  4464. this.L22 = this.L22.scale(scale);
  4465. };
  4466. return SphericalHarmonics;
  4467. }());
  4468. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4469. // SphericalPolynomial
  4470. var SphericalPolynomial = (function () {
  4471. function SphericalPolynomial() {
  4472. this.x = Vector3.Zero();
  4473. this.y = Vector3.Zero();
  4474. this.z = Vector3.Zero();
  4475. this.xx = Vector3.Zero();
  4476. this.yy = Vector3.Zero();
  4477. this.zz = Vector3.Zero();
  4478. this.xy = Vector3.Zero();
  4479. this.yz = Vector3.Zero();
  4480. this.zx = Vector3.Zero();
  4481. }
  4482. SphericalPolynomial.prototype.addAmbient = function (color) {
  4483. var colorVector = new Vector3(color.r, color.g, color.b);
  4484. this.xx = this.xx.add(colorVector);
  4485. this.yy = this.yy.add(colorVector);
  4486. this.zz = this.zz.add(colorVector);
  4487. };
  4488. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4489. var result = new SphericalPolynomial();
  4490. result.x = harmonics.L11.scale(1.02333);
  4491. result.y = harmonics.L1_1.scale(1.02333);
  4492. result.z = harmonics.L10.scale(1.02333);
  4493. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4494. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4495. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4496. result.yz = harmonics.L2_1.scale(0.858086);
  4497. result.zx = harmonics.L21.scale(0.858086);
  4498. result.xy = harmonics.L2_2.scale(0.858086);
  4499. return result;
  4500. };
  4501. return SphericalPolynomial;
  4502. }());
  4503. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4504. // Vertex formats
  4505. var PositionNormalVertex = (function () {
  4506. function PositionNormalVertex(position, normal) {
  4507. if (position === void 0) { position = Vector3.Zero(); }
  4508. if (normal === void 0) { normal = Vector3.Up(); }
  4509. this.position = position;
  4510. this.normal = normal;
  4511. }
  4512. PositionNormalVertex.prototype.clone = function () {
  4513. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4514. };
  4515. return PositionNormalVertex;
  4516. }());
  4517. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4518. var PositionNormalTextureVertex = (function () {
  4519. function PositionNormalTextureVertex(position, normal, uv) {
  4520. if (position === void 0) { position = Vector3.Zero(); }
  4521. if (normal === void 0) { normal = Vector3.Up(); }
  4522. if (uv === void 0) { uv = Vector2.Zero(); }
  4523. this.position = position;
  4524. this.normal = normal;
  4525. this.uv = uv;
  4526. }
  4527. PositionNormalTextureVertex.prototype.clone = function () {
  4528. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4529. };
  4530. return PositionNormalTextureVertex;
  4531. }());
  4532. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4533. // Temporary pre-allocated objects for engine internal use
  4534. // usage in any internal function :
  4535. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4536. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4537. var Tmp = (function () {
  4538. function Tmp() {
  4539. }
  4540. return Tmp;
  4541. }());
  4542. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4543. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4544. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4545. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4546. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4547. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4548. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4549. Matrix.Zero(), Matrix.Zero(),
  4550. Matrix.Zero(), Matrix.Zero(),
  4551. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4552. BABYLON.Tmp = Tmp;
  4553. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4554. var MathTmp = (function () {
  4555. function MathTmp() {
  4556. }
  4557. return MathTmp;
  4558. }());
  4559. MathTmp.Vector3 = [Vector3.Zero()];
  4560. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4561. MathTmp.Quaternion = [Quaternion.Zero()];
  4562. })(BABYLON || (BABYLON = {}));
  4563. //# sourceMappingURL=babylon.math.js.map
  4564. //# sourceMappingURL=babylon.mixins.js.map
  4565. var BABYLON;
  4566. (function (BABYLON) {
  4567. function generateSerializableMember(type, sourceName) {
  4568. return function (target, propertyKey) {
  4569. if (!target.__serializableMembers) {
  4570. target.__serializableMembers = {};
  4571. }
  4572. if (!target.__serializableMembers[propertyKey]) {
  4573. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4574. }
  4575. };
  4576. }
  4577. function serialize(sourceName) {
  4578. return generateSerializableMember(0, sourceName); // value member
  4579. }
  4580. BABYLON.serialize = serialize;
  4581. function serializeAsTexture(sourceName) {
  4582. return generateSerializableMember(1, sourceName); // texture member
  4583. }
  4584. BABYLON.serializeAsTexture = serializeAsTexture;
  4585. function serializeAsColor3(sourceName) {
  4586. return generateSerializableMember(2, sourceName); // color3 member
  4587. }
  4588. BABYLON.serializeAsColor3 = serializeAsColor3;
  4589. function serializeAsFresnelParameters(sourceName) {
  4590. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4591. }
  4592. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4593. function serializeAsVector2(sourceName) {
  4594. return generateSerializableMember(4, sourceName); // vector2 member
  4595. }
  4596. BABYLON.serializeAsVector2 = serializeAsVector2;
  4597. function serializeAsVector3(sourceName) {
  4598. return generateSerializableMember(5, sourceName); // vector3 member
  4599. }
  4600. BABYLON.serializeAsVector3 = serializeAsVector3;
  4601. function serializeAsMeshReference(sourceName) {
  4602. return generateSerializableMember(6, sourceName); // mesh reference member
  4603. }
  4604. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4605. function serializeAsColorCurves(sourceName) {
  4606. return generateSerializableMember(7, sourceName); // color curves
  4607. }
  4608. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4609. var SerializationHelper = (function () {
  4610. function SerializationHelper() {
  4611. }
  4612. SerializationHelper.Serialize = function (entity, serializationObject) {
  4613. if (!serializationObject) {
  4614. serializationObject = {};
  4615. }
  4616. // Tags
  4617. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4618. // Properties
  4619. for (var property in entity.__serializableMembers) {
  4620. var propertyDescriptor = entity.__serializableMembers[property];
  4621. var targetPropertyName = propertyDescriptor.sourceName || property;
  4622. var propertyType = propertyDescriptor.type;
  4623. var sourceProperty = entity[property];
  4624. if (sourceProperty !== undefined && sourceProperty !== null) {
  4625. switch (propertyType) {
  4626. case 0:
  4627. serializationObject[targetPropertyName] = sourceProperty;
  4628. break;
  4629. case 1:
  4630. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4631. break;
  4632. case 2:
  4633. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4634. break;
  4635. case 3:
  4636. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4637. break;
  4638. case 4:
  4639. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4640. break;
  4641. case 5:
  4642. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4643. break;
  4644. case 6:
  4645. serializationObject[targetPropertyName] = sourceProperty.id;
  4646. break;
  4647. case 7:
  4648. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4649. break;
  4650. }
  4651. }
  4652. }
  4653. return serializationObject;
  4654. };
  4655. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4656. var destination = creationFunction();
  4657. // Tags
  4658. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4659. // Properties
  4660. for (var property in destination.__serializableMembers) {
  4661. var propertyDescriptor = destination.__serializableMembers[property];
  4662. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4663. var propertyType = propertyDescriptor.type;
  4664. if (sourceProperty !== undefined && sourceProperty !== null) {
  4665. switch (propertyType) {
  4666. case 0:
  4667. destination[property] = sourceProperty;
  4668. break;
  4669. case 1:
  4670. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4671. break;
  4672. case 2:
  4673. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4674. break;
  4675. case 3:
  4676. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4677. break;
  4678. case 4:
  4679. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4680. break;
  4681. case 5:
  4682. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4683. break;
  4684. case 6:
  4685. destination[property] = scene.getLastMeshByID(sourceProperty);
  4686. break;
  4687. case 7:
  4688. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4689. break;
  4690. }
  4691. }
  4692. }
  4693. return destination;
  4694. };
  4695. SerializationHelper.Clone = function (creationFunction, source) {
  4696. var destination = creationFunction();
  4697. // Tags
  4698. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4699. // Properties
  4700. for (var property in destination.__serializableMembers) {
  4701. var propertyDescriptor = destination.__serializableMembers[property];
  4702. var sourceProperty = source[property];
  4703. var propertyType = propertyDescriptor.type;
  4704. if (sourceProperty !== undefined && sourceProperty !== null) {
  4705. switch (propertyType) {
  4706. case 0: // Value
  4707. case 6:
  4708. destination[property] = sourceProperty;
  4709. break;
  4710. case 1: // Texture
  4711. case 2: // Color3
  4712. case 3: // FresnelParameters
  4713. case 4: // Vector2
  4714. case 5: // Vector3
  4715. case 7:
  4716. destination[property] = sourceProperty.clone();
  4717. break;
  4718. }
  4719. }
  4720. }
  4721. return destination;
  4722. };
  4723. return SerializationHelper;
  4724. }());
  4725. BABYLON.SerializationHelper = SerializationHelper;
  4726. })(BABYLON || (BABYLON = {}));
  4727. //# sourceMappingURL=babylon.decorators.js.map
  4728. var BABYLON;
  4729. (function (BABYLON) {
  4730. /**
  4731. * A class serves as a medium between the observable and its observers
  4732. */
  4733. var EventState = (function () {
  4734. /**
  4735. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4736. */
  4737. function EventState(mask, skipNextObservers) {
  4738. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4739. this.initalize(mask, skipNextObservers);
  4740. }
  4741. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4742. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4743. this.mask = mask;
  4744. this.skipNextObservers = skipNextObservers;
  4745. return this;
  4746. };
  4747. return EventState;
  4748. }());
  4749. BABYLON.EventState = EventState;
  4750. /**
  4751. * Represent an Observer registered to a given Observable object.
  4752. */
  4753. var Observer = (function () {
  4754. function Observer(callback, mask) {
  4755. this.callback = callback;
  4756. this.mask = mask;
  4757. }
  4758. return Observer;
  4759. }());
  4760. BABYLON.Observer = Observer;
  4761. /**
  4762. * The Observable class is a simple implementation of the Observable pattern.
  4763. * 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.
  4764. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4765. * 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).
  4766. * 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.
  4767. */
  4768. var Observable = (function () {
  4769. function Observable() {
  4770. this._observers = new Array();
  4771. this._eventState = new EventState(0);
  4772. }
  4773. /**
  4774. * Create a new Observer with the specified callback
  4775. * @param callback the callback that will be executed for that Observer
  4776. * @param mask the mask used to filter observers
  4777. * @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.
  4778. */
  4779. Observable.prototype.add = function (callback, mask, insertFirst) {
  4780. if (mask === void 0) { mask = -1; }
  4781. if (insertFirst === void 0) { insertFirst = false; }
  4782. if (!callback) {
  4783. return null;
  4784. }
  4785. var observer = new Observer(callback, mask);
  4786. if (insertFirst) {
  4787. this._observers.unshift(observer);
  4788. }
  4789. else {
  4790. this._observers.push(observer);
  4791. }
  4792. return observer;
  4793. };
  4794. /**
  4795. * Remove an Observer from the Observable object
  4796. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4797. */
  4798. Observable.prototype.remove = function (observer) {
  4799. var index = this._observers.indexOf(observer);
  4800. if (index !== -1) {
  4801. this._observers.splice(index, 1);
  4802. return true;
  4803. }
  4804. return false;
  4805. };
  4806. /**
  4807. * Remove a callback from the Observable object
  4808. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4809. */
  4810. Observable.prototype.removeCallback = function (callback) {
  4811. for (var index = 0; index < this._observers.length; index++) {
  4812. if (this._observers[index].callback === callback) {
  4813. this._observers.splice(index, 1);
  4814. return true;
  4815. }
  4816. }
  4817. return false;
  4818. };
  4819. /**
  4820. * Notify all Observers by calling their respective callback with the given data
  4821. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  4822. * @param eventData
  4823. * @param mask
  4824. */
  4825. Observable.prototype.notifyObservers = function (eventData, mask) {
  4826. if (mask === void 0) { mask = -1; }
  4827. var state = this._eventState;
  4828. state.mask = mask;
  4829. state.skipNextObservers = false;
  4830. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4831. var obs = _a[_i];
  4832. if (obs.mask & mask) {
  4833. obs.callback(eventData, state);
  4834. }
  4835. if (state.skipNextObservers) {
  4836. return false;
  4837. }
  4838. }
  4839. return true;
  4840. };
  4841. /**
  4842. * return true is the Observable has at least one Observer registered
  4843. */
  4844. Observable.prototype.hasObservers = function () {
  4845. return this._observers.length > 0;
  4846. };
  4847. /**
  4848. * Clear the list of observers
  4849. */
  4850. Observable.prototype.clear = function () {
  4851. this._observers = new Array();
  4852. };
  4853. /**
  4854. * Clone the current observable
  4855. */
  4856. Observable.prototype.clone = function () {
  4857. var result = new Observable();
  4858. result._observers = this._observers.slice(0);
  4859. return result;
  4860. };
  4861. return Observable;
  4862. }());
  4863. BABYLON.Observable = Observable;
  4864. })(BABYLON || (BABYLON = {}));
  4865. //# sourceMappingURL=babylon.observable.js.map
  4866. var BABYLON;
  4867. (function (BABYLON) {
  4868. var Database = (function () {
  4869. function Database(urlToScene, callbackManifestChecked) {
  4870. // Handling various flavors of prefixed version of IndexedDB
  4871. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  4872. this.callbackManifestChecked = callbackManifestChecked;
  4873. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  4874. this.db = null;
  4875. this.enableSceneOffline = false;
  4876. this.enableTexturesOffline = false;
  4877. this.manifestVersionFound = 0;
  4878. this.mustUpdateRessources = false;
  4879. this.hasReachedQuota = false;
  4880. if (!Database.IDBStorageEnabled) {
  4881. this.callbackManifestChecked(true);
  4882. }
  4883. else {
  4884. this.checkManifestFile();
  4885. }
  4886. }
  4887. Database.prototype.checkManifestFile = function () {
  4888. var _this = this;
  4889. function noManifestFile() {
  4890. that.enableSceneOffline = false;
  4891. that.enableTexturesOffline = false;
  4892. that.callbackManifestChecked(false);
  4893. }
  4894. var that = this;
  4895. var timeStampUsed = false;
  4896. var manifestURL = this.currentSceneUrl + ".manifest";
  4897. var xhr = new XMLHttpRequest();
  4898. if (navigator.onLine) {
  4899. // Adding a timestamp to by-pass browsers' cache
  4900. timeStampUsed = true;
  4901. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  4902. }
  4903. xhr.open("GET", manifestURL, true);
  4904. xhr.addEventListener("load", function () {
  4905. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  4906. try {
  4907. var manifestFile = JSON.parse(xhr.response);
  4908. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  4909. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  4910. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  4911. _this.manifestVersionFound = manifestFile.version;
  4912. }
  4913. if (_this.callbackManifestChecked) {
  4914. _this.callbackManifestChecked(true);
  4915. }
  4916. }
  4917. catch (ex) {
  4918. noManifestFile();
  4919. }
  4920. }
  4921. else {
  4922. noManifestFile();
  4923. }
  4924. }, false);
  4925. xhr.addEventListener("error", function (event) {
  4926. if (timeStampUsed) {
  4927. timeStampUsed = false;
  4928. // Let's retry without the timeStamp
  4929. // It could fail when coupled with HTML5 Offline API
  4930. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  4931. xhr.open("GET", retryManifestURL, true);
  4932. xhr.send();
  4933. }
  4934. else {
  4935. noManifestFile();
  4936. }
  4937. }, false);
  4938. try {
  4939. xhr.send();
  4940. }
  4941. catch (ex) {
  4942. BABYLON.Tools.Error("Error on XHR send request.");
  4943. that.callbackManifestChecked(false);
  4944. }
  4945. };
  4946. Database.prototype.openAsync = function (successCallback, errorCallback) {
  4947. var _this = this;
  4948. function handleError() {
  4949. that.isSupported = false;
  4950. if (errorCallback)
  4951. errorCallback();
  4952. }
  4953. var that = this;
  4954. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  4955. // Your browser doesn't support IndexedDB
  4956. this.isSupported = false;
  4957. if (errorCallback)
  4958. errorCallback();
  4959. }
  4960. else {
  4961. // If the DB hasn't been opened or created yet
  4962. if (!this.db) {
  4963. this.hasReachedQuota = false;
  4964. this.isSupported = true;
  4965. var request = this.idbFactory.open("babylonjs", 1);
  4966. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  4967. request.onerror = function (event) {
  4968. handleError();
  4969. };
  4970. // executes when a version change transaction cannot complete due to other active transactions
  4971. request.onblocked = function (event) {
  4972. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  4973. handleError();
  4974. };
  4975. // DB has been opened successfully
  4976. request.onsuccess = function (event) {
  4977. _this.db = request.result;
  4978. successCallback();
  4979. };
  4980. // Initialization of the DB. Creating Scenes & Textures stores
  4981. request.onupgradeneeded = function (event) {
  4982. _this.db = (event.target).result;
  4983. try {
  4984. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  4985. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  4986. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  4987. }
  4988. catch (ex) {
  4989. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  4990. handleError();
  4991. }
  4992. };
  4993. }
  4994. else {
  4995. if (successCallback)
  4996. successCallback();
  4997. }
  4998. }
  4999. };
  5000. Database.prototype.loadImageFromDB = function (url, image) {
  5001. var _this = this;
  5002. var completeURL = Database.ReturnFullUrlLocation(url);
  5003. var saveAndLoadImage = function () {
  5004. if (!_this.hasReachedQuota && _this.db !== null) {
  5005. // the texture is not yet in the DB, let's try to save it
  5006. _this._saveImageIntoDBAsync(completeURL, image);
  5007. }
  5008. else {
  5009. image.src = url;
  5010. }
  5011. };
  5012. if (!this.mustUpdateRessources) {
  5013. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  5014. }
  5015. else {
  5016. saveAndLoadImage();
  5017. }
  5018. };
  5019. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  5020. if (this.isSupported && this.db !== null) {
  5021. var texture;
  5022. var transaction = this.db.transaction(["textures"]);
  5023. transaction.onabort = function (event) {
  5024. image.src = url;
  5025. };
  5026. transaction.oncomplete = function (event) {
  5027. var blobTextureURL;
  5028. if (texture) {
  5029. var URL = window.URL || window.webkitURL;
  5030. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  5031. image.onerror = function () {
  5032. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  5033. image.src = url;
  5034. };
  5035. image.src = blobTextureURL;
  5036. }
  5037. else {
  5038. notInDBCallback();
  5039. }
  5040. };
  5041. var getRequest = transaction.objectStore("textures").get(url);
  5042. getRequest.onsuccess = function (event) {
  5043. texture = (event.target).result;
  5044. };
  5045. getRequest.onerror = function (event) {
  5046. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  5047. image.src = url;
  5048. };
  5049. }
  5050. else {
  5051. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5052. image.src = url;
  5053. }
  5054. };
  5055. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  5056. var _this = this;
  5057. if (this.isSupported) {
  5058. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  5059. var generateBlobUrl = function () {
  5060. var blobTextureURL;
  5061. if (blob) {
  5062. var URL = window.URL || window.webkitURL;
  5063. try {
  5064. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  5065. }
  5066. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  5067. catch (ex) {
  5068. blobTextureURL = URL.createObjectURL(blob);
  5069. }
  5070. }
  5071. image.src = blobTextureURL;
  5072. };
  5073. if (Database.IsUASupportingBlobStorage) {
  5074. var xhr = new XMLHttpRequest(), blob;
  5075. xhr.open("GET", url, true);
  5076. xhr.responseType = "blob";
  5077. xhr.addEventListener("load", function () {
  5078. if (xhr.status === 200) {
  5079. // Blob as response (XHR2)
  5080. blob = xhr.response;
  5081. var transaction = _this.db.transaction(["textures"], "readwrite");
  5082. // the transaction could abort because of a QuotaExceededError error
  5083. transaction.onabort = function (event) {
  5084. try {
  5085. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5086. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5087. _this.hasReachedQuota = true;
  5088. }
  5089. }
  5090. catch (ex) { }
  5091. generateBlobUrl();
  5092. };
  5093. transaction.oncomplete = function (event) {
  5094. generateBlobUrl();
  5095. };
  5096. var newTexture = { textureUrl: url, data: blob };
  5097. try {
  5098. // Put the blob into the dabase
  5099. var addRequest = transaction.objectStore("textures").put(newTexture);
  5100. addRequest.onsuccess = function (event) {
  5101. };
  5102. addRequest.onerror = function (event) {
  5103. generateBlobUrl();
  5104. };
  5105. }
  5106. catch (ex) {
  5107. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  5108. if (ex.code === 25) {
  5109. Database.IsUASupportingBlobStorage = false;
  5110. }
  5111. image.src = url;
  5112. }
  5113. }
  5114. else {
  5115. image.src = url;
  5116. }
  5117. }, false);
  5118. xhr.addEventListener("error", function (event) {
  5119. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  5120. image.src = url;
  5121. }, false);
  5122. xhr.send();
  5123. }
  5124. else {
  5125. image.src = url;
  5126. }
  5127. }
  5128. else {
  5129. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5130. image.src = url;
  5131. }
  5132. };
  5133. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  5134. var _this = this;
  5135. var updateVersion = function (event) {
  5136. // the version is not yet in the DB or we need to update it
  5137. _this._saveVersionIntoDBAsync(url, versionLoaded);
  5138. };
  5139. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  5140. };
  5141. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  5142. var _this = this;
  5143. if (this.isSupported) {
  5144. var version;
  5145. try {
  5146. var transaction = this.db.transaction(["versions"]);
  5147. transaction.oncomplete = function (event) {
  5148. if (version) {
  5149. // If the version in the JSON file is > than the version in DB
  5150. if (_this.manifestVersionFound > version.data) {
  5151. _this.mustUpdateRessources = true;
  5152. updateInDBCallback();
  5153. }
  5154. else {
  5155. callback(version.data);
  5156. }
  5157. }
  5158. else {
  5159. _this.mustUpdateRessources = true;
  5160. updateInDBCallback();
  5161. }
  5162. };
  5163. transaction.onabort = function (event) {
  5164. callback(-1);
  5165. };
  5166. var getRequest = transaction.objectStore("versions").get(url);
  5167. getRequest.onsuccess = function (event) {
  5168. version = (event.target).result;
  5169. };
  5170. getRequest.onerror = function (event) {
  5171. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  5172. callback(-1);
  5173. };
  5174. }
  5175. catch (ex) {
  5176. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  5177. callback(-1);
  5178. }
  5179. }
  5180. else {
  5181. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5182. callback(-1);
  5183. }
  5184. };
  5185. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  5186. var _this = this;
  5187. if (this.isSupported && !this.hasReachedQuota) {
  5188. try {
  5189. // Open a transaction to the database
  5190. var transaction = this.db.transaction(["versions"], "readwrite");
  5191. // the transaction could abort because of a QuotaExceededError error
  5192. transaction.onabort = function (event) {
  5193. try {
  5194. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5195. _this.hasReachedQuota = true;
  5196. }
  5197. }
  5198. catch (ex) { }
  5199. callback(-1);
  5200. };
  5201. transaction.oncomplete = function (event) {
  5202. callback(_this.manifestVersionFound);
  5203. };
  5204. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  5205. // Put the scene into the database
  5206. var addRequest = transaction.objectStore("versions").put(newVersion);
  5207. addRequest.onsuccess = function (event) {
  5208. };
  5209. addRequest.onerror = function (event) {
  5210. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  5211. };
  5212. }
  5213. catch (ex) {
  5214. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  5215. callback(-1);
  5216. }
  5217. }
  5218. else {
  5219. callback(-1);
  5220. }
  5221. };
  5222. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  5223. var _this = this;
  5224. var completeUrl = Database.ReturnFullUrlLocation(url);
  5225. var saveAndLoadFile = function (event) {
  5226. // the scene is not yet in the DB, let's try to save it
  5227. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  5228. };
  5229. this._checkVersionFromDB(completeUrl, function (version) {
  5230. if (version !== -1) {
  5231. if (!_this.mustUpdateRessources) {
  5232. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  5233. }
  5234. else {
  5235. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  5236. }
  5237. }
  5238. else {
  5239. errorCallback();
  5240. }
  5241. });
  5242. };
  5243. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  5244. if (this.isSupported) {
  5245. var targetStore;
  5246. if (url.indexOf(".babylon") !== -1) {
  5247. targetStore = "scenes";
  5248. }
  5249. else {
  5250. targetStore = "textures";
  5251. }
  5252. var file;
  5253. var transaction = this.db.transaction([targetStore]);
  5254. transaction.oncomplete = function (event) {
  5255. if (file) {
  5256. callback(file.data);
  5257. }
  5258. else {
  5259. notInDBCallback();
  5260. }
  5261. };
  5262. transaction.onabort = function (event) {
  5263. notInDBCallback();
  5264. };
  5265. var getRequest = transaction.objectStore(targetStore).get(url);
  5266. getRequest.onsuccess = function (event) {
  5267. file = (event.target).result;
  5268. };
  5269. getRequest.onerror = function (event) {
  5270. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  5271. notInDBCallback();
  5272. };
  5273. }
  5274. else {
  5275. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5276. callback();
  5277. }
  5278. };
  5279. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  5280. var _this = this;
  5281. if (this.isSupported) {
  5282. var targetStore;
  5283. if (url.indexOf(".babylon") !== -1) {
  5284. targetStore = "scenes";
  5285. }
  5286. else {
  5287. targetStore = "textures";
  5288. }
  5289. // Create XHR
  5290. var xhr = new XMLHttpRequest(), fileData;
  5291. xhr.open("GET", url, true);
  5292. if (useArrayBuffer) {
  5293. xhr.responseType = "arraybuffer";
  5294. }
  5295. xhr.onprogress = progressCallback;
  5296. xhr.addEventListener("load", function () {
  5297. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  5298. // Blob as response (XHR2)
  5299. //fileData = xhr.responseText;
  5300. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  5301. if (!_this.hasReachedQuota) {
  5302. // Open a transaction to the database
  5303. var transaction = _this.db.transaction([targetStore], "readwrite");
  5304. // the transaction could abort because of a QuotaExceededError error
  5305. transaction.onabort = function (event) {
  5306. try {
  5307. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5308. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5309. _this.hasReachedQuota = true;
  5310. }
  5311. }
  5312. catch (ex) { }
  5313. callback(fileData);
  5314. };
  5315. transaction.oncomplete = function (event) {
  5316. callback(fileData);
  5317. };
  5318. var newFile;
  5319. if (targetStore === "scenes") {
  5320. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  5321. }
  5322. else {
  5323. newFile = { textureUrl: url, data: fileData };
  5324. }
  5325. try {
  5326. // Put the scene into the database
  5327. var addRequest = transaction.objectStore(targetStore).put(newFile);
  5328. addRequest.onsuccess = function (event) {
  5329. };
  5330. addRequest.onerror = function (event) {
  5331. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  5332. };
  5333. }
  5334. catch (ex) {
  5335. callback(fileData);
  5336. }
  5337. }
  5338. else {
  5339. callback(fileData);
  5340. }
  5341. }
  5342. else {
  5343. callback();
  5344. }
  5345. }, false);
  5346. xhr.addEventListener("error", function (event) {
  5347. BABYLON.Tools.Error("error on XHR request.");
  5348. callback();
  5349. }, false);
  5350. xhr.send();
  5351. }
  5352. else {
  5353. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5354. callback();
  5355. }
  5356. };
  5357. return Database;
  5358. }());
  5359. Database.IsUASupportingBlobStorage = true;
  5360. Database.IDBStorageEnabled = true;
  5361. Database.parseURL = function (url) {
  5362. var a = document.createElement('a');
  5363. a.href = url;
  5364. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  5365. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  5366. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  5367. return absLocation;
  5368. };
  5369. Database.ReturnFullUrlLocation = function (url) {
  5370. if (url.indexOf("http:/") === -1) {
  5371. return (Database.parseURL(window.location.href) + url);
  5372. }
  5373. else {
  5374. return url;
  5375. }
  5376. };
  5377. BABYLON.Database = Database;
  5378. })(BABYLON || (BABYLON = {}));
  5379. //# sourceMappingURL=babylon.database.js.map
  5380. var BABYLON;
  5381. (function (BABYLON) {
  5382. var Internals;
  5383. (function (Internals) {
  5384. /*
  5385. * Based on jsTGALoader - Javascript loader for TGA file
  5386. * By Vincent Thibault
  5387. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  5388. */
  5389. var TGATools = (function () {
  5390. function TGATools() {
  5391. }
  5392. TGATools.GetTGAHeader = function (data) {
  5393. var offset = 0;
  5394. var header = {
  5395. id_length: data[offset++],
  5396. colormap_type: data[offset++],
  5397. image_type: data[offset++],
  5398. colormap_index: data[offset++] | data[offset++] << 8,
  5399. colormap_length: data[offset++] | data[offset++] << 8,
  5400. colormap_size: data[offset++],
  5401. origin: [
  5402. data[offset++] | data[offset++] << 8,
  5403. data[offset++] | data[offset++] << 8
  5404. ],
  5405. width: data[offset++] | data[offset++] << 8,
  5406. height: data[offset++] | data[offset++] << 8,
  5407. pixel_size: data[offset++],
  5408. flags: data[offset++]
  5409. };
  5410. return header;
  5411. };
  5412. TGATools.UploadContent = function (gl, data) {
  5413. // Not enough data to contain header ?
  5414. if (data.length < 19) {
  5415. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  5416. return;
  5417. }
  5418. // Read Header
  5419. var offset = 18;
  5420. var header = TGATools.GetTGAHeader(data);
  5421. // Assume it's a valid Targa file.
  5422. if (header.id_length + offset > data.length) {
  5423. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  5424. return;
  5425. }
  5426. // Skip not needed data
  5427. offset += header.id_length;
  5428. var use_rle = false;
  5429. var use_pal = false;
  5430. var use_rgb = false;
  5431. var use_grey = false;
  5432. // Get some informations.
  5433. switch (header.image_type) {
  5434. case TGATools._TYPE_RLE_INDEXED:
  5435. use_rle = true;
  5436. case TGATools._TYPE_INDEXED:
  5437. use_pal = true;
  5438. break;
  5439. case TGATools._TYPE_RLE_RGB:
  5440. use_rle = true;
  5441. case TGATools._TYPE_RGB:
  5442. use_rgb = true;
  5443. break;
  5444. case TGATools._TYPE_RLE_GREY:
  5445. use_rle = true;
  5446. case TGATools._TYPE_GREY:
  5447. use_grey = true;
  5448. break;
  5449. }
  5450. var pixel_data;
  5451. var numAlphaBits = header.flags & 0xf;
  5452. var pixel_size = header.pixel_size >> 3;
  5453. var pixel_total = header.width * header.height * pixel_size;
  5454. // Read palettes
  5455. var palettes;
  5456. if (use_pal) {
  5457. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  5458. }
  5459. // Read LRE
  5460. if (use_rle) {
  5461. pixel_data = new Uint8Array(pixel_total);
  5462. var c, count, i;
  5463. var localOffset = 0;
  5464. var pixels = new Uint8Array(pixel_size);
  5465. while (offset < pixel_total && localOffset < pixel_total) {
  5466. c = data[offset++];
  5467. count = (c & 0x7f) + 1;
  5468. // RLE pixels
  5469. if (c & 0x80) {
  5470. // Bind pixel tmp array
  5471. for (i = 0; i < pixel_size; ++i) {
  5472. pixels[i] = data[offset++];
  5473. }
  5474. // Copy pixel array
  5475. for (i = 0; i < count; ++i) {
  5476. pixel_data.set(pixels, localOffset + i * pixel_size);
  5477. }
  5478. localOffset += pixel_size * count;
  5479. }
  5480. else {
  5481. count *= pixel_size;
  5482. for (i = 0; i < count; ++i) {
  5483. pixel_data[localOffset + i] = data[offset++];
  5484. }
  5485. localOffset += count;
  5486. }
  5487. }
  5488. }
  5489. else {
  5490. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  5491. }
  5492. // Load to texture
  5493. var x_start, y_start, x_step, y_step, y_end, x_end;
  5494. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  5495. default:
  5496. case TGATools._ORIGIN_UL:
  5497. x_start = 0;
  5498. x_step = 1;
  5499. x_end = header.width;
  5500. y_start = 0;
  5501. y_step = 1;
  5502. y_end = header.height;
  5503. break;
  5504. case TGATools._ORIGIN_BL:
  5505. x_start = 0;
  5506. x_step = 1;
  5507. x_end = header.width;
  5508. y_start = header.height - 1;
  5509. y_step = -1;
  5510. y_end = -1;
  5511. break;
  5512. case TGATools._ORIGIN_UR:
  5513. x_start = header.width - 1;
  5514. x_step = -1;
  5515. x_end = -1;
  5516. y_start = 0;
  5517. y_step = 1;
  5518. y_end = header.height;
  5519. break;
  5520. case TGATools._ORIGIN_BR:
  5521. x_start = header.width - 1;
  5522. x_step = -1;
  5523. x_end = -1;
  5524. y_start = header.height - 1;
  5525. y_step = -1;
  5526. y_end = -1;
  5527. break;
  5528. }
  5529. // Load the specify method
  5530. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  5531. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  5532. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  5533. };
  5534. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5535. var image = pixel_data, colormap = palettes;
  5536. var width = header.width, height = header.height;
  5537. var color, i = 0, x, y;
  5538. var imageData = new Uint8Array(width * height * 4);
  5539. for (y = y_start; y !== y_end; y += y_step) {
  5540. for (x = x_start; x !== x_end; x += x_step, i++) {
  5541. color = image[i];
  5542. imageData[(x + width * y) * 4 + 3] = 255;
  5543. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  5544. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  5545. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  5546. }
  5547. }
  5548. return imageData;
  5549. };
  5550. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5551. var image = pixel_data;
  5552. var width = header.width, height = header.height;
  5553. var color, i = 0, x, y;
  5554. var imageData = new Uint8Array(width * height * 4);
  5555. for (y = y_start; y !== y_end; y += y_step) {
  5556. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5557. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  5558. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  5559. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  5560. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  5561. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  5562. }
  5563. }
  5564. return imageData;
  5565. };
  5566. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5567. var image = pixel_data;
  5568. var width = header.width, height = header.height;
  5569. var i = 0, x, y;
  5570. var imageData = new Uint8Array(width * height * 4);
  5571. for (y = y_start; y !== y_end; y += y_step) {
  5572. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  5573. imageData[(x + width * y) * 4 + 3] = 255;
  5574. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5575. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5576. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5577. }
  5578. }
  5579. return imageData;
  5580. };
  5581. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5582. var image = pixel_data;
  5583. var width = header.width, height = header.height;
  5584. var i = 0, x, y;
  5585. var imageData = new Uint8Array(width * height * 4);
  5586. for (y = y_start; y !== y_end; y += y_step) {
  5587. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  5588. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5589. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5590. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5591. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  5592. }
  5593. }
  5594. return imageData;
  5595. };
  5596. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5597. var image = pixel_data;
  5598. var width = header.width, height = header.height;
  5599. var color, i = 0, x, y;
  5600. var imageData = new Uint8Array(width * height * 4);
  5601. for (y = y_start; y !== y_end; y += y_step) {
  5602. for (x = x_start; x !== x_end; x += x_step, i++) {
  5603. color = image[i];
  5604. imageData[(x + width * y) * 4 + 0] = color;
  5605. imageData[(x + width * y) * 4 + 1] = color;
  5606. imageData[(x + width * y) * 4 + 2] = color;
  5607. imageData[(x + width * y) * 4 + 3] = 255;
  5608. }
  5609. }
  5610. return imageData;
  5611. };
  5612. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5613. var image = pixel_data;
  5614. var width = header.width, height = header.height;
  5615. var i = 0, x, y;
  5616. var imageData = new Uint8Array(width * height * 4);
  5617. for (y = y_start; y !== y_end; y += y_step) {
  5618. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5619. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  5620. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  5621. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5622. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  5623. }
  5624. }
  5625. return imageData;
  5626. };
  5627. return TGATools;
  5628. }());
  5629. TGATools._TYPE_NO_DATA = 0;
  5630. TGATools._TYPE_INDEXED = 1;
  5631. TGATools._TYPE_RGB = 2;
  5632. TGATools._TYPE_GREY = 3;
  5633. TGATools._TYPE_RLE_INDEXED = 9;
  5634. TGATools._TYPE_RLE_RGB = 10;
  5635. TGATools._TYPE_RLE_GREY = 11;
  5636. TGATools._ORIGIN_MASK = 0x30;
  5637. TGATools._ORIGIN_SHIFT = 0x04;
  5638. TGATools._ORIGIN_BL = 0x00;
  5639. TGATools._ORIGIN_BR = 0x01;
  5640. TGATools._ORIGIN_UL = 0x02;
  5641. TGATools._ORIGIN_UR = 0x03;
  5642. Internals.TGATools = TGATools;
  5643. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5644. })(BABYLON || (BABYLON = {}));
  5645. //# sourceMappingURL=babylon.tools.tga.js.map
  5646. var BABYLON;
  5647. (function (BABYLON) {
  5648. var SmartArray = (function () {
  5649. function SmartArray(capacity) {
  5650. this.length = 0;
  5651. this._duplicateId = 0;
  5652. this.data = new Array(capacity);
  5653. this._id = SmartArray._GlobalId++;
  5654. }
  5655. SmartArray.prototype.push = function (value) {
  5656. this.data[this.length++] = value;
  5657. if (this.length > this.data.length) {
  5658. this.data.length *= 2;
  5659. }
  5660. if (!value.__smartArrayFlags) {
  5661. value.__smartArrayFlags = {};
  5662. }
  5663. value.__smartArrayFlags[this._id] = this._duplicateId;
  5664. };
  5665. SmartArray.prototype.pushNoDuplicate = function (value) {
  5666. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5667. return false;
  5668. }
  5669. this.push(value);
  5670. return true;
  5671. };
  5672. SmartArray.prototype.sort = function (compareFn) {
  5673. this.data.sort(compareFn);
  5674. };
  5675. SmartArray.prototype.reset = function () {
  5676. this.length = 0;
  5677. this._duplicateId++;
  5678. };
  5679. SmartArray.prototype.concat = function (array) {
  5680. if (array.length === 0) {
  5681. return;
  5682. }
  5683. if (this.length + array.length > this.data.length) {
  5684. this.data.length = (this.length + array.length) * 2;
  5685. }
  5686. for (var index = 0; index < array.length; index++) {
  5687. this.data[this.length++] = (array.data || array)[index];
  5688. }
  5689. };
  5690. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5691. if (array.length === 0) {
  5692. return;
  5693. }
  5694. if (this.length + array.length > this.data.length) {
  5695. this.data.length = (this.length + array.length) * 2;
  5696. }
  5697. for (var index = 0; index < array.length; index++) {
  5698. var item = (array.data || array)[index];
  5699. this.pushNoDuplicate(item);
  5700. }
  5701. };
  5702. SmartArray.prototype.indexOf = function (value) {
  5703. var position = this.data.indexOf(value);
  5704. if (position >= this.length) {
  5705. return -1;
  5706. }
  5707. return position;
  5708. };
  5709. return SmartArray;
  5710. }());
  5711. // Statics
  5712. SmartArray._GlobalId = 0;
  5713. BABYLON.SmartArray = SmartArray;
  5714. })(BABYLON || (BABYLON = {}));
  5715. //# sourceMappingURL=babylon.smartArray.js.map
  5716. var BABYLON;
  5717. (function (BABYLON) {
  5718. /**
  5719. * This class implement a typical dictionary using a string as key and the generic type T as value.
  5720. * The underlying implementation relies on an associative array to ensure the best performances.
  5721. * The value can be anything including 'null' but except 'undefined'
  5722. */
  5723. var StringDictionary = (function () {
  5724. function StringDictionary() {
  5725. this._count = 0;
  5726. this._data = {};
  5727. }
  5728. /**
  5729. * This will clear this dictionary and copy the content from the 'source' one.
  5730. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  5731. * @param source the dictionary to take the content from and copy to this dictionary
  5732. */
  5733. StringDictionary.prototype.copyFrom = function (source) {
  5734. var _this = this;
  5735. this.clear();
  5736. source.forEach(function (t, v) { return _this.add(t, v); });
  5737. };
  5738. /**
  5739. * Get a value based from its key
  5740. * @param key the given key to get the matching value from
  5741. * @return the value if found, otherwise undefined is returned
  5742. */
  5743. StringDictionary.prototype.get = function (key) {
  5744. var val = this._data[key];
  5745. if (val !== undefined) {
  5746. return val;
  5747. }
  5748. return undefined;
  5749. };
  5750. /**
  5751. * Get a value from its key or add it if it doesn't exist.
  5752. * This method will ensure you that a given key/data will be present in the dictionary.
  5753. * @param key the given key to get the matching value from
  5754. * @param factory the factory that will create the value if the key is not present in the dictionary.
  5755. * The factory will only be invoked if there's no data for the given key.
  5756. * @return the value corresponding to the key.
  5757. */
  5758. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  5759. var val = this.get(key);
  5760. if (val !== undefined) {
  5761. return val;
  5762. }
  5763. val = factory(key);
  5764. if (val) {
  5765. this.add(key, val);
  5766. }
  5767. return val;
  5768. };
  5769. /**
  5770. * Get a value from its key if present in the dictionary otherwise add it
  5771. * @param key the key to get the value from
  5772. * @param val if there's no such key/value pair in the dictionary add it with this value
  5773. * @return the value corresponding to the key
  5774. */
  5775. StringDictionary.prototype.getOrAdd = function (key, val) {
  5776. var curVal = this.get(key);
  5777. if (curVal !== undefined) {
  5778. return curVal;
  5779. }
  5780. this.add(key, val);
  5781. return val;
  5782. };
  5783. /**
  5784. * Check if there's a given key in the dictionary
  5785. * @param key the key to check for
  5786. * @return true if the key is present, false otherwise
  5787. */
  5788. StringDictionary.prototype.contains = function (key) {
  5789. return this._data[key] !== undefined;
  5790. };
  5791. /**
  5792. * Add a new key and its corresponding value
  5793. * @param key the key to add
  5794. * @param value the value corresponding to the key
  5795. * @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
  5796. */
  5797. StringDictionary.prototype.add = function (key, value) {
  5798. if (this._data[key] !== undefined) {
  5799. return false;
  5800. }
  5801. this._data[key] = value;
  5802. ++this._count;
  5803. return true;
  5804. };
  5805. StringDictionary.prototype.set = function (key, value) {
  5806. if (this._data[key] === undefined) {
  5807. return false;
  5808. }
  5809. this._data[key] = value;
  5810. return true;
  5811. };
  5812. /**
  5813. * Get the element of the given key and remove it from the dictionary
  5814. * @param key
  5815. */
  5816. StringDictionary.prototype.getAndRemove = function (key) {
  5817. var val = this.get(key);
  5818. if (val !== undefined) {
  5819. delete this._data[key];
  5820. --this._count;
  5821. return val;
  5822. }
  5823. return null;
  5824. };
  5825. /**
  5826. * Remove a key/value from the dictionary.
  5827. * @param key the key to remove
  5828. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  5829. */
  5830. StringDictionary.prototype.remove = function (key) {
  5831. if (this.contains(key)) {
  5832. delete this._data[key];
  5833. --this._count;
  5834. return true;
  5835. }
  5836. return false;
  5837. };
  5838. /**
  5839. * Clear the whole content of the dictionary
  5840. */
  5841. StringDictionary.prototype.clear = function () {
  5842. this._data = {};
  5843. this._count = 0;
  5844. };
  5845. Object.defineProperty(StringDictionary.prototype, "count", {
  5846. get: function () {
  5847. return this._count;
  5848. },
  5849. enumerable: true,
  5850. configurable: true
  5851. });
  5852. /**
  5853. * Execute a callback on each key/val of the dictionary.
  5854. * Note that you can remove any element in this dictionary in the callback implementation
  5855. * @param callback the callback to execute on a given key/value pair
  5856. */
  5857. StringDictionary.prototype.forEach = function (callback) {
  5858. for (var cur in this._data) {
  5859. var val = this._data[cur];
  5860. callback(cur, val);
  5861. }
  5862. };
  5863. /**
  5864. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  5865. * If the callback returns null or undefined the method will iterate to the next key/value pair
  5866. * Note that you can remove any element in this dictionary in the callback implementation
  5867. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  5868. */
  5869. StringDictionary.prototype.first = function (callback) {
  5870. for (var cur in this._data) {
  5871. var val = this._data[cur];
  5872. var res = callback(cur, val);
  5873. if (res) {
  5874. return res;
  5875. }
  5876. }
  5877. return null;
  5878. };
  5879. return StringDictionary;
  5880. }());
  5881. BABYLON.StringDictionary = StringDictionary;
  5882. })(BABYLON || (BABYLON = {}));
  5883. //# sourceMappingURL=babylon.stringDictionary.js.map
  5884. var BABYLON;
  5885. (function (BABYLON) {
  5886. // Screenshots
  5887. var screenshotCanvas;
  5888. var cloneValue = function (source, destinationObject) {
  5889. if (!source)
  5890. return null;
  5891. if (source instanceof BABYLON.Mesh) {
  5892. return null;
  5893. }
  5894. if (source instanceof BABYLON.SubMesh) {
  5895. return source.clone(destinationObject);
  5896. }
  5897. else if (source.clone) {
  5898. return source.clone();
  5899. }
  5900. return null;
  5901. };
  5902. var Tools = (function () {
  5903. function Tools() {
  5904. }
  5905. ;
  5906. Tools.Instantiate = function (className) {
  5907. var arr = className.split(".");
  5908. var fn = (window || this);
  5909. for (var i = 0, len = arr.length; i < len; i++) {
  5910. fn = fn[arr[i]];
  5911. }
  5912. if (typeof fn !== "function") {
  5913. return null;
  5914. }
  5915. return fn;
  5916. };
  5917. Tools.SetImmediate = function (action) {
  5918. if (window.setImmediate) {
  5919. window.setImmediate(action);
  5920. }
  5921. else {
  5922. setTimeout(action, 1);
  5923. }
  5924. };
  5925. Tools.IsExponentOfTwo = function (value) {
  5926. var count = 1;
  5927. do {
  5928. count *= 2;
  5929. } while (count < value);
  5930. return count === value;
  5931. };
  5932. Tools.GetExponentOfTwo = function (value, max) {
  5933. var count = 1;
  5934. do {
  5935. count *= 2;
  5936. } while (count < value);
  5937. if (count > max)
  5938. count = max;
  5939. return count;
  5940. };
  5941. Tools.GetFilename = function (path) {
  5942. var index = path.lastIndexOf("/");
  5943. if (index < 0)
  5944. return path;
  5945. return path.substring(index + 1);
  5946. };
  5947. Tools.GetDOMTextContent = function (element) {
  5948. var result = "";
  5949. var child = element.firstChild;
  5950. while (child) {
  5951. if (child.nodeType === 3) {
  5952. result += child.textContent;
  5953. }
  5954. child = child.nextSibling;
  5955. }
  5956. return result;
  5957. };
  5958. Tools.ToDegrees = function (angle) {
  5959. return angle * 180 / Math.PI;
  5960. };
  5961. Tools.ToRadians = function (angle) {
  5962. return angle * Math.PI / 180;
  5963. };
  5964. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5965. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5966. var output = "";
  5967. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5968. var i = 0;
  5969. var bytes = new Uint8Array(buffer);
  5970. while (i < bytes.length) {
  5971. chr1 = bytes[i++];
  5972. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5973. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5974. enc1 = chr1 >> 2;
  5975. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5976. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5977. enc4 = chr3 & 63;
  5978. if (isNaN(chr2)) {
  5979. enc3 = enc4 = 64;
  5980. }
  5981. else if (isNaN(chr3)) {
  5982. enc4 = 64;
  5983. }
  5984. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5985. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5986. }
  5987. return "data:image/png;base64," + output;
  5988. };
  5989. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5990. if (bias === void 0) { bias = null; }
  5991. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5992. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5993. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5994. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5995. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5996. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5997. }
  5998. if (bias) {
  5999. minimum.x -= minimum.x * bias.x + bias.y;
  6000. minimum.y -= minimum.y * bias.x + bias.y;
  6001. minimum.z -= minimum.z * bias.x + bias.y;
  6002. maximum.x += maximum.x * bias.x + bias.y;
  6003. maximum.y += maximum.y * bias.x + bias.y;
  6004. maximum.z += maximum.z * bias.x + bias.y;
  6005. }
  6006. return {
  6007. minimum: minimum,
  6008. maximum: maximum
  6009. };
  6010. };
  6011. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6012. if (bias === void 0) { bias = null; }
  6013. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6014. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6015. if (!stride) {
  6016. stride = 3;
  6017. }
  6018. for (var index = start; index < start + count; index++) {
  6019. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6020. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6021. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6022. }
  6023. if (bias) {
  6024. minimum.x -= minimum.x * bias.x + bias.y;
  6025. minimum.y -= minimum.y * bias.x + bias.y;
  6026. minimum.z -= minimum.z * bias.x + bias.y;
  6027. maximum.x += maximum.x * bias.x + bias.y;
  6028. maximum.y += maximum.y * bias.x + bias.y;
  6029. maximum.z += maximum.z * bias.x + bias.y;
  6030. }
  6031. return {
  6032. minimum: minimum,
  6033. maximum: maximum
  6034. };
  6035. };
  6036. Tools.Vector2ArrayFeeder = function (array) {
  6037. return function (index) {
  6038. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6039. var length = isFloatArray ? array.length / 2 : array.length;
  6040. if (index >= length) {
  6041. return null;
  6042. }
  6043. if (isFloatArray) {
  6044. var fa = array;
  6045. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6046. }
  6047. var a = array;
  6048. return a[index];
  6049. };
  6050. };
  6051. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6052. if (bias === void 0) { bias = null; }
  6053. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6054. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6055. var i = 0;
  6056. var cur = feeder(i++);
  6057. while (cur) {
  6058. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6059. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6060. cur = feeder(i++);
  6061. }
  6062. if (bias) {
  6063. minimum.x -= minimum.x * bias.x + bias.y;
  6064. minimum.y -= minimum.y * bias.x + bias.y;
  6065. maximum.x += maximum.x * bias.x + bias.y;
  6066. maximum.y += maximum.y * bias.x + bias.y;
  6067. }
  6068. return {
  6069. minimum: minimum,
  6070. maximum: maximum
  6071. };
  6072. };
  6073. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6074. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6075. return undefined;
  6076. return Array.isArray(obj) ? obj : [obj];
  6077. };
  6078. // Misc.
  6079. Tools.GetPointerPrefix = function () {
  6080. var eventPrefix = "pointer";
  6081. // Check if pointer events are supported
  6082. if (!window.PointerEvent && !navigator.pointerEnabled) {
  6083. eventPrefix = "mouse";
  6084. }
  6085. return eventPrefix;
  6086. };
  6087. /**
  6088. * @param func - the function to be called
  6089. * @param requester - the object that will request the next frame. Falls back to window.
  6090. */
  6091. Tools.QueueNewFrame = function (func, requester) {
  6092. if (requester === void 0) { requester = window; }
  6093. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  6094. /*if(requester.isPresenting) {
  6095. return;
  6096. } else*/ if (requester.requestAnimationFrame)
  6097. requester.requestAnimationFrame(func);
  6098. else if (requester.msRequestAnimationFrame)
  6099. requester.msRequestAnimationFrame(func);
  6100. else if (requester.webkitRequestAnimationFrame)
  6101. requester.webkitRequestAnimationFrame(func);
  6102. else if (requester.mozRequestAnimationFrame)
  6103. requester.mozRequestAnimationFrame(func);
  6104. else if (requester.oRequestAnimationFrame)
  6105. requester.oRequestAnimationFrame(func);
  6106. else {
  6107. window.setTimeout(func, 16);
  6108. }
  6109. };
  6110. Tools.RequestFullscreen = function (element) {
  6111. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6112. if (!requestFunction)
  6113. return;
  6114. requestFunction.call(element);
  6115. };
  6116. Tools.ExitFullscreen = function () {
  6117. if (document.exitFullscreen) {
  6118. document.exitFullscreen();
  6119. }
  6120. else if (document.mozCancelFullScreen) {
  6121. document.mozCancelFullScreen();
  6122. }
  6123. else if (document.webkitCancelFullScreen) {
  6124. document.webkitCancelFullScreen();
  6125. }
  6126. else if (document.msCancelFullScreen) {
  6127. document.msCancelFullScreen();
  6128. }
  6129. };
  6130. Tools.SetCorsBehavior = function (url, img) {
  6131. if (Tools.CorsBehavior) {
  6132. switch (typeof (Tools.CorsBehavior)) {
  6133. case "function":
  6134. var result = Tools.CorsBehavior(url);
  6135. if (result) {
  6136. return result;
  6137. }
  6138. break;
  6139. case "string":
  6140. default:
  6141. img.crossOrigin = Tools.CorsBehavior;
  6142. break;
  6143. }
  6144. }
  6145. };
  6146. // External files
  6147. Tools.CleanUrl = function (url) {
  6148. url = url.replace(/#/mg, "%23");
  6149. return url;
  6150. };
  6151. Tools.LoadImage = function (url, onload, onerror, database) {
  6152. if (url instanceof ArrayBuffer) {
  6153. url = Tools.EncodeArrayBufferTobase64(url);
  6154. }
  6155. url = Tools.CleanUrl(url);
  6156. var img = new Image();
  6157. if (url.substr(0, 5) !== "data:") {
  6158. Tools.SetCorsBehavior(url, img);
  6159. }
  6160. img.onload = function () {
  6161. onload(img);
  6162. };
  6163. img.onerror = function (err) {
  6164. Tools.Error("Error while trying to load image: " + url);
  6165. if (Tools.UseFallbackTexture) {
  6166. img.src = Tools.fallbackTexture;
  6167. onload(img);
  6168. }
  6169. else {
  6170. onerror();
  6171. }
  6172. };
  6173. var noIndexedDB = function () {
  6174. img.src = url;
  6175. };
  6176. var loadFromIndexedDB = function () {
  6177. database.loadImageFromDB(url, img);
  6178. };
  6179. //ANY database to do!
  6180. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6181. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6182. }
  6183. else {
  6184. if (url.indexOf("file:") === -1) {
  6185. noIndexedDB();
  6186. }
  6187. else {
  6188. var textureName = url.substring(5).toLowerCase();
  6189. if (BABYLON.FilesInput.FilesTextures[textureName]) {
  6190. try {
  6191. var blobURL;
  6192. try {
  6193. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  6194. }
  6195. catch (ex) {
  6196. // Chrome doesn't support oneTimeOnly parameter
  6197. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  6198. }
  6199. img.src = blobURL;
  6200. }
  6201. catch (e) {
  6202. img.src = null;
  6203. }
  6204. }
  6205. else {
  6206. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6207. img.src = Tools.fallbackTexture;
  6208. }
  6209. }
  6210. }
  6211. return img;
  6212. };
  6213. //ANY
  6214. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6215. url = Tools.CleanUrl(url);
  6216. var noIndexedDB = function () {
  6217. var request = new XMLHttpRequest();
  6218. var loadUrl = Tools.BaseUrl + url;
  6219. request.open('GET', loadUrl, true);
  6220. if (useArrayBuffer) {
  6221. request.responseType = "arraybuffer";
  6222. }
  6223. request.onprogress = progressCallBack;
  6224. request.onreadystatechange = function () {
  6225. if (request.readyState === 4) {
  6226. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6227. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  6228. callback(!useArrayBuffer ? request.responseText : request.response);
  6229. }
  6230. else {
  6231. if (onError) {
  6232. onError();
  6233. }
  6234. else {
  6235. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  6236. }
  6237. }
  6238. }
  6239. };
  6240. request.send(null);
  6241. };
  6242. var loadFromIndexedDB = function () {
  6243. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6244. };
  6245. if (url.indexOf("file:") !== -1) {
  6246. var fileName = url.substring(5).toLowerCase();
  6247. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6248. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6249. }
  6250. else {
  6251. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  6252. }
  6253. }
  6254. else {
  6255. // Caching all files
  6256. if (database && database.enableSceneOffline) {
  6257. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6258. }
  6259. else {
  6260. noIndexedDB();
  6261. }
  6262. }
  6263. };
  6264. /**
  6265. * Load a script (identified by an url). When the url returns, the
  6266. * content of this file is added into a new script element, attached to the DOM (body element)
  6267. */
  6268. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6269. var head = document.getElementsByTagName('head')[0];
  6270. var script = document.createElement('script');
  6271. script.type = 'text/javascript';
  6272. script.src = scriptUrl;
  6273. var self = this;
  6274. script.onload = function () {
  6275. if (onSuccess) {
  6276. onSuccess();
  6277. }
  6278. };
  6279. script.onerror = function () {
  6280. if (onError) {
  6281. onError();
  6282. }
  6283. };
  6284. head.appendChild(script);
  6285. };
  6286. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6287. var reader = new FileReader();
  6288. reader.onload = function (e) {
  6289. //target doesn't have result from ts 1.3
  6290. callback(e.target['result']);
  6291. };
  6292. reader.onprogress = progressCallback;
  6293. reader.readAsDataURL(fileToLoad);
  6294. };
  6295. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6296. var reader = new FileReader();
  6297. reader.onerror = function (e) {
  6298. Tools.Log("Error while reading file: " + fileToLoad.name);
  6299. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6300. };
  6301. reader.onload = function (e) {
  6302. //target doesn't have result from ts 1.3
  6303. callback(e.target['result']);
  6304. };
  6305. reader.onprogress = progressCallBack;
  6306. if (!useArrayBuffer) {
  6307. // Asynchronous read
  6308. reader.readAsText(fileToLoad);
  6309. }
  6310. else {
  6311. reader.readAsArrayBuffer(fileToLoad);
  6312. }
  6313. };
  6314. //returns a downloadable url to a file content.
  6315. Tools.FileAsURL = function (content) {
  6316. var fileBlob = new Blob([content]);
  6317. var url = window.URL || window.webkitURL;
  6318. var link = url.createObjectURL(fileBlob);
  6319. return link;
  6320. };
  6321. // Misc.
  6322. Tools.Format = function (value, decimals) {
  6323. if (decimals === void 0) { decimals = 2; }
  6324. return value.toFixed(decimals);
  6325. };
  6326. Tools.CheckExtends = function (v, min, max) {
  6327. if (v.x < min.x)
  6328. min.x = v.x;
  6329. if (v.y < min.y)
  6330. min.y = v.y;
  6331. if (v.z < min.z)
  6332. min.z = v.z;
  6333. if (v.x > max.x)
  6334. max.x = v.x;
  6335. if (v.y > max.y)
  6336. max.y = v.y;
  6337. if (v.z > max.z)
  6338. max.z = v.z;
  6339. };
  6340. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6341. for (var prop in source) {
  6342. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6343. continue;
  6344. }
  6345. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6346. continue;
  6347. }
  6348. var sourceValue = source[prop];
  6349. var typeOfSourceValue = typeof sourceValue;
  6350. if (typeOfSourceValue === "function") {
  6351. continue;
  6352. }
  6353. if (typeOfSourceValue === "object") {
  6354. if (sourceValue instanceof Array) {
  6355. destination[prop] = [];
  6356. if (sourceValue.length > 0) {
  6357. if (typeof sourceValue[0] == "object") {
  6358. for (var index = 0; index < sourceValue.length; index++) {
  6359. var clonedValue = cloneValue(sourceValue[index], destination);
  6360. if (destination[prop].indexOf(clonedValue) === -1) {
  6361. destination[prop].push(clonedValue);
  6362. }
  6363. }
  6364. }
  6365. else {
  6366. destination[prop] = sourceValue.slice(0);
  6367. }
  6368. }
  6369. }
  6370. else {
  6371. destination[prop] = cloneValue(sourceValue, destination);
  6372. }
  6373. }
  6374. else {
  6375. destination[prop] = sourceValue;
  6376. }
  6377. }
  6378. };
  6379. Tools.IsEmpty = function (obj) {
  6380. for (var i in obj) {
  6381. return false;
  6382. }
  6383. return true;
  6384. };
  6385. Tools.RegisterTopRootEvents = function (events) {
  6386. for (var index = 0; index < events.length; index++) {
  6387. var event = events[index];
  6388. window.addEventListener(event.name, event.handler, false);
  6389. try {
  6390. if (window.parent) {
  6391. window.parent.addEventListener(event.name, event.handler, false);
  6392. }
  6393. }
  6394. catch (e) {
  6395. }
  6396. }
  6397. };
  6398. Tools.UnregisterTopRootEvents = function (events) {
  6399. for (var index = 0; index < events.length; index++) {
  6400. var event = events[index];
  6401. window.removeEventListener(event.name, event.handler);
  6402. try {
  6403. if (window.parent) {
  6404. window.parent.removeEventListener(event.name, event.handler);
  6405. }
  6406. }
  6407. catch (e) {
  6408. }
  6409. }
  6410. };
  6411. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6412. if (mimeType === void 0) { mimeType = "image/png"; }
  6413. // Read the contents of the framebuffer
  6414. var numberOfChannelsByLine = width * 4;
  6415. var halfHeight = height / 2;
  6416. //Reading datas from WebGL
  6417. var data = engine.readPixels(0, 0, width, height);
  6418. //To flip image on Y axis.
  6419. for (var i = 0; i < halfHeight; i++) {
  6420. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6421. var currentCell = j + i * numberOfChannelsByLine;
  6422. var targetLine = height - i - 1;
  6423. var targetCell = j + targetLine * numberOfChannelsByLine;
  6424. var temp = data[currentCell];
  6425. data[currentCell] = data[targetCell];
  6426. data[targetCell] = temp;
  6427. }
  6428. }
  6429. // Create a 2D canvas to store the result
  6430. if (!screenshotCanvas) {
  6431. screenshotCanvas = document.createElement('canvas');
  6432. }
  6433. screenshotCanvas.width = width;
  6434. screenshotCanvas.height = height;
  6435. var context = screenshotCanvas.getContext('2d');
  6436. // Copy the pixels to a 2D canvas
  6437. var imageData = context.createImageData(width, height);
  6438. var castData = (imageData.data);
  6439. castData.set(data);
  6440. context.putImageData(imageData, 0, 0);
  6441. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6442. };
  6443. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6444. if (mimeType === void 0) { mimeType = "image/png"; }
  6445. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6446. if (successCallback) {
  6447. successCallback(base64Image);
  6448. }
  6449. else {
  6450. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6451. if (("download" in document.createElement("a"))) {
  6452. var a = window.document.createElement("a");
  6453. a.href = base64Image;
  6454. var date = new Date();
  6455. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6456. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6457. window.document.body.appendChild(a);
  6458. a.addEventListener("click", function () {
  6459. a.parentElement.removeChild(a);
  6460. });
  6461. a.click();
  6462. }
  6463. else {
  6464. var newWindow = window.open("");
  6465. var img = newWindow.document.createElement("img");
  6466. img.src = base64Image;
  6467. newWindow.document.body.appendChild(img);
  6468. }
  6469. }
  6470. };
  6471. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6472. if (mimeType === void 0) { mimeType = "image/png"; }
  6473. var width;
  6474. var height;
  6475. // If a precision value is specified
  6476. if (size.precision) {
  6477. width = Math.round(engine.getRenderWidth() * size.precision);
  6478. height = Math.round(width / engine.getAspectRatio(camera));
  6479. }
  6480. else if (size.width && size.height) {
  6481. width = size.width;
  6482. height = size.height;
  6483. }
  6484. else if (size.width && !size.height) {
  6485. width = size.width;
  6486. height = Math.round(width / engine.getAspectRatio(camera));
  6487. }
  6488. else if (size.height && !size.width) {
  6489. height = size.height;
  6490. width = Math.round(height * engine.getAspectRatio(camera));
  6491. }
  6492. else if (!isNaN(size)) {
  6493. height = size;
  6494. width = size;
  6495. }
  6496. else {
  6497. Tools.Error("Invalid 'size' parameter !");
  6498. return;
  6499. }
  6500. if (!screenshotCanvas) {
  6501. screenshotCanvas = document.createElement('canvas');
  6502. }
  6503. screenshotCanvas.width = width;
  6504. screenshotCanvas.height = height;
  6505. var renderContext = screenshotCanvas.getContext("2d");
  6506. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6507. var newWidth = width;
  6508. var newHeight = newWidth / ratio;
  6509. if (newHeight > height) {
  6510. newHeight = height;
  6511. newWidth = newHeight * ratio;
  6512. }
  6513. var offsetX = Math.max(0, width - newWidth) / 2;
  6514. var offsetY = Math.max(0, height - newHeight) / 2;
  6515. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6516. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6517. };
  6518. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  6519. if (mimeType === void 0) { mimeType = "image/png"; }
  6520. var width;
  6521. var height;
  6522. //If a precision value is specified
  6523. if (size.precision) {
  6524. width = Math.round(engine.getRenderWidth() * size.precision);
  6525. height = Math.round(width / engine.getAspectRatio(camera));
  6526. size = { width: width, height: height };
  6527. }
  6528. else if (size.width && size.height) {
  6529. width = size.width;
  6530. height = size.height;
  6531. }
  6532. else if (size.width && !size.height) {
  6533. width = size.width;
  6534. height = Math.round(width / engine.getAspectRatio(camera));
  6535. size = { width: width, height: height };
  6536. }
  6537. else if (size.height && !size.width) {
  6538. height = size.height;
  6539. width = Math.round(height * engine.getAspectRatio(camera));
  6540. size = { width: width, height: height };
  6541. }
  6542. else if (!isNaN(size)) {
  6543. height = size;
  6544. width = size;
  6545. }
  6546. else {
  6547. Tools.Error("Invalid 'size' parameter !");
  6548. return;
  6549. }
  6550. var scene = camera.getScene();
  6551. var previousCamera = null;
  6552. if (scene.activeCamera !== camera) {
  6553. previousCamera = scene.activeCamera;
  6554. scene.activeCamera = camera;
  6555. }
  6556. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6557. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6558. texture.renderList = scene.meshes;
  6559. texture.onAfterRenderObservable.add(function () {
  6560. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6561. });
  6562. scene.incrementRenderId();
  6563. scene.resetCachedMaterial();
  6564. texture.render(true);
  6565. texture.dispose();
  6566. if (previousCamera) {
  6567. scene.activeCamera = previousCamera;
  6568. }
  6569. camera.getProjectionMatrix(true); // Force cache refresh;
  6570. };
  6571. // XHR response validator for local file scenario
  6572. Tools.ValidateXHRData = function (xhr, dataType) {
  6573. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6574. if (dataType === void 0) { dataType = 7; }
  6575. try {
  6576. if (dataType & 1) {
  6577. if (xhr.responseText && xhr.responseText.length > 0) {
  6578. return true;
  6579. }
  6580. else if (dataType === 1) {
  6581. return false;
  6582. }
  6583. }
  6584. if (dataType & 2) {
  6585. // Check header width and height since there is no "TGA" magic number
  6586. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6587. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6588. return true;
  6589. }
  6590. else if (dataType === 2) {
  6591. return false;
  6592. }
  6593. }
  6594. if (dataType & 4) {
  6595. // Check for the "DDS" magic number
  6596. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6597. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6598. return true;
  6599. }
  6600. else {
  6601. return false;
  6602. }
  6603. }
  6604. }
  6605. catch (e) {
  6606. }
  6607. return false;
  6608. };
  6609. /**
  6610. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6611. * Be aware Math.random() could cause collisions, but:
  6612. * "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"
  6613. */
  6614. Tools.RandomId = function () {
  6615. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6616. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6617. return v.toString(16);
  6618. });
  6619. };
  6620. Object.defineProperty(Tools, "NoneLogLevel", {
  6621. get: function () {
  6622. return Tools._NoneLogLevel;
  6623. },
  6624. enumerable: true,
  6625. configurable: true
  6626. });
  6627. Object.defineProperty(Tools, "MessageLogLevel", {
  6628. get: function () {
  6629. return Tools._MessageLogLevel;
  6630. },
  6631. enumerable: true,
  6632. configurable: true
  6633. });
  6634. Object.defineProperty(Tools, "WarningLogLevel", {
  6635. get: function () {
  6636. return Tools._WarningLogLevel;
  6637. },
  6638. enumerable: true,
  6639. configurable: true
  6640. });
  6641. Object.defineProperty(Tools, "ErrorLogLevel", {
  6642. get: function () {
  6643. return Tools._ErrorLogLevel;
  6644. },
  6645. enumerable: true,
  6646. configurable: true
  6647. });
  6648. Object.defineProperty(Tools, "AllLogLevel", {
  6649. get: function () {
  6650. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6651. },
  6652. enumerable: true,
  6653. configurable: true
  6654. });
  6655. Tools._AddLogEntry = function (entry) {
  6656. Tools._LogCache = entry + Tools._LogCache;
  6657. if (Tools.OnNewCacheEntry) {
  6658. Tools.OnNewCacheEntry(entry);
  6659. }
  6660. };
  6661. Tools._FormatMessage = function (message) {
  6662. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6663. var date = new Date();
  6664. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6665. };
  6666. Tools._LogDisabled = function (message) {
  6667. // nothing to do
  6668. };
  6669. Tools._LogEnabled = function (message) {
  6670. var formattedMessage = Tools._FormatMessage(message);
  6671. console.log("BJS - " + formattedMessage);
  6672. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6673. Tools._AddLogEntry(entry);
  6674. };
  6675. Tools._WarnDisabled = function (message) {
  6676. // nothing to do
  6677. };
  6678. Tools._WarnEnabled = function (message) {
  6679. var formattedMessage = Tools._FormatMessage(message);
  6680. console.warn("BJS - " + formattedMessage);
  6681. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6682. Tools._AddLogEntry(entry);
  6683. };
  6684. Tools._ErrorDisabled = function (message) {
  6685. // nothing to do
  6686. };
  6687. Tools._ErrorEnabled = function (message) {
  6688. Tools.errorsCount++;
  6689. var formattedMessage = Tools._FormatMessage(message);
  6690. console.error("BJS - " + formattedMessage);
  6691. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6692. Tools._AddLogEntry(entry);
  6693. };
  6694. Object.defineProperty(Tools, "LogCache", {
  6695. get: function () {
  6696. return Tools._LogCache;
  6697. },
  6698. enumerable: true,
  6699. configurable: true
  6700. });
  6701. Tools.ClearLogCache = function () {
  6702. Tools._LogCache = "";
  6703. Tools.errorsCount = 0;
  6704. };
  6705. Object.defineProperty(Tools, "LogLevels", {
  6706. set: function (level) {
  6707. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6708. Tools.Log = Tools._LogEnabled;
  6709. }
  6710. else {
  6711. Tools.Log = Tools._LogDisabled;
  6712. }
  6713. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6714. Tools.Warn = Tools._WarnEnabled;
  6715. }
  6716. else {
  6717. Tools.Warn = Tools._WarnDisabled;
  6718. }
  6719. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6720. Tools.Error = Tools._ErrorEnabled;
  6721. }
  6722. else {
  6723. Tools.Error = Tools._ErrorDisabled;
  6724. }
  6725. },
  6726. enumerable: true,
  6727. configurable: true
  6728. });
  6729. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6730. get: function () {
  6731. return Tools._PerformanceNoneLogLevel;
  6732. },
  6733. enumerable: true,
  6734. configurable: true
  6735. });
  6736. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6737. get: function () {
  6738. return Tools._PerformanceUserMarkLogLevel;
  6739. },
  6740. enumerable: true,
  6741. configurable: true
  6742. });
  6743. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6744. get: function () {
  6745. return Tools._PerformanceConsoleLogLevel;
  6746. },
  6747. enumerable: true,
  6748. configurable: true
  6749. });
  6750. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6751. set: function (level) {
  6752. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6753. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6754. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6755. return;
  6756. }
  6757. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6758. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6759. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6760. return;
  6761. }
  6762. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6763. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6764. },
  6765. enumerable: true,
  6766. configurable: true
  6767. });
  6768. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6769. };
  6770. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6771. };
  6772. Tools._StartUserMark = function (counterName, condition) {
  6773. if (condition === void 0) { condition = true; }
  6774. if (!condition || !Tools._performance.mark) {
  6775. return;
  6776. }
  6777. Tools._performance.mark(counterName + "-Begin");
  6778. };
  6779. Tools._EndUserMark = function (counterName, condition) {
  6780. if (condition === void 0) { condition = true; }
  6781. if (!condition || !Tools._performance.mark) {
  6782. return;
  6783. }
  6784. Tools._performance.mark(counterName + "-End");
  6785. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6786. };
  6787. Tools._StartPerformanceConsole = function (counterName, condition) {
  6788. if (condition === void 0) { condition = true; }
  6789. if (!condition) {
  6790. return;
  6791. }
  6792. Tools._StartUserMark(counterName, condition);
  6793. if (console.time) {
  6794. console.time(counterName);
  6795. }
  6796. };
  6797. Tools._EndPerformanceConsole = function (counterName, condition) {
  6798. if (condition === void 0) { condition = true; }
  6799. if (!condition) {
  6800. return;
  6801. }
  6802. Tools._EndUserMark(counterName, condition);
  6803. if (console.time) {
  6804. console.timeEnd(counterName);
  6805. }
  6806. };
  6807. Object.defineProperty(Tools, "Now", {
  6808. get: function () {
  6809. if (window.performance && window.performance.now) {
  6810. return window.performance.now();
  6811. }
  6812. return new Date().getTime();
  6813. },
  6814. enumerable: true,
  6815. configurable: true
  6816. });
  6817. /**
  6818. * This method will return the name of the class used to create the instance of the given object.
  6819. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6820. * @param object the object to get the class name from
  6821. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6822. */
  6823. Tools.getClassName = function (object, isType) {
  6824. if (isType === void 0) { isType = false; }
  6825. var name = null;
  6826. if (!isType && object.getClassName) {
  6827. name = object.getClassName();
  6828. }
  6829. else {
  6830. if (object instanceof Object) {
  6831. var classObj = isType ? object : Object.getPrototypeOf(object);
  6832. name = classObj.constructor["__bjsclassName__"];
  6833. }
  6834. if (!name) {
  6835. name = typeof object;
  6836. }
  6837. }
  6838. return name;
  6839. };
  6840. Tools.first = function (array, predicate) {
  6841. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6842. var el = array_1[_i];
  6843. if (predicate(el)) {
  6844. return el;
  6845. }
  6846. }
  6847. };
  6848. /**
  6849. * This method will return the name of the full name of the class, including its owning module (if any).
  6850. * 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).
  6851. * @param object the object to get the class name from
  6852. * @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.
  6853. */
  6854. Tools.getFullClassName = function (object, isType) {
  6855. if (isType === void 0) { isType = false; }
  6856. var className = null;
  6857. var moduleName = null;
  6858. if (!isType && object.getClassName) {
  6859. className = object.getClassName();
  6860. }
  6861. else {
  6862. if (object instanceof Object) {
  6863. var classObj = isType ? object : Object.getPrototypeOf(object);
  6864. className = classObj.constructor["__bjsclassName__"];
  6865. moduleName = classObj.constructor["__bjsmoduleName__"];
  6866. }
  6867. if (!className) {
  6868. className = typeof object;
  6869. }
  6870. }
  6871. if (!className) {
  6872. return null;
  6873. }
  6874. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6875. };
  6876. /**
  6877. * 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.
  6878. * @param array
  6879. */
  6880. Tools.arrayOrStringFeeder = function (array) {
  6881. return function (index) {
  6882. if (index >= array.length) {
  6883. return null;
  6884. }
  6885. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6886. if (val && val.getHashCode) {
  6887. val = val.getHashCode();
  6888. }
  6889. if (typeof val === "string") {
  6890. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6891. }
  6892. return val;
  6893. };
  6894. };
  6895. /**
  6896. * Compute the hashCode of a stream of number
  6897. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6898. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6899. * @return the hash code computed
  6900. */
  6901. Tools.hashCodeFromStream = function (feeder) {
  6902. // Based from here: http://stackoverflow.com/a/7616484/802124
  6903. var hash = 0;
  6904. var index = 0;
  6905. var chr = feeder(index++);
  6906. while (chr != null) {
  6907. hash = ((hash << 5) - hash) + chr;
  6908. hash |= 0; // Convert to 32bit integer
  6909. chr = feeder(index++);
  6910. }
  6911. return hash;
  6912. };
  6913. return Tools;
  6914. }());
  6915. Tools.BaseUrl = "";
  6916. Tools.CorsBehavior = "anonymous";
  6917. Tools.UseFallbackTexture = true;
  6918. // Used in case of a texture loading problem
  6919. 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";
  6920. // Logs
  6921. Tools._NoneLogLevel = 0;
  6922. Tools._MessageLogLevel = 1;
  6923. Tools._WarningLogLevel = 2;
  6924. Tools._ErrorLogLevel = 4;
  6925. Tools._LogCache = "";
  6926. Tools.errorsCount = 0;
  6927. Tools.Log = Tools._LogEnabled;
  6928. Tools.Warn = Tools._WarnEnabled;
  6929. Tools.Error = Tools._ErrorEnabled;
  6930. // Performances
  6931. Tools._PerformanceNoneLogLevel = 0;
  6932. Tools._PerformanceUserMarkLogLevel = 1;
  6933. Tools._PerformanceConsoleLogLevel = 2;
  6934. Tools._performance = window.performance;
  6935. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6936. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6937. BABYLON.Tools = Tools;
  6938. /**
  6939. * This class is used to track a performance counter which is number based.
  6940. * The user has access to many properties which give statistics of different nature
  6941. *
  6942. * The implementer can track two kinds of Performance Counter: time and count
  6943. * 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.
  6944. * 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.
  6945. */
  6946. var PerfCounter = (function () {
  6947. function PerfCounter() {
  6948. this._startMonitoringTime = 0;
  6949. this._min = 0;
  6950. this._max = 0;
  6951. this._average = 0;
  6952. this._lastSecAverage = 0;
  6953. this._current = 0;
  6954. this._totalValueCount = 0;
  6955. this._totalAccumulated = 0;
  6956. this._lastSecAccumulated = 0;
  6957. this._lastSecTime = 0;
  6958. this._lastSecValueCount = 0;
  6959. }
  6960. Object.defineProperty(PerfCounter.prototype, "min", {
  6961. /**
  6962. * Returns the smallest value ever
  6963. */
  6964. get: function () {
  6965. return this._min;
  6966. },
  6967. enumerable: true,
  6968. configurable: true
  6969. });
  6970. Object.defineProperty(PerfCounter.prototype, "max", {
  6971. /**
  6972. * Returns the biggest value ever
  6973. */
  6974. get: function () {
  6975. return this._max;
  6976. },
  6977. enumerable: true,
  6978. configurable: true
  6979. });
  6980. Object.defineProperty(PerfCounter.prototype, "average", {
  6981. /**
  6982. * Returns the average value since the performance counter is running
  6983. */
  6984. get: function () {
  6985. return this._average;
  6986. },
  6987. enumerable: true,
  6988. configurable: true
  6989. });
  6990. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6991. /**
  6992. * Returns the average value of the last second the counter was monitored
  6993. */
  6994. get: function () {
  6995. return this._lastSecAverage;
  6996. },
  6997. enumerable: true,
  6998. configurable: true
  6999. });
  7000. Object.defineProperty(PerfCounter.prototype, "current", {
  7001. /**
  7002. * Returns the current value
  7003. */
  7004. get: function () {
  7005. return this._current;
  7006. },
  7007. enumerable: true,
  7008. configurable: true
  7009. });
  7010. Object.defineProperty(PerfCounter.prototype, "total", {
  7011. get: function () {
  7012. return this._totalAccumulated;
  7013. },
  7014. enumerable: true,
  7015. configurable: true
  7016. });
  7017. /**
  7018. * Call this method to start monitoring a new frame.
  7019. * 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.
  7020. */
  7021. PerfCounter.prototype.fetchNewFrame = function () {
  7022. this._totalValueCount++;
  7023. this._current = 0;
  7024. this._lastSecValueCount++;
  7025. };
  7026. /**
  7027. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7028. * @param newCount the count value to add to the monitored count
  7029. * @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.
  7030. */
  7031. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7032. this._current += newCount;
  7033. if (fetchResult) {
  7034. this._fetchResult();
  7035. }
  7036. };
  7037. /**
  7038. * Start monitoring this performance counter
  7039. */
  7040. PerfCounter.prototype.beginMonitoring = function () {
  7041. this._startMonitoringTime = Tools.Now;
  7042. };
  7043. /**
  7044. * Compute the time lapsed since the previous beginMonitoring() call.
  7045. * @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
  7046. */
  7047. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7048. if (newFrame === void 0) { newFrame = true; }
  7049. if (newFrame) {
  7050. this.fetchNewFrame();
  7051. }
  7052. var currentTime = Tools.Now;
  7053. this._current = currentTime - this._startMonitoringTime;
  7054. if (newFrame) {
  7055. this._fetchResult();
  7056. }
  7057. };
  7058. PerfCounter.prototype._fetchResult = function () {
  7059. this._totalAccumulated += this._current;
  7060. this._lastSecAccumulated += this._current;
  7061. // Min/Max update
  7062. this._min = Math.min(this._min, this._current);
  7063. this._max = Math.max(this._max, this._current);
  7064. this._average = this._totalAccumulated / this._totalValueCount;
  7065. // Reset last sec?
  7066. var now = Tools.Now;
  7067. if ((now - this._lastSecTime) > 1000) {
  7068. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7069. this._lastSecTime = now;
  7070. this._lastSecAccumulated = 0;
  7071. this._lastSecValueCount = 0;
  7072. }
  7073. };
  7074. return PerfCounter;
  7075. }());
  7076. BABYLON.PerfCounter = PerfCounter;
  7077. /**
  7078. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7079. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7080. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7081. * @param name The name of the class, case should be preserved
  7082. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7083. */
  7084. function className(name, module) {
  7085. return function (target) {
  7086. target["__bjsclassName__"] = name;
  7087. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7088. };
  7089. }
  7090. BABYLON.className = className;
  7091. /**
  7092. * An implementation of a loop for asynchronous functions.
  7093. */
  7094. var AsyncLoop = (function () {
  7095. /**
  7096. * Constroctor.
  7097. * @param iterations the number of iterations.
  7098. * @param _fn the function to run each iteration
  7099. * @param _successCallback the callback that will be called upon succesful execution
  7100. * @param offset starting offset.
  7101. */
  7102. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7103. if (offset === void 0) { offset = 0; }
  7104. this.iterations = iterations;
  7105. this._fn = _fn;
  7106. this._successCallback = _successCallback;
  7107. this.index = offset - 1;
  7108. this._done = false;
  7109. }
  7110. /**
  7111. * Execute the next iteration. Must be called after the last iteration was finished.
  7112. */
  7113. AsyncLoop.prototype.executeNext = function () {
  7114. if (!this._done) {
  7115. if (this.index + 1 < this.iterations) {
  7116. ++this.index;
  7117. this._fn(this);
  7118. }
  7119. else {
  7120. this.breakLoop();
  7121. }
  7122. }
  7123. };
  7124. /**
  7125. * Break the loop and run the success callback.
  7126. */
  7127. AsyncLoop.prototype.breakLoop = function () {
  7128. this._done = true;
  7129. this._successCallback();
  7130. };
  7131. /**
  7132. * Helper function
  7133. */
  7134. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7135. if (offset === void 0) { offset = 0; }
  7136. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7137. loop.executeNext();
  7138. return loop;
  7139. };
  7140. /**
  7141. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7142. * @param iterations total number of iterations
  7143. * @param syncedIterations number of synchronous iterations in each async iteration.
  7144. * @param fn the function to call each iteration.
  7145. * @param callback a success call back that will be called when iterating stops.
  7146. * @param breakFunction a break condition (optional)
  7147. * @param timeout timeout settings for the setTimeout function. default - 0.
  7148. * @constructor
  7149. */
  7150. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7151. if (timeout === void 0) { timeout = 0; }
  7152. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7153. if (breakFunction && breakFunction())
  7154. loop.breakLoop();
  7155. else {
  7156. setTimeout(function () {
  7157. for (var i = 0; i < syncedIterations; ++i) {
  7158. var iteration = (loop.index * syncedIterations) + i;
  7159. if (iteration >= iterations)
  7160. break;
  7161. fn(iteration);
  7162. if (breakFunction && breakFunction()) {
  7163. loop.breakLoop();
  7164. break;
  7165. }
  7166. }
  7167. loop.executeNext();
  7168. }, timeout);
  7169. }
  7170. }, callback);
  7171. };
  7172. return AsyncLoop;
  7173. }());
  7174. BABYLON.AsyncLoop = AsyncLoop;
  7175. })(BABYLON || (BABYLON = {}));
  7176. //# sourceMappingURL=babylon.tools.js.map
  7177. var BABYLON;
  7178. (function (BABYLON) {
  7179. var Internals;
  7180. (function (Internals) {
  7181. var _AlphaState = (function () {
  7182. /**
  7183. * Initializes the state.
  7184. */
  7185. function _AlphaState() {
  7186. this._isAlphaBlendDirty = false;
  7187. this._isBlendFunctionParametersDirty = false;
  7188. this._alphaBlend = false;
  7189. this._blendFunctionParameters = new Array(4);
  7190. this.reset();
  7191. }
  7192. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7193. get: function () {
  7194. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7195. },
  7196. enumerable: true,
  7197. configurable: true
  7198. });
  7199. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7200. get: function () {
  7201. return this._alphaBlend;
  7202. },
  7203. set: function (value) {
  7204. if (this._alphaBlend === value) {
  7205. return;
  7206. }
  7207. this._alphaBlend = value;
  7208. this._isAlphaBlendDirty = true;
  7209. },
  7210. enumerable: true,
  7211. configurable: true
  7212. });
  7213. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7214. if (this._blendFunctionParameters[0] === value0 &&
  7215. this._blendFunctionParameters[1] === value1 &&
  7216. this._blendFunctionParameters[2] === value2 &&
  7217. this._blendFunctionParameters[3] === value3) {
  7218. return;
  7219. }
  7220. this._blendFunctionParameters[0] = value0;
  7221. this._blendFunctionParameters[1] = value1;
  7222. this._blendFunctionParameters[2] = value2;
  7223. this._blendFunctionParameters[3] = value3;
  7224. this._isBlendFunctionParametersDirty = true;
  7225. };
  7226. _AlphaState.prototype.reset = function () {
  7227. this._alphaBlend = false;
  7228. this._blendFunctionParameters[0] = null;
  7229. this._blendFunctionParameters[1] = null;
  7230. this._blendFunctionParameters[2] = null;
  7231. this._blendFunctionParameters[3] = null;
  7232. this._isAlphaBlendDirty = true;
  7233. this._isBlendFunctionParametersDirty = false;
  7234. };
  7235. _AlphaState.prototype.apply = function (gl) {
  7236. if (!this.isDirty) {
  7237. return;
  7238. }
  7239. // Alpha blend
  7240. if (this._isAlphaBlendDirty) {
  7241. if (this._alphaBlend) {
  7242. gl.enable(gl.BLEND);
  7243. }
  7244. else {
  7245. gl.disable(gl.BLEND);
  7246. }
  7247. this._isAlphaBlendDirty = false;
  7248. }
  7249. // Alpha function
  7250. if (this._isBlendFunctionParametersDirty) {
  7251. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7252. this._isBlendFunctionParametersDirty = false;
  7253. }
  7254. };
  7255. return _AlphaState;
  7256. }());
  7257. Internals._AlphaState = _AlphaState;
  7258. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7259. })(BABYLON || (BABYLON = {}));
  7260. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7261. var BABYLON;
  7262. (function (BABYLON) {
  7263. var Internals;
  7264. (function (Internals) {
  7265. var _DepthCullingState = (function () {
  7266. /**
  7267. * Initializes the state.
  7268. */
  7269. function _DepthCullingState() {
  7270. this._isDepthTestDirty = false;
  7271. this._isDepthMaskDirty = false;
  7272. this._isDepthFuncDirty = false;
  7273. this._isCullFaceDirty = false;
  7274. this._isCullDirty = false;
  7275. this._isZOffsetDirty = false;
  7276. this.reset();
  7277. }
  7278. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7279. get: function () {
  7280. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7281. },
  7282. enumerable: true,
  7283. configurable: true
  7284. });
  7285. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7286. get: function () {
  7287. return this._zOffset;
  7288. },
  7289. set: function (value) {
  7290. if (this._zOffset === value) {
  7291. return;
  7292. }
  7293. this._zOffset = value;
  7294. this._isZOffsetDirty = true;
  7295. },
  7296. enumerable: true,
  7297. configurable: true
  7298. });
  7299. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7300. get: function () {
  7301. return this._cullFace;
  7302. },
  7303. set: function (value) {
  7304. if (this._cullFace === value) {
  7305. return;
  7306. }
  7307. this._cullFace = value;
  7308. this._isCullFaceDirty = true;
  7309. },
  7310. enumerable: true,
  7311. configurable: true
  7312. });
  7313. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7314. get: function () {
  7315. return this._cull;
  7316. },
  7317. set: function (value) {
  7318. if (this._cull === value) {
  7319. return;
  7320. }
  7321. this._cull = value;
  7322. this._isCullDirty = true;
  7323. },
  7324. enumerable: true,
  7325. configurable: true
  7326. });
  7327. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7328. get: function () {
  7329. return this._depthFunc;
  7330. },
  7331. set: function (value) {
  7332. if (this._depthFunc === value) {
  7333. return;
  7334. }
  7335. this._depthFunc = value;
  7336. this._isDepthFuncDirty = true;
  7337. },
  7338. enumerable: true,
  7339. configurable: true
  7340. });
  7341. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7342. get: function () {
  7343. return this._depthMask;
  7344. },
  7345. set: function (value) {
  7346. if (this._depthMask === value) {
  7347. return;
  7348. }
  7349. this._depthMask = value;
  7350. this._isDepthMaskDirty = true;
  7351. },
  7352. enumerable: true,
  7353. configurable: true
  7354. });
  7355. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7356. get: function () {
  7357. return this._depthTest;
  7358. },
  7359. set: function (value) {
  7360. if (this._depthTest === value) {
  7361. return;
  7362. }
  7363. this._depthTest = value;
  7364. this._isDepthTestDirty = true;
  7365. },
  7366. enumerable: true,
  7367. configurable: true
  7368. });
  7369. _DepthCullingState.prototype.reset = function () {
  7370. this._depthMask = true;
  7371. this._depthTest = true;
  7372. this._depthFunc = null;
  7373. this._cullFace = null;
  7374. this._cull = null;
  7375. this._zOffset = 0;
  7376. this._isDepthTestDirty = true;
  7377. this._isDepthMaskDirty = true;
  7378. this._isDepthFuncDirty = false;
  7379. this._isCullFaceDirty = false;
  7380. this._isCullDirty = false;
  7381. this._isZOffsetDirty = false;
  7382. };
  7383. _DepthCullingState.prototype.apply = function (gl) {
  7384. if (!this.isDirty) {
  7385. return;
  7386. }
  7387. // Cull
  7388. if (this._isCullDirty) {
  7389. if (this.cull) {
  7390. gl.enable(gl.CULL_FACE);
  7391. }
  7392. else {
  7393. gl.disable(gl.CULL_FACE);
  7394. }
  7395. this._isCullDirty = false;
  7396. }
  7397. // Cull face
  7398. if (this._isCullFaceDirty) {
  7399. gl.cullFace(this.cullFace);
  7400. this._isCullFaceDirty = false;
  7401. }
  7402. // Depth mask
  7403. if (this._isDepthMaskDirty) {
  7404. gl.depthMask(this.depthMask);
  7405. this._isDepthMaskDirty = false;
  7406. }
  7407. // Depth test
  7408. if (this._isDepthTestDirty) {
  7409. if (this.depthTest) {
  7410. gl.enable(gl.DEPTH_TEST);
  7411. }
  7412. else {
  7413. gl.disable(gl.DEPTH_TEST);
  7414. }
  7415. this._isDepthTestDirty = false;
  7416. }
  7417. // Depth func
  7418. if (this._isDepthFuncDirty) {
  7419. gl.depthFunc(this.depthFunc);
  7420. this._isDepthFuncDirty = false;
  7421. }
  7422. // zOffset
  7423. if (this._isZOffsetDirty) {
  7424. if (this.zOffset) {
  7425. gl.enable(gl.POLYGON_OFFSET_FILL);
  7426. gl.polygonOffset(this.zOffset, 0);
  7427. }
  7428. else {
  7429. gl.disable(gl.POLYGON_OFFSET_FILL);
  7430. }
  7431. this._isZOffsetDirty = false;
  7432. }
  7433. };
  7434. return _DepthCullingState;
  7435. }());
  7436. Internals._DepthCullingState = _DepthCullingState;
  7437. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7438. })(BABYLON || (BABYLON = {}));
  7439. //# sourceMappingURL=babylon.depthCullingState.js.map
  7440. var BABYLON;
  7441. (function (BABYLON) {
  7442. var Internals;
  7443. (function (Internals) {
  7444. var _StencilState = (function () {
  7445. function _StencilState() {
  7446. this._isStencilTestDirty = false;
  7447. this._isStencilMaskDirty = false;
  7448. this._isStencilFuncDirty = false;
  7449. this._isStencilOpDirty = false;
  7450. this.reset();
  7451. }
  7452. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7453. get: function () {
  7454. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7455. },
  7456. enumerable: true,
  7457. configurable: true
  7458. });
  7459. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7460. get: function () {
  7461. return this._stencilFunc;
  7462. },
  7463. set: function (value) {
  7464. if (this._stencilFunc === value) {
  7465. return;
  7466. }
  7467. this._stencilFunc = value;
  7468. this._isStencilFuncDirty = true;
  7469. },
  7470. enumerable: true,
  7471. configurable: true
  7472. });
  7473. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7474. get: function () {
  7475. return this._stencilFuncRef;
  7476. },
  7477. set: function (value) {
  7478. if (this._stencilFuncRef === value) {
  7479. return;
  7480. }
  7481. this._stencilFuncRef = value;
  7482. this._isStencilFuncDirty = true;
  7483. },
  7484. enumerable: true,
  7485. configurable: true
  7486. });
  7487. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7488. get: function () {
  7489. return this._stencilFuncMask;
  7490. },
  7491. set: function (value) {
  7492. if (this._stencilFuncMask === value) {
  7493. return;
  7494. }
  7495. this._stencilFuncMask = value;
  7496. this._isStencilFuncDirty = true;
  7497. },
  7498. enumerable: true,
  7499. configurable: true
  7500. });
  7501. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7502. get: function () {
  7503. return this._stencilOpStencilFail;
  7504. },
  7505. set: function (value) {
  7506. if (this._stencilOpStencilFail === value) {
  7507. return;
  7508. }
  7509. this._stencilOpStencilFail = value;
  7510. this._isStencilOpDirty = true;
  7511. },
  7512. enumerable: true,
  7513. configurable: true
  7514. });
  7515. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7516. get: function () {
  7517. return this._stencilOpDepthFail;
  7518. },
  7519. set: function (value) {
  7520. if (this._stencilOpDepthFail === value) {
  7521. return;
  7522. }
  7523. this._stencilOpDepthFail = value;
  7524. this._isStencilOpDirty = true;
  7525. },
  7526. enumerable: true,
  7527. configurable: true
  7528. });
  7529. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7530. get: function () {
  7531. return this._stencilOpStencilDepthPass;
  7532. },
  7533. set: function (value) {
  7534. if (this._stencilOpStencilDepthPass === value) {
  7535. return;
  7536. }
  7537. this._stencilOpStencilDepthPass = value;
  7538. this._isStencilOpDirty = true;
  7539. },
  7540. enumerable: true,
  7541. configurable: true
  7542. });
  7543. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7544. get: function () {
  7545. return this._stencilMask;
  7546. },
  7547. set: function (value) {
  7548. if (this._stencilMask === value) {
  7549. return;
  7550. }
  7551. this._stencilMask = value;
  7552. this._isStencilMaskDirty = true;
  7553. },
  7554. enumerable: true,
  7555. configurable: true
  7556. });
  7557. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7558. get: function () {
  7559. return this._stencilTest;
  7560. },
  7561. set: function (value) {
  7562. if (this._stencilTest === value) {
  7563. return;
  7564. }
  7565. this._stencilTest = value;
  7566. this._isStencilTestDirty = true;
  7567. },
  7568. enumerable: true,
  7569. configurable: true
  7570. });
  7571. _StencilState.prototype.reset = function () {
  7572. this._stencilTest = false;
  7573. this._stencilMask = 0xFF;
  7574. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7575. this._stencilFuncRef = 1;
  7576. this._stencilFuncMask = 0xFF;
  7577. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7578. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7579. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7580. this._isStencilTestDirty = true;
  7581. this._isStencilMaskDirty = true;
  7582. this._isStencilFuncDirty = true;
  7583. this._isStencilOpDirty = true;
  7584. };
  7585. _StencilState.prototype.apply = function (gl) {
  7586. if (!this.isDirty) {
  7587. return;
  7588. }
  7589. // Stencil test
  7590. if (this._isStencilTestDirty) {
  7591. if (this.stencilTest) {
  7592. gl.enable(gl.STENCIL_TEST);
  7593. }
  7594. else {
  7595. gl.disable(gl.STENCIL_TEST);
  7596. }
  7597. this._isStencilTestDirty = false;
  7598. }
  7599. // Stencil mask
  7600. if (this._isStencilMaskDirty) {
  7601. gl.stencilMask(this.stencilMask);
  7602. this._isStencilMaskDirty = false;
  7603. }
  7604. // Stencil func
  7605. if (this._isStencilFuncDirty) {
  7606. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7607. this._isStencilFuncDirty = false;
  7608. }
  7609. // Stencil op
  7610. if (this._isStencilOpDirty) {
  7611. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7612. this._isStencilOpDirty = false;
  7613. }
  7614. };
  7615. return _StencilState;
  7616. }());
  7617. Internals._StencilState = _StencilState;
  7618. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7619. })(BABYLON || (BABYLON = {}));
  7620. //# sourceMappingURL=babylon.stencilState.js.map
  7621. var BABYLON;
  7622. (function (BABYLON) {
  7623. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7624. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7625. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7626. gl.compileShader(shader);
  7627. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7628. throw new Error(gl.getShaderInfoLog(shader));
  7629. }
  7630. return shader;
  7631. };
  7632. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7633. var magFilter = gl.NEAREST;
  7634. var minFilter = gl.NEAREST;
  7635. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7636. magFilter = gl.LINEAR;
  7637. if (generateMipMaps) {
  7638. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7639. }
  7640. else {
  7641. minFilter = gl.LINEAR;
  7642. }
  7643. }
  7644. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7645. magFilter = gl.LINEAR;
  7646. if (generateMipMaps) {
  7647. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7648. }
  7649. else {
  7650. minFilter = gl.LINEAR;
  7651. }
  7652. }
  7653. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7654. magFilter = gl.NEAREST;
  7655. if (generateMipMaps) {
  7656. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7657. }
  7658. else {
  7659. minFilter = gl.NEAREST;
  7660. }
  7661. }
  7662. return {
  7663. min: minFilter,
  7664. mag: magFilter
  7665. };
  7666. };
  7667. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7668. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7669. var engine = scene.getEngine();
  7670. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7671. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7672. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7673. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7674. texture._baseWidth = width;
  7675. texture._baseHeight = height;
  7676. texture._width = potWidth;
  7677. texture._height = potHeight;
  7678. texture.isReady = true;
  7679. processFunction(potWidth, potHeight);
  7680. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7681. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7682. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7683. if (!noMipmap && !isCompressed) {
  7684. gl.generateMipmap(gl.TEXTURE_2D);
  7685. }
  7686. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7687. engine.resetTextureCache();
  7688. scene._removePendingData(texture);
  7689. texture.onLoadedCallbacks.forEach(function (callback) {
  7690. callback();
  7691. });
  7692. texture.onLoadedCallbacks = [];
  7693. };
  7694. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7695. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7696. var img;
  7697. var onload = function () {
  7698. loadedImages[index] = img;
  7699. loadedImages._internalCount++;
  7700. scene._removePendingData(img);
  7701. if (loadedImages._internalCount === 6) {
  7702. onfinish(loadedImages);
  7703. }
  7704. };
  7705. var onerror = function () {
  7706. scene._removePendingData(img);
  7707. if (onErrorCallBack) {
  7708. onErrorCallBack();
  7709. }
  7710. };
  7711. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7712. scene._addPendingData(img);
  7713. };
  7714. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7715. if (onError === void 0) { onError = null; }
  7716. var loadedImages = [];
  7717. loadedImages._internalCount = 0;
  7718. for (var index = 0; index < 6; index++) {
  7719. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7720. }
  7721. };
  7722. var InstancingAttributeInfo = (function () {
  7723. function InstancingAttributeInfo() {
  7724. }
  7725. return InstancingAttributeInfo;
  7726. }());
  7727. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7728. var EngineCapabilities = (function () {
  7729. function EngineCapabilities() {
  7730. }
  7731. return EngineCapabilities;
  7732. }());
  7733. BABYLON.EngineCapabilities = EngineCapabilities;
  7734. /**
  7735. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7736. */
  7737. var Engine = (function () {
  7738. /**
  7739. * @constructor
  7740. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7741. * @param {boolean} [antialias] - enable antialias
  7742. * @param options - further options to be sent to the getContext function
  7743. */
  7744. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7745. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7746. var _this = this;
  7747. // Public members
  7748. this.isFullscreen = false;
  7749. this.isPointerLock = false;
  7750. this.cullBackFaces = true;
  7751. this.renderEvenInBackground = true;
  7752. // To enable/disable IDB support and avoid XHR on .manifest
  7753. this.enableOfflineSupport = true;
  7754. this.scenes = new Array();
  7755. this._windowIsBackground = false;
  7756. this._webGLVersion = 1.0;
  7757. this._badOS = false;
  7758. this._drawCalls = new BABYLON.PerfCounter();
  7759. this._renderingQueueLaunched = false;
  7760. this._activeRenderLoops = [];
  7761. // FPS
  7762. this.fpsRange = 60;
  7763. this.previousFramesDuration = [];
  7764. this.fps = 60;
  7765. this.deltaTime = 0;
  7766. // States
  7767. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7768. this._stencilState = new BABYLON.Internals._StencilState();
  7769. this._alphaState = new BABYLON.Internals._AlphaState();
  7770. this._alphaMode = Engine.ALPHA_DISABLE;
  7771. // Cache
  7772. this._loadedTexturesCache = new Array();
  7773. this._maxTextureChannels = 16;
  7774. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7775. this._compiledEffects = {};
  7776. this._vertexAttribArraysEnabled = [];
  7777. this._uintIndicesCurrentlySet = false;
  7778. this._currentBoundBuffer = new Array();
  7779. this._currentBufferPointers = [];
  7780. this._currentInstanceLocations = new Array();
  7781. this._currentInstanceBuffers = new Array();
  7782. this._vaoRecordInProgress = false;
  7783. this._mustWipeVertexAttributes = false;
  7784. // Hardware supported Compressed Textures
  7785. this._texturesSupported = new Array();
  7786. this._onVRFullScreenTriggered = function () {
  7787. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7788. //get the old size before we change
  7789. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7790. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7791. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  7792. //But actually, no browser follow the specs...
  7793. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  7794. //get the width and height, change the render size
  7795. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7796. var width, height;
  7797. _this.setHardwareScalingLevel(1);
  7798. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7799. }
  7800. else {
  7801. //When the specs are implemented, need to uncomment this.
  7802. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7803. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7804. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7805. _this._vrDisplayEnabled = undefined;
  7806. }
  7807. };
  7808. this._renderingCanvas = canvas;
  7809. Engine.Instances.push(this);
  7810. this._externalData = new BABYLON.StringDictionary();
  7811. options = options || {};
  7812. if (antialias != null) {
  7813. options.antialias = antialias;
  7814. }
  7815. if (options.preserveDrawingBuffer === undefined) {
  7816. options.preserveDrawingBuffer = false;
  7817. }
  7818. // GL
  7819. if (!options.disableWebGL2Support) {
  7820. try {
  7821. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7822. if (this._gl) {
  7823. this._webGLVersion = 2.0;
  7824. }
  7825. }
  7826. catch (e) {
  7827. }
  7828. }
  7829. if (!this._gl) {
  7830. if (!canvas) {
  7831. throw new Error("The provided canvas is null or undefined.");
  7832. }
  7833. try {
  7834. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7835. }
  7836. catch (e) {
  7837. throw new Error("WebGL not supported");
  7838. }
  7839. }
  7840. if (!this._gl) {
  7841. throw new Error("WebGL not supported");
  7842. }
  7843. this._onBlur = function () {
  7844. _this._windowIsBackground = true;
  7845. };
  7846. this._onFocus = function () {
  7847. _this._windowIsBackground = false;
  7848. };
  7849. window.addEventListener("blur", this._onBlur);
  7850. window.addEventListener("focus", this._onFocus);
  7851. // Viewport
  7852. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7853. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7854. this.resize();
  7855. // Caps
  7856. this._isStencilEnable = options.stencil;
  7857. this._caps = new EngineCapabilities();
  7858. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7859. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7860. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7861. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7862. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7863. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7864. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7865. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7866. // Infos
  7867. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7868. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7869. if (rendererInfo != null) {
  7870. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7871. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7872. }
  7873. if (!this._glVendor) {
  7874. this._glVendor = "Unknown vendor";
  7875. }
  7876. if (!this._glRenderer) {
  7877. this._glRenderer = "Unknown renderer";
  7878. }
  7879. // Extensions
  7880. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7881. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7882. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7883. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7884. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7885. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7886. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7887. this._caps.atc = this._gl.getExtension('WEBGL_compressed_texture_atc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_atc');
  7888. 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');
  7889. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7890. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7891. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7892. this._caps.highPrecisionShaderSupported = true;
  7893. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7894. // Checks if some of the format renders first to allow the use of webgl inspector.
  7895. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7896. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7897. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7898. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7899. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7900. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7901. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7902. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7903. // Vertex array object
  7904. if (this._webGLVersion > 1) {
  7905. this._caps.vertexArrayObject = true;
  7906. }
  7907. else {
  7908. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7909. if (vertexArrayObjectExtension != null) {
  7910. this._caps.vertexArrayObject = true;
  7911. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7912. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7913. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7914. }
  7915. else {
  7916. this._caps.vertexArrayObject = false;
  7917. }
  7918. }
  7919. // Instances count
  7920. if (this._webGLVersion > 1) {
  7921. this._caps.instancedArrays = true;
  7922. }
  7923. else {
  7924. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7925. if (instanceExtension != null) {
  7926. this._caps.instancedArrays = true;
  7927. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7928. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7929. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7930. }
  7931. else {
  7932. this._caps.instancedArrays = false;
  7933. }
  7934. }
  7935. // Intelligently add supported compressed formats in order to check for.
  7936. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7937. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7938. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7939. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7940. // ATC before ETC1, since both old (widely supported), but ATC supports alpha, but ETC1 does not
  7941. if (this._caps.astc)
  7942. this.texturesSupported.push('-astc.ktx');
  7943. if (this._caps.s3tc)
  7944. this.texturesSupported.push('-dxt.ktx');
  7945. if (this._caps.pvrtc)
  7946. this.texturesSupported.push('-pvrtc.ktx');
  7947. if (this._caps.etc2)
  7948. this.texturesSupported.push('-etc2.ktx');
  7949. if (this._caps.atc)
  7950. this.texturesSupported.push('-atc.ktx');
  7951. if (this._caps.etc1)
  7952. this.texturesSupported.push('-etc1.ktx');
  7953. if (this._gl.getShaderPrecisionFormat) {
  7954. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7955. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7956. }
  7957. // Depth buffer
  7958. this.setDepthBuffer(true);
  7959. this.setDepthFunctionToLessOrEqual();
  7960. this.setDepthWrite(true);
  7961. // Fullscreen
  7962. this._onFullscreenChange = function () {
  7963. if (document.fullscreen !== undefined) {
  7964. _this.isFullscreen = document.fullscreen;
  7965. }
  7966. else if (document.mozFullScreen !== undefined) {
  7967. _this.isFullscreen = document.mozFullScreen;
  7968. }
  7969. else if (document.webkitIsFullScreen !== undefined) {
  7970. _this.isFullscreen = document.webkitIsFullScreen;
  7971. }
  7972. else if (document.msIsFullScreen !== undefined) {
  7973. _this.isFullscreen = document.msIsFullScreen;
  7974. }
  7975. // Pointer lock
  7976. if (_this.isFullscreen && _this._pointerLockRequested) {
  7977. canvas.requestPointerLock = canvas.requestPointerLock ||
  7978. canvas.msRequestPointerLock ||
  7979. canvas.mozRequestPointerLock ||
  7980. canvas.webkitRequestPointerLock;
  7981. if (canvas.requestPointerLock) {
  7982. canvas.requestPointerLock();
  7983. }
  7984. }
  7985. };
  7986. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7987. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7988. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7989. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7990. // Pointer lock
  7991. this._onPointerLockChange = function () {
  7992. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7993. document.webkitPointerLockElement === canvas ||
  7994. document.msPointerLockElement === canvas ||
  7995. document.pointerLockElement === canvas);
  7996. };
  7997. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7998. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7999. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8000. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8001. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  8002. Engine.audioEngine = new BABYLON.AudioEngine();
  8003. }
  8004. //default loading screen
  8005. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  8006. //Load WebVR Devices
  8007. if (options.autoEnableWebVR) {
  8008. this.initWebVR();
  8009. }
  8010. //Detect if we are running on a faulty buggy OS.
  8011. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  8012. //ua sniffing is the tool of the devil.
  8013. this._badOS = regexp.test(navigator.userAgent);
  8014. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8015. }
  8016. Object.defineProperty(Engine, "LastCreatedEngine", {
  8017. get: function () {
  8018. if (Engine.Instances.length === 0) {
  8019. return null;
  8020. }
  8021. return Engine.Instances[Engine.Instances.length - 1];
  8022. },
  8023. enumerable: true,
  8024. configurable: true
  8025. });
  8026. Object.defineProperty(Engine, "LastCreatedScene", {
  8027. get: function () {
  8028. var lastCreatedEngine = Engine.LastCreatedEngine;
  8029. if (!lastCreatedEngine) {
  8030. return null;
  8031. }
  8032. if (lastCreatedEngine.scenes.length === 0) {
  8033. return null;
  8034. }
  8035. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8036. },
  8037. enumerable: true,
  8038. configurable: true
  8039. });
  8040. Object.defineProperty(Engine, "NEVER", {
  8041. get: function () {
  8042. return Engine._NEVER;
  8043. },
  8044. enumerable: true,
  8045. configurable: true
  8046. });
  8047. Object.defineProperty(Engine, "ALWAYS", {
  8048. get: function () {
  8049. return Engine._ALWAYS;
  8050. },
  8051. enumerable: true,
  8052. configurable: true
  8053. });
  8054. Object.defineProperty(Engine, "LESS", {
  8055. get: function () {
  8056. return Engine._LESS;
  8057. },
  8058. enumerable: true,
  8059. configurable: true
  8060. });
  8061. Object.defineProperty(Engine, "EQUAL", {
  8062. get: function () {
  8063. return Engine._EQUAL;
  8064. },
  8065. enumerable: true,
  8066. configurable: true
  8067. });
  8068. Object.defineProperty(Engine, "LEQUAL", {
  8069. get: function () {
  8070. return Engine._LEQUAL;
  8071. },
  8072. enumerable: true,
  8073. configurable: true
  8074. });
  8075. Object.defineProperty(Engine, "GREATER", {
  8076. get: function () {
  8077. return Engine._GREATER;
  8078. },
  8079. enumerable: true,
  8080. configurable: true
  8081. });
  8082. Object.defineProperty(Engine, "GEQUAL", {
  8083. get: function () {
  8084. return Engine._GEQUAL;
  8085. },
  8086. enumerable: true,
  8087. configurable: true
  8088. });
  8089. Object.defineProperty(Engine, "NOTEQUAL", {
  8090. get: function () {
  8091. return Engine._NOTEQUAL;
  8092. },
  8093. enumerable: true,
  8094. configurable: true
  8095. });
  8096. Object.defineProperty(Engine, "KEEP", {
  8097. get: function () {
  8098. return Engine._KEEP;
  8099. },
  8100. enumerable: true,
  8101. configurable: true
  8102. });
  8103. Object.defineProperty(Engine, "REPLACE", {
  8104. get: function () {
  8105. return Engine._REPLACE;
  8106. },
  8107. enumerable: true,
  8108. configurable: true
  8109. });
  8110. Object.defineProperty(Engine, "INCR", {
  8111. get: function () {
  8112. return Engine._INCR;
  8113. },
  8114. enumerable: true,
  8115. configurable: true
  8116. });
  8117. Object.defineProperty(Engine, "DECR", {
  8118. get: function () {
  8119. return Engine._DECR;
  8120. },
  8121. enumerable: true,
  8122. configurable: true
  8123. });
  8124. Object.defineProperty(Engine, "INVERT", {
  8125. get: function () {
  8126. return Engine._INVERT;
  8127. },
  8128. enumerable: true,
  8129. configurable: true
  8130. });
  8131. Object.defineProperty(Engine, "INCR_WRAP", {
  8132. get: function () {
  8133. return Engine._INCR_WRAP;
  8134. },
  8135. enumerable: true,
  8136. configurable: true
  8137. });
  8138. Object.defineProperty(Engine, "DECR_WRAP", {
  8139. get: function () {
  8140. return Engine._DECR_WRAP;
  8141. },
  8142. enumerable: true,
  8143. configurable: true
  8144. });
  8145. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8146. get: function () {
  8147. return Engine._ALPHA_DISABLE;
  8148. },
  8149. enumerable: true,
  8150. configurable: true
  8151. });
  8152. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8153. get: function () {
  8154. return Engine._ALPHA_ONEONE;
  8155. },
  8156. enumerable: true,
  8157. configurable: true
  8158. });
  8159. Object.defineProperty(Engine, "ALPHA_ADD", {
  8160. get: function () {
  8161. return Engine._ALPHA_ADD;
  8162. },
  8163. enumerable: true,
  8164. configurable: true
  8165. });
  8166. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8167. get: function () {
  8168. return Engine._ALPHA_COMBINE;
  8169. },
  8170. enumerable: true,
  8171. configurable: true
  8172. });
  8173. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8174. get: function () {
  8175. return Engine._ALPHA_SUBTRACT;
  8176. },
  8177. enumerable: true,
  8178. configurable: true
  8179. });
  8180. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8181. get: function () {
  8182. return Engine._ALPHA_MULTIPLY;
  8183. },
  8184. enumerable: true,
  8185. configurable: true
  8186. });
  8187. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8188. get: function () {
  8189. return Engine._ALPHA_MAXIMIZED;
  8190. },
  8191. enumerable: true,
  8192. configurable: true
  8193. });
  8194. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8195. get: function () {
  8196. return Engine._ALPHA_PREMULTIPLIED;
  8197. },
  8198. enumerable: true,
  8199. configurable: true
  8200. });
  8201. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8202. get: function () {
  8203. return Engine._DELAYLOADSTATE_NONE;
  8204. },
  8205. enumerable: true,
  8206. configurable: true
  8207. });
  8208. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8209. get: function () {
  8210. return Engine._DELAYLOADSTATE_LOADED;
  8211. },
  8212. enumerable: true,
  8213. configurable: true
  8214. });
  8215. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8216. get: function () {
  8217. return Engine._DELAYLOADSTATE_LOADING;
  8218. },
  8219. enumerable: true,
  8220. configurable: true
  8221. });
  8222. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8223. get: function () {
  8224. return Engine._DELAYLOADSTATE_NOTLOADED;
  8225. },
  8226. enumerable: true,
  8227. configurable: true
  8228. });
  8229. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8230. get: function () {
  8231. return Engine._TEXTUREFORMAT_ALPHA;
  8232. },
  8233. enumerable: true,
  8234. configurable: true
  8235. });
  8236. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8237. get: function () {
  8238. return Engine._TEXTUREFORMAT_LUMINANCE;
  8239. },
  8240. enumerable: true,
  8241. configurable: true
  8242. });
  8243. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8244. get: function () {
  8245. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8246. },
  8247. enumerable: true,
  8248. configurable: true
  8249. });
  8250. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8251. get: function () {
  8252. return Engine._TEXTUREFORMAT_RGB;
  8253. },
  8254. enumerable: true,
  8255. configurable: true
  8256. });
  8257. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8258. get: function () {
  8259. return Engine._TEXTUREFORMAT_RGBA;
  8260. },
  8261. enumerable: true,
  8262. configurable: true
  8263. });
  8264. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8265. get: function () {
  8266. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8267. },
  8268. enumerable: true,
  8269. configurable: true
  8270. });
  8271. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8272. get: function () {
  8273. return Engine._TEXTURETYPE_FLOAT;
  8274. },
  8275. enumerable: true,
  8276. configurable: true
  8277. });
  8278. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8279. get: function () {
  8280. return Engine._TEXTURETYPE_HALF_FLOAT;
  8281. },
  8282. enumerable: true,
  8283. configurable: true
  8284. });
  8285. Object.defineProperty(Engine, "Version", {
  8286. get: function () {
  8287. return "2.6-alpha";
  8288. },
  8289. enumerable: true,
  8290. configurable: true
  8291. });
  8292. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8293. get: function () {
  8294. return this._texturesSupported;
  8295. },
  8296. enumerable: true,
  8297. configurable: true
  8298. });
  8299. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8300. get: function () {
  8301. return this._textureFormatInUse;
  8302. },
  8303. enumerable: true,
  8304. configurable: true
  8305. });
  8306. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8307. get: function () {
  8308. return this._webGLVersion;
  8309. },
  8310. enumerable: true,
  8311. configurable: true
  8312. });
  8313. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8314. /**
  8315. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8316. */
  8317. get: function () {
  8318. return this._isStencilEnable;
  8319. },
  8320. enumerable: true,
  8321. configurable: true
  8322. });
  8323. Engine.prototype._prepareWorkingCanvas = function () {
  8324. if (this._workingCanvas) {
  8325. return;
  8326. }
  8327. this._workingCanvas = document.createElement("canvas");
  8328. this._workingContext = this._workingCanvas.getContext("2d");
  8329. };
  8330. Engine.prototype.resetTextureCache = function () {
  8331. for (var index = 0; index < this._maxTextureChannels; index++) {
  8332. this._activeTexturesCache[index] = null;
  8333. }
  8334. };
  8335. Engine.prototype.getGlInfo = function () {
  8336. return {
  8337. vendor: this._glVendor,
  8338. renderer: this._glRenderer,
  8339. version: this._glVersion
  8340. };
  8341. };
  8342. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8343. if (useScreen === void 0) { useScreen = false; }
  8344. var viewport = camera.viewport;
  8345. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8346. };
  8347. Engine.prototype.getRenderWidth = function (useScreen) {
  8348. if (useScreen === void 0) { useScreen = false; }
  8349. if (!useScreen && this._currentRenderTarget) {
  8350. return this._currentRenderTarget._width;
  8351. }
  8352. return this._renderingCanvas.width;
  8353. };
  8354. Engine.prototype.getRenderHeight = function (useScreen) {
  8355. if (useScreen === void 0) { useScreen = false; }
  8356. if (!useScreen && this._currentRenderTarget) {
  8357. return this._currentRenderTarget._height;
  8358. }
  8359. return this._renderingCanvas.height;
  8360. };
  8361. Engine.prototype.getRenderingCanvas = function () {
  8362. return this._renderingCanvas;
  8363. };
  8364. Engine.prototype.getRenderingCanvasClientRect = function () {
  8365. return this._renderingCanvas.getBoundingClientRect();
  8366. };
  8367. Engine.prototype.setHardwareScalingLevel = function (level) {
  8368. this._hardwareScalingLevel = level;
  8369. this.resize();
  8370. };
  8371. Engine.prototype.getHardwareScalingLevel = function () {
  8372. return this._hardwareScalingLevel;
  8373. };
  8374. Engine.prototype.getLoadedTexturesCache = function () {
  8375. return this._loadedTexturesCache;
  8376. };
  8377. Engine.prototype.getCaps = function () {
  8378. return this._caps;
  8379. };
  8380. Object.defineProperty(Engine.prototype, "drawCalls", {
  8381. get: function () {
  8382. return this._drawCalls.current;
  8383. },
  8384. enumerable: true,
  8385. configurable: true
  8386. });
  8387. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8388. get: function () {
  8389. return this._drawCalls;
  8390. },
  8391. enumerable: true,
  8392. configurable: true
  8393. });
  8394. Engine.prototype.getDepthFunction = function () {
  8395. return this._depthCullingState.depthFunc;
  8396. };
  8397. Engine.prototype.setDepthFunction = function (depthFunc) {
  8398. this._depthCullingState.depthFunc = depthFunc;
  8399. };
  8400. Engine.prototype.setDepthFunctionToGreater = function () {
  8401. this._depthCullingState.depthFunc = this._gl.GREATER;
  8402. };
  8403. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8404. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8405. };
  8406. Engine.prototype.setDepthFunctionToLess = function () {
  8407. this._depthCullingState.depthFunc = this._gl.LESS;
  8408. };
  8409. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8410. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8411. };
  8412. Engine.prototype.getStencilBuffer = function () {
  8413. return this._stencilState.stencilTest;
  8414. };
  8415. Engine.prototype.setStencilBuffer = function (enable) {
  8416. this._stencilState.stencilTest = enable;
  8417. };
  8418. Engine.prototype.getStencilMask = function () {
  8419. return this._stencilState.stencilMask;
  8420. };
  8421. Engine.prototype.setStencilMask = function (mask) {
  8422. this._stencilState.stencilMask = mask;
  8423. };
  8424. Engine.prototype.getStencilFunction = function () {
  8425. return this._stencilState.stencilFunc;
  8426. };
  8427. Engine.prototype.getStencilFunctionReference = function () {
  8428. return this._stencilState.stencilFuncRef;
  8429. };
  8430. Engine.prototype.getStencilFunctionMask = function () {
  8431. return this._stencilState.stencilFuncMask;
  8432. };
  8433. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8434. this._stencilState.stencilFunc = stencilFunc;
  8435. };
  8436. Engine.prototype.setStencilFunctionReference = function (reference) {
  8437. this._stencilState.stencilFuncRef = reference;
  8438. };
  8439. Engine.prototype.setStencilFunctionMask = function (mask) {
  8440. this._stencilState.stencilFuncMask = mask;
  8441. };
  8442. Engine.prototype.getStencilOperationFail = function () {
  8443. return this._stencilState.stencilOpStencilFail;
  8444. };
  8445. Engine.prototype.getStencilOperationDepthFail = function () {
  8446. return this._stencilState.stencilOpDepthFail;
  8447. };
  8448. Engine.prototype.getStencilOperationPass = function () {
  8449. return this._stencilState.stencilOpStencilDepthPass;
  8450. };
  8451. Engine.prototype.setStencilOperationFail = function (operation) {
  8452. this._stencilState.stencilOpStencilFail = operation;
  8453. };
  8454. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8455. this._stencilState.stencilOpDepthFail = operation;
  8456. };
  8457. Engine.prototype.setStencilOperationPass = function (operation) {
  8458. this._stencilState.stencilOpStencilDepthPass = operation;
  8459. };
  8460. /**
  8461. * stop executing a render loop function and remove it from the execution array
  8462. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8463. */
  8464. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8465. if (!renderFunction) {
  8466. this._activeRenderLoops = [];
  8467. return;
  8468. }
  8469. var index = this._activeRenderLoops.indexOf(renderFunction);
  8470. if (index >= 0) {
  8471. this._activeRenderLoops.splice(index, 1);
  8472. }
  8473. };
  8474. Engine.prototype._renderLoop = function () {
  8475. var shouldRender = true;
  8476. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8477. shouldRender = false;
  8478. }
  8479. if (shouldRender) {
  8480. // Start new frame
  8481. this.beginFrame();
  8482. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8483. var renderFunction = this._activeRenderLoops[index];
  8484. renderFunction();
  8485. }
  8486. // Present
  8487. this.endFrame();
  8488. }
  8489. if (this._activeRenderLoops.length > 0) {
  8490. // Register new frame
  8491. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8492. }
  8493. else {
  8494. this._renderingQueueLaunched = false;
  8495. }
  8496. };
  8497. /**
  8498. * Register and execute a render loop. The engine can have more than one render function.
  8499. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8500. * @example
  8501. * engine.runRenderLoop(function () {
  8502. * scene.render()
  8503. * })
  8504. */
  8505. Engine.prototype.runRenderLoop = function (renderFunction) {
  8506. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8507. return;
  8508. }
  8509. this._activeRenderLoops.push(renderFunction);
  8510. if (!this._renderingQueueLaunched) {
  8511. this._renderingQueueLaunched = true;
  8512. this._bindedRenderFunction = this._renderLoop.bind(this);
  8513. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8514. }
  8515. };
  8516. /**
  8517. * Toggle full screen mode.
  8518. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8519. * @param {any} options - an options object to be sent to the requestFullscreen function
  8520. */
  8521. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8522. if (this.isFullscreen) {
  8523. BABYLON.Tools.ExitFullscreen();
  8524. }
  8525. else {
  8526. this._pointerLockRequested = requestPointerLock;
  8527. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8528. }
  8529. };
  8530. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8531. if (stencil === void 0) { stencil = false; }
  8532. this.applyStates();
  8533. var mode = 0;
  8534. if (backBuffer && color) {
  8535. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8536. mode |= this._gl.COLOR_BUFFER_BIT;
  8537. }
  8538. if (depth) {
  8539. this._gl.clearDepth(1.0);
  8540. mode |= this._gl.DEPTH_BUFFER_BIT;
  8541. }
  8542. if (stencil) {
  8543. this._gl.clearStencil(0);
  8544. mode |= this._gl.STENCIL_BUFFER_BIT;
  8545. }
  8546. this._gl.clear(mode);
  8547. };
  8548. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8549. var gl = this._gl;
  8550. // Save state
  8551. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8552. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8553. // Change state
  8554. gl.enable(gl.SCISSOR_TEST);
  8555. gl.scissor(x, y, width, height);
  8556. // Clear
  8557. this.clear(clearColor, true, true, true);
  8558. // Restore state
  8559. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8560. if (curScissor === true) {
  8561. gl.enable(gl.SCISSOR_TEST);
  8562. }
  8563. else {
  8564. gl.disable(gl.SCISSOR_TEST);
  8565. }
  8566. };
  8567. /**
  8568. * Set the WebGL's viewport
  8569. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8570. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8571. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8572. */
  8573. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8574. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8575. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8576. var x = viewport.x || 0;
  8577. var y = viewport.y || 0;
  8578. this._cachedViewport = viewport;
  8579. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8580. };
  8581. /**
  8582. * Directly set the WebGL Viewport
  8583. * The x, y, width & height are directly passed to the WebGL call
  8584. * @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.
  8585. */
  8586. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8587. var currentViewport = this._cachedViewport;
  8588. this._cachedViewport = null;
  8589. this._gl.viewport(x, y, width, height);
  8590. return currentViewport;
  8591. };
  8592. Engine.prototype.beginFrame = function () {
  8593. this._measureFps();
  8594. };
  8595. Engine.prototype.endFrame = function () {
  8596. //force a flush in case we are using a bad OS.
  8597. if (this._badOS) {
  8598. this.flushFramebuffer();
  8599. }
  8600. //submit frame to the vr device, if enabled
  8601. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8602. this._vrDisplayEnabled.submitFrame();
  8603. }
  8604. };
  8605. /**
  8606. * resize the view according to the canvas' size.
  8607. * @example
  8608. * window.addEventListener("resize", function () {
  8609. * engine.resize();
  8610. * });
  8611. */
  8612. Engine.prototype.resize = function () {
  8613. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8614. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8615. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8616. };
  8617. /**
  8618. * force a specific size of the canvas
  8619. * @param {number} width - the new canvas' width
  8620. * @param {number} height - the new canvas' height
  8621. */
  8622. Engine.prototype.setSize = function (width, height) {
  8623. this._renderingCanvas.width = width;
  8624. this._renderingCanvas.height = height;
  8625. for (var index = 0; index < this.scenes.length; index++) {
  8626. var scene = this.scenes[index];
  8627. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8628. var cam = scene.cameras[camIndex];
  8629. cam._currentRenderId = 0;
  8630. }
  8631. }
  8632. };
  8633. //WebVR functions
  8634. Engine.prototype.initWebVR = function () {
  8635. if (!this.vrDisplaysPromise) {
  8636. this._getVRDisplays();
  8637. }
  8638. };
  8639. Engine.prototype.enableVR = function (vrDevice) {
  8640. this._vrDisplayEnabled = vrDevice;
  8641. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8642. };
  8643. Engine.prototype.disableVR = function () {
  8644. if (this._vrDisplayEnabled) {
  8645. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8646. }
  8647. };
  8648. Engine.prototype._getVRDisplays = function () {
  8649. var _this = this;
  8650. var getWebVRDevices = function (devices) {
  8651. var size = devices.length;
  8652. var i = 0;
  8653. _this._vrDisplays = devices.filter(function (device) {
  8654. return devices[i] instanceof VRDisplay;
  8655. });
  8656. return _this._vrDisplays;
  8657. };
  8658. //using a key due to typescript
  8659. if (navigator.getVRDisplays) {
  8660. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8661. }
  8662. };
  8663. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8664. this._currentRenderTarget = texture;
  8665. this.bindUnboundFramebuffer(texture._framebuffer);
  8666. var gl = this._gl;
  8667. if (texture.isCube) {
  8668. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8669. }
  8670. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8671. this.wipeCaches();
  8672. };
  8673. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8674. if (this._currentFramebuffer !== framebuffer) {
  8675. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8676. this._currentFramebuffer = framebuffer;
  8677. }
  8678. };
  8679. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  8680. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8681. this._currentRenderTarget = null;
  8682. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8683. var gl = this._gl;
  8684. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8685. gl.generateMipmap(gl.TEXTURE_2D);
  8686. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8687. }
  8688. this.bindUnboundFramebuffer(null);
  8689. };
  8690. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8691. if (texture.generateMipMaps) {
  8692. var gl = this._gl;
  8693. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8694. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8695. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8696. }
  8697. };
  8698. Engine.prototype.flushFramebuffer = function () {
  8699. this._gl.flush();
  8700. };
  8701. Engine.prototype.restoreDefaultFramebuffer = function () {
  8702. this._currentRenderTarget = null;
  8703. this.bindUnboundFramebuffer(null);
  8704. this.setViewport(this._cachedViewport);
  8705. this.wipeCaches();
  8706. };
  8707. // VBOs
  8708. Engine.prototype._resetVertexBufferBinding = function () {
  8709. this.bindArrayBuffer(null);
  8710. this._cachedVertexBuffers = null;
  8711. };
  8712. Engine.prototype.createVertexBuffer = function (vertices) {
  8713. var vbo = this._gl.createBuffer();
  8714. this.bindArrayBuffer(vbo);
  8715. if (vertices instanceof Float32Array) {
  8716. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8717. }
  8718. else {
  8719. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8720. }
  8721. this._resetVertexBufferBinding();
  8722. vbo.references = 1;
  8723. return vbo;
  8724. };
  8725. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8726. var vbo = this._gl.createBuffer();
  8727. this.bindArrayBuffer(vbo);
  8728. if (vertices instanceof Float32Array) {
  8729. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8730. }
  8731. else {
  8732. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8733. }
  8734. this._resetVertexBufferBinding();
  8735. vbo.references = 1;
  8736. return vbo;
  8737. };
  8738. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8739. this.bindArrayBuffer(vertexBuffer);
  8740. if (offset === undefined) {
  8741. offset = 0;
  8742. }
  8743. if (count === undefined) {
  8744. if (vertices instanceof Float32Array) {
  8745. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8746. }
  8747. else {
  8748. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8749. }
  8750. }
  8751. else {
  8752. if (vertices instanceof Float32Array) {
  8753. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8754. }
  8755. else {
  8756. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8757. }
  8758. }
  8759. this._resetVertexBufferBinding();
  8760. };
  8761. Engine.prototype._resetIndexBufferBinding = function () {
  8762. this.bindIndexBuffer(null);
  8763. this._cachedIndexBuffer = null;
  8764. };
  8765. Engine.prototype.createIndexBuffer = function (indices) {
  8766. var vbo = this._gl.createBuffer();
  8767. this.bindIndexBuffer(vbo);
  8768. // Check for 32 bits indices
  8769. var arrayBuffer;
  8770. var need32Bits = false;
  8771. if (indices instanceof Uint16Array) {
  8772. arrayBuffer = indices;
  8773. }
  8774. else {
  8775. //check 32 bit support
  8776. if (this._caps.uintIndices) {
  8777. if (indices instanceof Uint32Array) {
  8778. arrayBuffer = indices;
  8779. need32Bits = true;
  8780. }
  8781. else {
  8782. //number[] or Int32Array, check if 32 bit is necessary
  8783. for (var index = 0; index < indices.length; index++) {
  8784. if (indices[index] > 65535) {
  8785. need32Bits = true;
  8786. break;
  8787. }
  8788. }
  8789. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8790. }
  8791. }
  8792. else {
  8793. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8794. arrayBuffer = new Uint16Array(indices);
  8795. }
  8796. }
  8797. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8798. this._resetIndexBufferBinding();
  8799. vbo.references = 1;
  8800. vbo.is32Bits = need32Bits;
  8801. return vbo;
  8802. };
  8803. Engine.prototype.bindArrayBuffer = function (buffer) {
  8804. if (!this._vaoRecordInProgress) {
  8805. this._unBindVertexArrayObject();
  8806. }
  8807. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8808. };
  8809. Engine.prototype.bindIndexBuffer = function (buffer) {
  8810. if (!this._vaoRecordInProgress) {
  8811. this._unBindVertexArrayObject();
  8812. }
  8813. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8814. };
  8815. Engine.prototype.bindBuffer = function (buffer, target) {
  8816. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8817. this._gl.bindBuffer(target, buffer);
  8818. this._currentBoundBuffer[target] = buffer;
  8819. }
  8820. };
  8821. Engine.prototype.updateArrayBuffer = function (data) {
  8822. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8823. };
  8824. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8825. var pointer = this._currentBufferPointers[indx];
  8826. var changed = false;
  8827. if (!pointer) {
  8828. changed = true;
  8829. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8830. }
  8831. else {
  8832. if (pointer.buffer !== buffer) {
  8833. pointer.buffer = buffer;
  8834. changed = true;
  8835. }
  8836. if (pointer.size !== size) {
  8837. pointer.size = size;
  8838. changed = true;
  8839. }
  8840. if (pointer.type !== type) {
  8841. pointer.type = type;
  8842. changed = true;
  8843. }
  8844. if (pointer.normalized !== normalized) {
  8845. pointer.normalized = normalized;
  8846. changed = true;
  8847. }
  8848. if (pointer.stride !== stride) {
  8849. pointer.stride = stride;
  8850. changed = true;
  8851. }
  8852. if (pointer.offset !== offset) {
  8853. pointer.offset = offset;
  8854. changed = true;
  8855. }
  8856. }
  8857. if (changed || this._vaoRecordInProgress) {
  8858. this.bindArrayBuffer(buffer);
  8859. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8860. }
  8861. };
  8862. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8863. if (indexBuffer == null) {
  8864. return;
  8865. }
  8866. if (this._cachedIndexBuffer !== indexBuffer) {
  8867. this._cachedIndexBuffer = indexBuffer;
  8868. this.bindIndexBuffer(indexBuffer);
  8869. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8870. }
  8871. };
  8872. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8873. var attributes = effect.getAttributesNames();
  8874. if (!this._vaoRecordInProgress) {
  8875. this._unBindVertexArrayObject();
  8876. }
  8877. this.unbindAllAttributes();
  8878. for (var index = 0; index < attributes.length; index++) {
  8879. var order = effect.getAttributeLocation(index);
  8880. if (order >= 0) {
  8881. var vertexBuffer = vertexBuffers[attributes[index]];
  8882. if (!vertexBuffer) {
  8883. continue;
  8884. }
  8885. this._gl.enableVertexAttribArray(order);
  8886. if (!this._vaoRecordInProgress) {
  8887. this._vertexAttribArraysEnabled[order] = true;
  8888. }
  8889. var buffer = vertexBuffer.getBuffer();
  8890. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8891. if (vertexBuffer.getIsInstanced()) {
  8892. this._gl.vertexAttribDivisor(order, 1);
  8893. if (!this._vaoRecordInProgress) {
  8894. this._currentInstanceLocations.push(order);
  8895. this._currentInstanceBuffers.push(buffer);
  8896. }
  8897. }
  8898. }
  8899. }
  8900. };
  8901. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8902. var vao = this._gl.createVertexArray();
  8903. this._vaoRecordInProgress = true;
  8904. this._gl.bindVertexArray(vao);
  8905. this._mustWipeVertexAttributes = true;
  8906. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8907. this.bindIndexBuffer(indexBuffer);
  8908. this._vaoRecordInProgress = false;
  8909. this._gl.bindVertexArray(null);
  8910. return vao;
  8911. };
  8912. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8913. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8914. this._cachedVertexArrayObject = vertexArrayObject;
  8915. this._gl.bindVertexArray(vertexArrayObject);
  8916. this._cachedVertexBuffers = null;
  8917. this._cachedIndexBuffer = null;
  8918. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8919. this._mustWipeVertexAttributes = true;
  8920. }
  8921. };
  8922. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8923. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8924. this._cachedVertexBuffers = vertexBuffer;
  8925. this._cachedEffectForVertexBuffers = effect;
  8926. var attributesCount = effect.getAttributesCount();
  8927. this._unBindVertexArrayObject();
  8928. this.unbindAllAttributes();
  8929. var offset = 0;
  8930. for (var index = 0; index < attributesCount; index++) {
  8931. if (index < vertexDeclaration.length) {
  8932. var order = effect.getAttributeLocation(index);
  8933. if (order >= 0) {
  8934. this._gl.enableVertexAttribArray(order);
  8935. this._vertexAttribArraysEnabled[order] = true;
  8936. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8937. }
  8938. offset += vertexDeclaration[index] * 4;
  8939. }
  8940. }
  8941. }
  8942. this._bindIndexBufferWithCache(indexBuffer);
  8943. };
  8944. Engine.prototype._unBindVertexArrayObject = function () {
  8945. if (!this._cachedVertexArrayObject) {
  8946. return;
  8947. }
  8948. this._cachedVertexArrayObject = null;
  8949. this._gl.bindVertexArray(null);
  8950. };
  8951. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8952. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8953. this._cachedVertexBuffers = vertexBuffers;
  8954. this._cachedEffectForVertexBuffers = effect;
  8955. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8956. }
  8957. this._bindIndexBufferWithCache(indexBuffer);
  8958. };
  8959. Engine.prototype.unbindInstanceAttributes = function () {
  8960. var boundBuffer;
  8961. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8962. var instancesBuffer = this._currentInstanceBuffers[i];
  8963. if (boundBuffer != instancesBuffer) {
  8964. boundBuffer = instancesBuffer;
  8965. this.bindArrayBuffer(instancesBuffer);
  8966. }
  8967. var offsetLocation = this._currentInstanceLocations[i];
  8968. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8969. }
  8970. this._currentInstanceBuffers.length = 0;
  8971. this._currentInstanceLocations.length = 0;
  8972. };
  8973. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8974. this._gl.deleteVertexArray(vao);
  8975. };
  8976. Engine.prototype._releaseBuffer = function (buffer) {
  8977. buffer.references--;
  8978. if (buffer.references === 0) {
  8979. this._gl.deleteBuffer(buffer);
  8980. return true;
  8981. }
  8982. return false;
  8983. };
  8984. Engine.prototype.createInstancesBuffer = function (capacity) {
  8985. var buffer = this._gl.createBuffer();
  8986. buffer.capacity = capacity;
  8987. this.bindArrayBuffer(buffer);
  8988. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8989. return buffer;
  8990. };
  8991. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8992. this._gl.deleteBuffer(buffer);
  8993. };
  8994. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8995. this.bindArrayBuffer(instancesBuffer);
  8996. if (data) {
  8997. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8998. }
  8999. if (offsetLocations[0].index !== undefined) {
  9000. var stride = 0;
  9001. for (var i = 0; i < offsetLocations.length; i++) {
  9002. var ai = offsetLocations[i];
  9003. stride += ai.attributeSize * 4;
  9004. }
  9005. for (var i = 0; i < offsetLocations.length; i++) {
  9006. var ai = offsetLocations[i];
  9007. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9008. this._gl.enableVertexAttribArray(ai.index);
  9009. this._vertexAttribArraysEnabled[ai.index] = true;
  9010. }
  9011. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9012. this._gl.vertexAttribDivisor(ai.index, 1);
  9013. this._currentInstanceLocations.push(ai.index);
  9014. this._currentInstanceBuffers.push(instancesBuffer);
  9015. }
  9016. }
  9017. else {
  9018. for (var index = 0; index < 4; index++) {
  9019. var offsetLocation = offsetLocations[index];
  9020. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9021. this._gl.enableVertexAttribArray(offsetLocation);
  9022. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9023. }
  9024. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9025. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9026. this._currentInstanceLocations.push(offsetLocation);
  9027. this._currentInstanceBuffers.push(instancesBuffer);
  9028. }
  9029. }
  9030. };
  9031. Engine.prototype.applyStates = function () {
  9032. this._depthCullingState.apply(this._gl);
  9033. this._stencilState.apply(this._gl);
  9034. this._alphaState.apply(this._gl);
  9035. };
  9036. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9037. // Apply states
  9038. this.applyStates();
  9039. this._drawCalls.addCount(1, false);
  9040. // Render
  9041. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9042. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9043. if (instancesCount) {
  9044. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9045. return;
  9046. }
  9047. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9048. };
  9049. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9050. // Apply states
  9051. this.applyStates();
  9052. this._drawCalls.addCount(1, false);
  9053. if (instancesCount) {
  9054. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9055. return;
  9056. }
  9057. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9058. };
  9059. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9060. // Apply states
  9061. this.applyStates();
  9062. this._drawCalls.addCount(1, false);
  9063. if (instancesCount) {
  9064. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9065. return;
  9066. }
  9067. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9068. };
  9069. // Shaders
  9070. Engine.prototype._releaseEffect = function (effect) {
  9071. if (this._compiledEffects[effect._key]) {
  9072. delete this._compiledEffects[effect._key];
  9073. if (effect.getProgram()) {
  9074. this._gl.deleteProgram(effect.getProgram());
  9075. }
  9076. }
  9077. };
  9078. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9079. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9080. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9081. var name = vertex + "+" + fragment + "@" + defines;
  9082. if (this._compiledEffects[name]) {
  9083. return this._compiledEffects[name];
  9084. }
  9085. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9086. effect._key = name;
  9087. this._compiledEffects[name] = effect;
  9088. return effect;
  9089. };
  9090. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9091. if (uniformsNames === void 0) { uniformsNames = []; }
  9092. if (samplers === void 0) { samplers = []; }
  9093. if (defines === void 0) { defines = ""; }
  9094. return this.createEffect({
  9095. vertex: "particles",
  9096. fragmentElement: fragmentName
  9097. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9098. };
  9099. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9100. context = context || this._gl;
  9101. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9102. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9103. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9104. var shaderProgram = context.createProgram();
  9105. context.attachShader(shaderProgram, vertexShader);
  9106. context.attachShader(shaderProgram, fragmentShader);
  9107. context.linkProgram(shaderProgram);
  9108. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9109. if (!linked) {
  9110. var error = context.getProgramInfoLog(shaderProgram);
  9111. if (error) {
  9112. throw new Error(error);
  9113. }
  9114. }
  9115. context.deleteShader(vertexShader);
  9116. context.deleteShader(fragmentShader);
  9117. return shaderProgram;
  9118. };
  9119. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9120. var results = [];
  9121. for (var index = 0; index < uniformsNames.length; index++) {
  9122. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9123. }
  9124. return results;
  9125. };
  9126. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9127. var results = [];
  9128. for (var index = 0; index < attributesNames.length; index++) {
  9129. try {
  9130. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9131. }
  9132. catch (e) {
  9133. results.push(-1);
  9134. }
  9135. }
  9136. return results;
  9137. };
  9138. Engine.prototype.enableEffect = function (effect) {
  9139. // Use program
  9140. this.setProgram(effect.getProgram());
  9141. this._currentEffect = effect;
  9142. if (effect.onBind) {
  9143. effect.onBind(effect);
  9144. }
  9145. };
  9146. Engine.prototype.setIntArray = function (uniform, array) {
  9147. if (!uniform)
  9148. return;
  9149. this._gl.uniform1iv(uniform, array);
  9150. };
  9151. Engine.prototype.setIntArray2 = function (uniform, array) {
  9152. if (!uniform || array.length % 2 !== 0)
  9153. return;
  9154. this._gl.uniform2iv(uniform, array);
  9155. };
  9156. Engine.prototype.setIntArray3 = function (uniform, array) {
  9157. if (!uniform || array.length % 3 !== 0)
  9158. return;
  9159. this._gl.uniform3iv(uniform, array);
  9160. };
  9161. Engine.prototype.setIntArray4 = function (uniform, array) {
  9162. if (!uniform || array.length % 4 !== 0)
  9163. return;
  9164. this._gl.uniform4iv(uniform, array);
  9165. };
  9166. Engine.prototype.setFloatArray = function (uniform, array) {
  9167. if (!uniform)
  9168. return;
  9169. this._gl.uniform1fv(uniform, array);
  9170. };
  9171. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9172. if (!uniform || array.length % 2 !== 0)
  9173. return;
  9174. this._gl.uniform2fv(uniform, array);
  9175. };
  9176. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9177. if (!uniform || array.length % 3 !== 0)
  9178. return;
  9179. this._gl.uniform3fv(uniform, array);
  9180. };
  9181. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9182. if (!uniform || array.length % 4 !== 0)
  9183. return;
  9184. this._gl.uniform4fv(uniform, array);
  9185. };
  9186. Engine.prototype.setArray = function (uniform, array) {
  9187. if (!uniform)
  9188. return;
  9189. this._gl.uniform1fv(uniform, array);
  9190. };
  9191. Engine.prototype.setArray2 = function (uniform, array) {
  9192. if (!uniform || array.length % 2 !== 0)
  9193. return;
  9194. this._gl.uniform2fv(uniform, array);
  9195. };
  9196. Engine.prototype.setArray3 = function (uniform, array) {
  9197. if (!uniform || array.length % 3 !== 0)
  9198. return;
  9199. this._gl.uniform3fv(uniform, array);
  9200. };
  9201. Engine.prototype.setArray4 = function (uniform, array) {
  9202. if (!uniform || array.length % 4 !== 0)
  9203. return;
  9204. this._gl.uniform4fv(uniform, array);
  9205. };
  9206. Engine.prototype.setMatrices = function (uniform, matrices) {
  9207. if (!uniform)
  9208. return;
  9209. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9210. };
  9211. Engine.prototype.setMatrix = function (uniform, matrix) {
  9212. if (!uniform)
  9213. return;
  9214. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9215. };
  9216. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9217. if (!uniform)
  9218. return;
  9219. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9220. };
  9221. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9222. if (!uniform)
  9223. return;
  9224. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9225. };
  9226. Engine.prototype.setFloat = function (uniform, value) {
  9227. if (!uniform)
  9228. return;
  9229. this._gl.uniform1f(uniform, value);
  9230. };
  9231. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9232. if (!uniform)
  9233. return;
  9234. this._gl.uniform2f(uniform, x, y);
  9235. };
  9236. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9237. if (!uniform)
  9238. return;
  9239. this._gl.uniform3f(uniform, x, y, z);
  9240. };
  9241. Engine.prototype.setBool = function (uniform, bool) {
  9242. if (!uniform)
  9243. return;
  9244. this._gl.uniform1i(uniform, bool);
  9245. };
  9246. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9247. if (!uniform)
  9248. return;
  9249. this._gl.uniform4f(uniform, x, y, z, w);
  9250. };
  9251. Engine.prototype.setColor3 = function (uniform, color3) {
  9252. if (!uniform)
  9253. return;
  9254. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9255. };
  9256. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9257. if (!uniform)
  9258. return;
  9259. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9260. };
  9261. // States
  9262. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9263. if (zOffset === void 0) { zOffset = 0; }
  9264. if (reverseSide === void 0) { reverseSide = false; }
  9265. // Culling
  9266. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9267. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9268. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9269. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9270. if (culling) {
  9271. this._depthCullingState.cullFace = cullFace;
  9272. this._depthCullingState.cull = true;
  9273. }
  9274. else {
  9275. this._depthCullingState.cull = false;
  9276. }
  9277. }
  9278. // Z offset
  9279. this._depthCullingState.zOffset = zOffset;
  9280. };
  9281. Engine.prototype.setDepthBuffer = function (enable) {
  9282. this._depthCullingState.depthTest = enable;
  9283. };
  9284. Engine.prototype.getDepthWrite = function () {
  9285. return this._depthCullingState.depthMask;
  9286. };
  9287. Engine.prototype.setDepthWrite = function (enable) {
  9288. this._depthCullingState.depthMask = enable;
  9289. };
  9290. Engine.prototype.setColorWrite = function (enable) {
  9291. this._gl.colorMask(enable, enable, enable, enable);
  9292. };
  9293. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9294. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9295. if (this._alphaMode === mode) {
  9296. return;
  9297. }
  9298. switch (mode) {
  9299. case Engine.ALPHA_DISABLE:
  9300. this._alphaState.alphaBlend = false;
  9301. break;
  9302. case Engine.ALPHA_PREMULTIPLIED:
  9303. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9304. this._alphaState.alphaBlend = true;
  9305. break;
  9306. case Engine.ALPHA_COMBINE:
  9307. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9308. this._alphaState.alphaBlend = true;
  9309. break;
  9310. case Engine.ALPHA_ONEONE:
  9311. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9312. this._alphaState.alphaBlend = true;
  9313. break;
  9314. case Engine.ALPHA_ADD:
  9315. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9316. this._alphaState.alphaBlend = true;
  9317. break;
  9318. case Engine.ALPHA_SUBTRACT:
  9319. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9320. this._alphaState.alphaBlend = true;
  9321. break;
  9322. case Engine.ALPHA_MULTIPLY:
  9323. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9324. this._alphaState.alphaBlend = true;
  9325. break;
  9326. case Engine.ALPHA_MAXIMIZED:
  9327. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9328. this._alphaState.alphaBlend = true;
  9329. break;
  9330. }
  9331. if (!noDepthWriteChange) {
  9332. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9333. }
  9334. this._alphaMode = mode;
  9335. };
  9336. Engine.prototype.getAlphaMode = function () {
  9337. return this._alphaMode;
  9338. };
  9339. Engine.prototype.setAlphaTesting = function (enable) {
  9340. this._alphaTest = enable;
  9341. };
  9342. Engine.prototype.getAlphaTesting = function () {
  9343. return this._alphaTest;
  9344. };
  9345. // Textures
  9346. Engine.prototype.wipeCaches = function () {
  9347. this.resetTextureCache();
  9348. this._currentEffect = null;
  9349. this._stencilState.reset();
  9350. this._depthCullingState.reset();
  9351. this.setDepthFunctionToLessOrEqual();
  9352. this._alphaState.reset();
  9353. this._cachedVertexBuffers = null;
  9354. this._cachedIndexBuffer = null;
  9355. this._cachedEffectForVertexBuffers = null;
  9356. this._unBindVertexArrayObject();
  9357. this.bindIndexBuffer(null);
  9358. this.bindArrayBuffer(null);
  9359. };
  9360. /**
  9361. * Set the compressed texture format to use, based on the formats you have, and the formats
  9362. * supported by the hardware / browser.
  9363. *
  9364. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9365. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9366. * to API arguments needed to compressed textures. This puts the burden on the container
  9367. * generator to house the arcane code for determining these for current & future formats.
  9368. *
  9369. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9370. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9371. *
  9372. * Note: The result of this call is not taken into account when a texture is base64.
  9373. *
  9374. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9375. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9376. *
  9377. * Current families are astc, dxt, pvrtc, etc2, atc, & etc1.
  9378. * @returns The extension selected.
  9379. */
  9380. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9381. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9382. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9383. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9384. return this._textureFormatInUse = this._texturesSupported[i];
  9385. }
  9386. }
  9387. }
  9388. // actively set format to nothing, to allow this to be called more than once
  9389. // and possibly fail the 2nd time
  9390. return this._textureFormatInUse = null;
  9391. };
  9392. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9393. var _this = this;
  9394. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9395. if (onLoad === void 0) { onLoad = null; }
  9396. if (onError === void 0) { onError = null; }
  9397. if (buffer === void 0) { buffer = null; }
  9398. var texture = fallBack ? fallBack : this._gl.createTexture();
  9399. var extension;
  9400. var isKTX = false;
  9401. var fromData = false;
  9402. var url = String(urlArg);
  9403. if (url.substr(0, 5) === "data:") {
  9404. fromData = true;
  9405. }
  9406. if (!fromData) {
  9407. var lastDot = url.lastIndexOf('.');
  9408. extension = url.substring(lastDot).toLowerCase();
  9409. if (this._textureFormatInUse && !fromData && !fallBack) {
  9410. extension = this._textureFormatInUse;
  9411. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9412. isKTX = true;
  9413. }
  9414. }
  9415. else {
  9416. var oldUrl = url;
  9417. fromData = oldUrl.split(':');
  9418. url = oldUrl;
  9419. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  9420. }
  9421. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9422. var isTGA = (extension === ".tga");
  9423. scene._addPendingData(texture);
  9424. texture.url = url;
  9425. texture.noMipmap = noMipmap;
  9426. texture.references = 1;
  9427. texture.samplingMode = samplingMode;
  9428. texture.onLoadedCallbacks = [];
  9429. if (onLoad) {
  9430. texture.onLoadedCallbacks.push(onLoad);
  9431. }
  9432. if (!fallBack)
  9433. this._loadedTexturesCache.push(texture);
  9434. var onerror = function () {
  9435. scene._removePendingData(texture);
  9436. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9437. if (isKTX) {
  9438. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, texture);
  9439. }
  9440. else if (onError) {
  9441. onError();
  9442. }
  9443. };
  9444. var callback;
  9445. if (isKTX || isTGA || isDDS) {
  9446. if (isKTX) {
  9447. callback = function (data) {
  9448. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9449. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9450. ktx.uploadLevels(_this._gl, !noMipmap);
  9451. }, samplingMode);
  9452. };
  9453. }
  9454. else if (isTGA) {
  9455. callback = function (arrayBuffer) {
  9456. var data = new Uint8Array(arrayBuffer);
  9457. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9458. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9459. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9460. }, samplingMode);
  9461. };
  9462. }
  9463. else if (isDDS) {
  9464. callback = function (data) {
  9465. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9466. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9467. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9468. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9469. }, samplingMode);
  9470. };
  9471. }
  9472. if (!(fromData instanceof Array))
  9473. BABYLON.Tools.LoadFile(url, function (data) {
  9474. callback(data);
  9475. }, null, scene.database, true, onerror);
  9476. else
  9477. callback(buffer);
  9478. }
  9479. else {
  9480. var onload = function (img) {
  9481. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9482. var isPot = (img.width === potWidth && img.height === potHeight);
  9483. if (!isPot) {
  9484. _this._prepareWorkingCanvas();
  9485. _this._workingCanvas.width = potWidth;
  9486. _this._workingCanvas.height = potHeight;
  9487. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9488. _this._workingContext.imageSmoothingEnabled = false;
  9489. _this._workingContext.mozImageSmoothingEnabled = false;
  9490. _this._workingContext.oImageSmoothingEnabled = false;
  9491. _this._workingContext.webkitImageSmoothingEnabled = false;
  9492. _this._workingContext.msImageSmoothingEnabled = false;
  9493. }
  9494. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9495. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9496. _this._workingContext.imageSmoothingEnabled = true;
  9497. _this._workingContext.mozImageSmoothingEnabled = true;
  9498. _this._workingContext.oImageSmoothingEnabled = true;
  9499. _this._workingContext.webkitImageSmoothingEnabled = true;
  9500. _this._workingContext.msImageSmoothingEnabled = true;
  9501. }
  9502. }
  9503. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9504. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9505. }, samplingMode);
  9506. };
  9507. if (!(fromData instanceof Array))
  9508. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9509. else
  9510. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9511. }
  9512. return texture;
  9513. };
  9514. Engine.prototype._getInternalFormat = function (format) {
  9515. var internalFormat = this._gl.RGBA;
  9516. switch (format) {
  9517. case Engine.TEXTUREFORMAT_ALPHA:
  9518. internalFormat = this._gl.ALPHA;
  9519. break;
  9520. case Engine.TEXTUREFORMAT_LUMINANCE:
  9521. internalFormat = this._gl.LUMINANCE;
  9522. break;
  9523. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9524. internalFormat = this._gl.LUMINANCE_ALPHA;
  9525. break;
  9526. case Engine.TEXTUREFORMAT_RGB:
  9527. internalFormat = this._gl.RGB;
  9528. break;
  9529. case Engine.TEXTUREFORMAT_RGBA:
  9530. internalFormat = this._gl.RGBA;
  9531. break;
  9532. }
  9533. return internalFormat;
  9534. };
  9535. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9536. if (compression === void 0) { compression = null; }
  9537. var internalFormat = this._getInternalFormat(format);
  9538. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9539. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9540. if (texture._width % 4 !== 0) {
  9541. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9542. }
  9543. if (compression) {
  9544. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9545. }
  9546. else {
  9547. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9548. }
  9549. if (texture.generateMipMaps) {
  9550. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9551. }
  9552. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9553. this.resetTextureCache();
  9554. texture.isReady = true;
  9555. };
  9556. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9557. if (compression === void 0) { compression = null; }
  9558. var texture = this._gl.createTexture();
  9559. texture._baseWidth = width;
  9560. texture._baseHeight = height;
  9561. texture._width = width;
  9562. texture._height = height;
  9563. texture.references = 1;
  9564. this.updateRawTexture(texture, data, format, invertY, compression);
  9565. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9566. // Filters
  9567. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9568. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9569. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9570. if (generateMipMaps) {
  9571. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9572. }
  9573. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9574. texture.samplingMode = samplingMode;
  9575. this._loadedTexturesCache.push(texture);
  9576. return texture;
  9577. };
  9578. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9579. var texture = this._gl.createTexture();
  9580. texture._baseWidth = width;
  9581. texture._baseHeight = height;
  9582. if (generateMipMaps) {
  9583. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9584. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9585. }
  9586. this.resetTextureCache();
  9587. texture._width = width;
  9588. texture._height = height;
  9589. texture.isReady = false;
  9590. texture.generateMipMaps = generateMipMaps;
  9591. texture.references = 1;
  9592. texture.samplingMode = samplingMode;
  9593. this.updateTextureSamplingMode(samplingMode, texture);
  9594. this._loadedTexturesCache.push(texture);
  9595. return texture;
  9596. };
  9597. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9598. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9599. if (texture.isCube) {
  9600. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9601. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9602. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9603. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9604. }
  9605. else {
  9606. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9607. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9608. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9609. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9610. }
  9611. texture.samplingMode = samplingMode;
  9612. };
  9613. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9614. if (premulAlpha === void 0) { premulAlpha = false; }
  9615. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9616. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9617. if (premulAlpha) {
  9618. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9619. }
  9620. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9621. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9622. if (texture.generateMipMaps) {
  9623. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9624. }
  9625. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9626. if (premulAlpha) {
  9627. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9628. }
  9629. this.resetTextureCache();
  9630. texture.isReady = true;
  9631. };
  9632. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9633. if (texture._isDisabled) {
  9634. return;
  9635. }
  9636. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9637. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9638. try {
  9639. // Testing video texture support
  9640. if (this._videoTextureSupported === undefined) {
  9641. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9642. if (this._gl.getError() !== 0) {
  9643. this._videoTextureSupported = false;
  9644. }
  9645. else {
  9646. this._videoTextureSupported = true;
  9647. }
  9648. }
  9649. // Copy video through the current working canvas if video texture is not supported
  9650. if (!this._videoTextureSupported) {
  9651. if (!texture._workingCanvas) {
  9652. texture._workingCanvas = document.createElement("canvas");
  9653. texture._workingContext = texture._workingCanvas.getContext("2d");
  9654. texture._workingCanvas.width = texture._width;
  9655. texture._workingCanvas.height = texture._height;
  9656. }
  9657. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9658. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9659. }
  9660. else {
  9661. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9662. }
  9663. if (texture.generateMipMaps) {
  9664. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9665. }
  9666. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9667. this.resetTextureCache();
  9668. texture.isReady = true;
  9669. }
  9670. catch (ex) {
  9671. // Something unexpected
  9672. // Let's disable the texture
  9673. texture._isDisabled = true;
  9674. }
  9675. };
  9676. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9677. // old version had a "generateMipMaps" arg instead of options.
  9678. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9679. // in the same way, generateDepthBuffer is defaulted to true
  9680. var generateMipMaps = false;
  9681. var generateDepthBuffer = true;
  9682. var generateStencilBuffer = false;
  9683. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9684. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9685. if (options !== undefined) {
  9686. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9687. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9688. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9689. type = options.type === undefined ? type : options.type;
  9690. if (options.samplingMode !== undefined) {
  9691. samplingMode = options.samplingMode;
  9692. }
  9693. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9694. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9695. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9696. }
  9697. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9698. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9699. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9700. }
  9701. }
  9702. var gl = this._gl;
  9703. var texture = gl.createTexture();
  9704. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9705. var width = size.width || size;
  9706. var height = size.height || size;
  9707. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9708. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9709. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9710. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9711. }
  9712. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9713. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9714. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9715. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9716. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9717. var depthStencilBuffer;
  9718. // Create the depth/stencil buffer
  9719. if (generateStencilBuffer) {
  9720. depthStencilBuffer = gl.createRenderbuffer();
  9721. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9722. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9723. }
  9724. else if (generateDepthBuffer) {
  9725. depthStencilBuffer = gl.createRenderbuffer();
  9726. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9727. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9728. }
  9729. // Create the framebuffer
  9730. var framebuffer = gl.createFramebuffer();
  9731. this.bindUnboundFramebuffer(framebuffer);
  9732. // Manage attachments
  9733. if (generateStencilBuffer) {
  9734. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9735. }
  9736. else if (generateDepthBuffer) {
  9737. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9738. }
  9739. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9740. if (generateMipMaps) {
  9741. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9742. }
  9743. // Unbind
  9744. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9745. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9746. this.bindUnboundFramebuffer(null);
  9747. texture._framebuffer = framebuffer;
  9748. if (generateDepthBuffer) {
  9749. texture._depthBuffer = depthStencilBuffer;
  9750. }
  9751. texture._baseWidth = width;
  9752. texture._baseHeight = height;
  9753. texture._width = width;
  9754. texture._height = height;
  9755. texture.isReady = true;
  9756. texture.generateMipMaps = generateMipMaps;
  9757. texture.references = 1;
  9758. texture.samplingMode = samplingMode;
  9759. texture.type = type;
  9760. this.resetTextureCache();
  9761. this._loadedTexturesCache.push(texture);
  9762. return texture;
  9763. };
  9764. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9765. var gl = this._gl;
  9766. var texture = gl.createTexture();
  9767. var generateMipMaps = true;
  9768. var generateDepthBuffer = true;
  9769. var generateStencilBuffer = false;
  9770. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9771. if (options !== undefined) {
  9772. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9773. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9774. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9775. if (options.samplingMode !== undefined) {
  9776. samplingMode = options.samplingMode;
  9777. }
  9778. }
  9779. texture.isCube = true;
  9780. texture.references = 1;
  9781. texture.generateMipMaps = generateMipMaps;
  9782. texture.references = 1;
  9783. texture.samplingMode = samplingMode;
  9784. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9785. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9786. for (var face = 0; face < 6; face++) {
  9787. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9788. }
  9789. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9790. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9791. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9792. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9793. // Create the depth buffer
  9794. var depthStencilBuffer;
  9795. // Create the depth/stencil buffer
  9796. if (generateStencilBuffer) {
  9797. depthStencilBuffer = gl.createRenderbuffer();
  9798. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9799. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  9800. }
  9801. else if (generateDepthBuffer) {
  9802. depthStencilBuffer = gl.createRenderbuffer();
  9803. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9804. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  9805. }
  9806. // Create the framebuffer
  9807. var framebuffer = gl.createFramebuffer();
  9808. this.bindUnboundFramebuffer(framebuffer);
  9809. // Manage attachments
  9810. if (generateStencilBuffer) {
  9811. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9812. }
  9813. else if (generateDepthBuffer) {
  9814. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9815. }
  9816. // Mipmaps
  9817. if (texture.generateMipMaps) {
  9818. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9819. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9820. }
  9821. // Unbind
  9822. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9823. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9824. this.bindUnboundFramebuffer(null);
  9825. texture._framebuffer = framebuffer;
  9826. if (generateDepthBuffer) {
  9827. texture._depthBuffer = depthStencilBuffer;
  9828. }
  9829. texture._width = size;
  9830. texture._height = size;
  9831. texture.isReady = true;
  9832. this.resetTextureCache();
  9833. this._loadedTexturesCache.push(texture);
  9834. return texture;
  9835. };
  9836. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9837. var _this = this;
  9838. if (onLoad === void 0) { onLoad = null; }
  9839. if (onError === void 0) { onError = null; }
  9840. var gl = this._gl;
  9841. var texture = gl.createTexture();
  9842. texture.isCube = true;
  9843. texture.url = rootUrl;
  9844. texture.references = 1;
  9845. texture.onLoadedCallbacks = [];
  9846. var isKTX = false;
  9847. var lastDot = rootUrl.lastIndexOf('.');
  9848. var extension = rootUrl.substring(lastDot).toLowerCase();
  9849. if (this._textureFormatInUse) {
  9850. extension = this._textureFormatInUse;
  9851. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9852. isKTX = true;
  9853. }
  9854. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9855. if (isKTX) {
  9856. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9857. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9858. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9859. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9860. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9861. ktx.uploadLevels(_this._gl, !noMipmap);
  9862. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9863. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9865. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9866. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9867. _this.resetTextureCache();
  9868. texture._width = ktx.pixelWidth;
  9869. texture._height = ktx.pixelHeight;
  9870. texture.isReady = true;
  9871. }, null, null, true, onError);
  9872. }
  9873. else if (isDDS) {
  9874. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9875. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9876. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9877. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9878. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9879. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9880. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9881. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9882. }
  9883. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9884. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9885. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9886. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9887. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9888. _this.resetTextureCache();
  9889. texture._width = info.width;
  9890. texture._height = info.height;
  9891. texture.isReady = true;
  9892. }, null, null, true, onError);
  9893. }
  9894. else {
  9895. cascadeLoad(rootUrl, scene, function (imgs) {
  9896. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9897. var height = width;
  9898. _this._prepareWorkingCanvas();
  9899. _this._workingCanvas.width = width;
  9900. _this._workingCanvas.height = height;
  9901. var faces = [
  9902. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9903. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9904. ];
  9905. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9906. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9907. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9908. for (var index = 0; index < faces.length; index++) {
  9909. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9910. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9911. }
  9912. if (!noMipmap) {
  9913. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9914. }
  9915. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9916. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9917. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9918. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9919. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9920. _this.resetTextureCache();
  9921. texture._width = width;
  9922. texture._height = height;
  9923. texture.isReady = true;
  9924. texture.onLoadedCallbacks.forEach(function (callback) {
  9925. callback();
  9926. });
  9927. if (onLoad) {
  9928. onLoad();
  9929. }
  9930. }, files, onError);
  9931. }
  9932. this._loadedTexturesCache.push(texture);
  9933. return texture;
  9934. };
  9935. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9936. texture._width = width;
  9937. texture._height = height;
  9938. texture._size = width * height;
  9939. texture._baseWidth = width;
  9940. texture._baseHeight = height;
  9941. };
  9942. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  9943. var _this = this;
  9944. if (onLoad === void 0) { onLoad = null; }
  9945. if (onError === void 0) { onError = null; }
  9946. var gl = this._gl;
  9947. var texture = gl.createTexture();
  9948. scene._addPendingData(texture);
  9949. texture.isCube = true;
  9950. texture.references = 1;
  9951. texture.url = url;
  9952. var textureType = gl.UNSIGNED_BYTE;
  9953. if (type === Engine.TEXTURETYPE_FLOAT) {
  9954. textureType = gl.FLOAT;
  9955. }
  9956. var internalFormat = this._getInternalFormat(format);
  9957. var needConversion = false;
  9958. if (internalFormat === gl.RGB) {
  9959. internalFormat = gl.RGBA;
  9960. needConversion = true;
  9961. }
  9962. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9963. var width = size;
  9964. var height = width;
  9965. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9966. texture._width = width;
  9967. texture._height = height;
  9968. var onerror = function () {
  9969. scene._removePendingData(texture);
  9970. if (onError) {
  9971. onError();
  9972. }
  9973. };
  9974. var internalCallback = function (data) {
  9975. var rgbeDataArrays = callback(data);
  9976. var facesIndex = [
  9977. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9978. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9979. ];
  9980. width = texture._width;
  9981. height = texture._height;
  9982. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9983. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9984. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9985. if (mipmmapGenerator) {
  9986. var arrayTemp = [];
  9987. // Data are known to be in +X +Y +Z -X -Y -Z
  9988. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9989. arrayTemp.push(rgbeDataArrays[0]); // +X
  9990. arrayTemp.push(rgbeDataArrays[3]); // -X
  9991. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9992. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9993. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9994. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9995. var mipData = mipmmapGenerator(arrayTemp);
  9996. // mipData is order in +X -X +Y -Y +Z -Z
  9997. var mipFaces = [0, 2, 4, 1, 3, 5];
  9998. for (var level = 0; level < mipData.length; level++) {
  9999. var mipSize = width >> level;
  10000. for (var mipIndex in mipFaces) {
  10001. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  10002. if (needConversion) {
  10003. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10004. }
  10005. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10006. }
  10007. }
  10008. }
  10009. else {
  10010. // Data are known to be in +X +Y +Z -X -Y -Z
  10011. for (var index = 0; index < facesIndex.length; index++) {
  10012. var faceData = rgbeDataArrays[index];
  10013. if (needConversion) {
  10014. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  10015. }
  10016. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  10017. }
  10018. if (!noMipmap && isPot) {
  10019. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10020. }
  10021. else {
  10022. noMipmap = true;
  10023. }
  10024. }
  10025. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  10026. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10027. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10028. }
  10029. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  10030. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10031. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10032. }
  10033. else {
  10034. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10035. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10036. }
  10037. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10038. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10039. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10040. texture.isReady = true;
  10041. _this.resetTextureCache();
  10042. scene._removePendingData(texture);
  10043. if (onLoad) {
  10044. onLoad();
  10045. }
  10046. };
  10047. BABYLON.Tools.LoadFile(url, function (data) {
  10048. internalCallback(data);
  10049. }, onerror, scene.database, true);
  10050. return texture;
  10051. };
  10052. ;
  10053. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10054. // Create new RGBA data container.
  10055. var rgbaData;
  10056. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10057. rgbaData = new Float32Array(width * height * 4);
  10058. }
  10059. else {
  10060. rgbaData = new Uint32Array(width * height * 4);
  10061. }
  10062. // Convert each pixel.
  10063. for (var x = 0; x < width; x++) {
  10064. for (var y = 0; y < height; y++) {
  10065. var index = (y * width + x) * 3;
  10066. var newIndex = (y * width + x) * 4;
  10067. // Map Old Value to new value.
  10068. rgbaData[newIndex + 0] = rgbData[index + 0];
  10069. rgbaData[newIndex + 1] = rgbData[index + 1];
  10070. rgbaData[newIndex + 2] = rgbData[index + 2];
  10071. // Add fully opaque alpha channel.
  10072. rgbaData[newIndex + 3] = 1;
  10073. }
  10074. }
  10075. return rgbaData;
  10076. };
  10077. Engine.prototype._releaseTexture = function (texture) {
  10078. var gl = this._gl;
  10079. if (texture._framebuffer) {
  10080. gl.deleteFramebuffer(texture._framebuffer);
  10081. }
  10082. if (texture._depthBuffer) {
  10083. gl.deleteRenderbuffer(texture._depthBuffer);
  10084. }
  10085. gl.deleteTexture(texture);
  10086. // Unbind channels
  10087. this.unbindAllTextures();
  10088. var index = this._loadedTexturesCache.indexOf(texture);
  10089. if (index !== -1) {
  10090. this._loadedTexturesCache.splice(index, 1);
  10091. }
  10092. };
  10093. Engine.prototype.setProgram = function (program) {
  10094. if (this._currentProgram !== program) {
  10095. this._gl.useProgram(program);
  10096. this._currentProgram = program;
  10097. }
  10098. };
  10099. Engine.prototype.bindSamplers = function (effect) {
  10100. this.setProgram(effect.getProgram());
  10101. var samplers = effect.getSamplers();
  10102. for (var index = 0; index < samplers.length; index++) {
  10103. var uniform = effect.getUniform(samplers[index]);
  10104. this._gl.uniform1i(uniform, index);
  10105. }
  10106. this._currentEffect = null;
  10107. };
  10108. Engine.prototype.activateTexture = function (texture) {
  10109. if (this._activeTexture !== texture) {
  10110. this._gl.activeTexture(texture);
  10111. this._activeTexture = texture;
  10112. }
  10113. };
  10114. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10115. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10116. this._gl.bindTexture(target, texture);
  10117. this._activeTexturesCache[this._activeTexture] = texture;
  10118. }
  10119. };
  10120. Engine.prototype._bindTexture = function (channel, texture) {
  10121. if (channel < 0) {
  10122. return;
  10123. }
  10124. this.activateTexture(this._gl.TEXTURE0 + channel);
  10125. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10126. };
  10127. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10128. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10129. };
  10130. Engine.prototype.unbindAllTextures = function () {
  10131. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10132. this.activateTexture(this._gl["TEXTURE" + channel]);
  10133. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10134. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10135. }
  10136. };
  10137. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10138. if (channel < 0) {
  10139. return;
  10140. }
  10141. this._gl.uniform1i(uniform, channel);
  10142. this._setTexture(channel, texture);
  10143. };
  10144. Engine.prototype._setTexture = function (channel, texture) {
  10145. // Not ready?
  10146. if (!texture || !texture.isReady()) {
  10147. if (this._activeTexturesCache[channel] != null) {
  10148. this.activateTexture(this._gl["TEXTURE" + channel]);
  10149. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10150. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10151. }
  10152. return;
  10153. }
  10154. // Video
  10155. var alreadyActivated = false;
  10156. if (texture instanceof BABYLON.VideoTexture) {
  10157. this.activateTexture(this._gl["TEXTURE" + channel]);
  10158. alreadyActivated = true;
  10159. texture.update();
  10160. }
  10161. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10162. texture.delayLoad();
  10163. return;
  10164. }
  10165. var internalTexture = texture.getInternalTexture();
  10166. if (this._activeTexturesCache[channel] === internalTexture) {
  10167. return;
  10168. }
  10169. if (!alreadyActivated) {
  10170. this.activateTexture(this._gl["TEXTURE" + channel]);
  10171. }
  10172. if (internalTexture.isCube) {
  10173. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10174. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10175. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10176. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10177. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10178. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10179. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10180. }
  10181. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10182. }
  10183. else {
  10184. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10185. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10186. internalTexture._cachedWrapU = texture.wrapU;
  10187. switch (texture.wrapU) {
  10188. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10189. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10190. break;
  10191. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10192. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10193. break;
  10194. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10195. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10196. break;
  10197. }
  10198. }
  10199. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10200. internalTexture._cachedWrapV = texture.wrapV;
  10201. switch (texture.wrapV) {
  10202. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10203. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10204. break;
  10205. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10206. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10207. break;
  10208. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10209. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10210. break;
  10211. }
  10212. }
  10213. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10214. }
  10215. };
  10216. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10217. if (channel < 0) {
  10218. return;
  10219. }
  10220. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10221. this._textureUnits = new Int32Array(textures.length);
  10222. }
  10223. for (var i = 0; i < textures.length; i++) {
  10224. this._textureUnits[i] = channel + i;
  10225. }
  10226. this._gl.uniform1iv(uniform, this._textureUnits);
  10227. for (var index = 0; index < textures.length; index++) {
  10228. this._setTexture(channel + index, textures[index]);
  10229. }
  10230. };
  10231. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10232. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10233. var value = texture.anisotropicFilteringLevel;
  10234. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10235. value = 1;
  10236. }
  10237. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10238. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10239. texture._cachedAnisotropicFilteringLevel = value;
  10240. }
  10241. };
  10242. Engine.prototype.readPixels = function (x, y, width, height) {
  10243. var data = new Uint8Array(height * width * 4);
  10244. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10245. return data;
  10246. };
  10247. /**
  10248. * Add an externaly attached data from its key.
  10249. * This method call will fail and return false, if such key already exists.
  10250. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10251. * @param key the unique key that identifies the data
  10252. * @param data the data object to associate to the key for this Engine instance
  10253. * @return true if no such key were already present and the data was added successfully, false otherwise
  10254. */
  10255. Engine.prototype.addExternalData = function (key, data) {
  10256. return this._externalData.add(key, data);
  10257. };
  10258. /**
  10259. * Get an externaly attached data from its key
  10260. * @param key the unique key that identifies the data
  10261. * @return the associated data, if present (can be null), or undefined if not present
  10262. */
  10263. Engine.prototype.getExternalData = function (key) {
  10264. return this._externalData.get(key);
  10265. };
  10266. /**
  10267. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10268. * @param key the unique key that identifies the data
  10269. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10270. * @return the associated data, can be null if the factory returned null.
  10271. */
  10272. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10273. return this._externalData.getOrAddWithFactory(key, factory);
  10274. };
  10275. /**
  10276. * Remove an externaly attached data from the Engine instance
  10277. * @param key the unique key that identifies the data
  10278. * @return true if the data was successfully removed, false if it doesn't exist
  10279. */
  10280. Engine.prototype.removeExternalData = function (key) {
  10281. return this._externalData.remove(key);
  10282. };
  10283. Engine.prototype.releaseInternalTexture = function (texture) {
  10284. if (!texture) {
  10285. return;
  10286. }
  10287. texture.references--;
  10288. // Final reference ?
  10289. if (texture.references === 0) {
  10290. var texturesCache = this.getLoadedTexturesCache();
  10291. var index = texturesCache.indexOf(texture);
  10292. if (index > -1) {
  10293. texturesCache.splice(index, 1);
  10294. }
  10295. this._releaseTexture(texture);
  10296. }
  10297. };
  10298. Engine.prototype.unbindAllAttributes = function () {
  10299. if (this._mustWipeVertexAttributes) {
  10300. this._mustWipeVertexAttributes = false;
  10301. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10302. this._gl.disableVertexAttribArray(i);
  10303. this._vertexAttribArraysEnabled[i] = false;
  10304. this._currentBufferPointers[i] = null;
  10305. }
  10306. return;
  10307. }
  10308. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10309. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10310. continue;
  10311. }
  10312. this._gl.disableVertexAttribArray(i);
  10313. this._vertexAttribArraysEnabled[i] = false;
  10314. this._currentBufferPointers[i] = null;
  10315. }
  10316. };
  10317. // Dispose
  10318. Engine.prototype.dispose = function () {
  10319. this.hideLoadingUI();
  10320. this.stopRenderLoop();
  10321. // Release scenes
  10322. while (this.scenes.length) {
  10323. this.scenes[0].dispose();
  10324. }
  10325. // Release audio engine
  10326. Engine.audioEngine.dispose();
  10327. // Release effects
  10328. for (var name in this._compiledEffects) {
  10329. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10330. }
  10331. // Unbind
  10332. this.unbindAllAttributes();
  10333. this._gl = null;
  10334. //WebVR
  10335. this.disableVR();
  10336. // Events
  10337. window.removeEventListener("blur", this._onBlur);
  10338. window.removeEventListener("focus", this._onFocus);
  10339. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10340. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10341. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10342. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10343. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10344. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10345. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10346. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10347. // Remove from Instances
  10348. var index = Engine.Instances.indexOf(this);
  10349. if (index >= 0) {
  10350. Engine.Instances.splice(index, 1);
  10351. }
  10352. };
  10353. // Loading screen
  10354. Engine.prototype.displayLoadingUI = function () {
  10355. this._loadingScreen.displayLoadingUI();
  10356. };
  10357. Engine.prototype.hideLoadingUI = function () {
  10358. this._loadingScreen.hideLoadingUI();
  10359. };
  10360. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10361. get: function () {
  10362. return this._loadingScreen;
  10363. },
  10364. set: function (loadingScreen) {
  10365. this._loadingScreen = loadingScreen;
  10366. },
  10367. enumerable: true,
  10368. configurable: true
  10369. });
  10370. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10371. set: function (text) {
  10372. this._loadingScreen.loadingUIText = text;
  10373. },
  10374. enumerable: true,
  10375. configurable: true
  10376. });
  10377. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10378. set: function (color) {
  10379. this._loadingScreen.loadingUIBackgroundColor = color;
  10380. },
  10381. enumerable: true,
  10382. configurable: true
  10383. });
  10384. Engine.prototype.attachContextLostEvent = function (callback) {
  10385. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10386. };
  10387. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10388. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10389. };
  10390. Engine.prototype.getVertexShaderSource = function (program) {
  10391. var shaders = this._gl.getAttachedShaders(program);
  10392. return this._gl.getShaderSource(shaders[0]);
  10393. };
  10394. Engine.prototype.getFragmentShaderSource = function (program) {
  10395. var shaders = this._gl.getAttachedShaders(program);
  10396. return this._gl.getShaderSource(shaders[1]);
  10397. };
  10398. // FPS
  10399. Engine.prototype.getFps = function () {
  10400. return this.fps;
  10401. };
  10402. Engine.prototype.getDeltaTime = function () {
  10403. return this.deltaTime;
  10404. };
  10405. Engine.prototype._measureFps = function () {
  10406. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10407. var length = this.previousFramesDuration.length;
  10408. if (length >= 2) {
  10409. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10410. }
  10411. if (length >= this.fpsRange) {
  10412. if (length > this.fpsRange) {
  10413. this.previousFramesDuration.splice(0, 1);
  10414. length = this.previousFramesDuration.length;
  10415. }
  10416. var sum = 0;
  10417. for (var id = 0; id < length - 1; id++) {
  10418. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10419. }
  10420. this.fps = 1000.0 / (sum / (length - 1));
  10421. }
  10422. };
  10423. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10424. if (this._webGLVersion > 1) {
  10425. return this._caps.colorBufferFloat;
  10426. }
  10427. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10428. };
  10429. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10430. if (this._webGLVersion > 1) {
  10431. return this._caps.colorBufferFloat;
  10432. }
  10433. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10434. };
  10435. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10436. Engine.prototype._canRenderToFramebuffer = function (type) {
  10437. var gl = this._gl;
  10438. //clear existing errors
  10439. while (gl.getError() !== gl.NO_ERROR) { }
  10440. var successful = true;
  10441. var texture = gl.createTexture();
  10442. gl.bindTexture(gl.TEXTURE_2D, texture);
  10443. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10444. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10445. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10446. var fb = gl.createFramebuffer();
  10447. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10448. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10449. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10450. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10451. successful = successful && (gl.getError() === gl.NO_ERROR);
  10452. //try render by clearing frame buffer's color buffer
  10453. if (successful) {
  10454. gl.clear(gl.COLOR_BUFFER_BIT);
  10455. successful = successful && (gl.getError() === gl.NO_ERROR);
  10456. }
  10457. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10458. if (successful) {
  10459. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10460. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10461. var readFormat = gl.RGBA;
  10462. var readType = gl.UNSIGNED_BYTE;
  10463. var buffer = new Uint8Array(4);
  10464. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10465. successful = successful && (gl.getError() === gl.NO_ERROR);
  10466. }
  10467. //clean up
  10468. gl.deleteTexture(texture);
  10469. gl.deleteFramebuffer(fb);
  10470. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10471. //clear accumulated errors
  10472. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10473. return successful;
  10474. };
  10475. Engine.prototype._getWebGLTextureType = function (type) {
  10476. if (type === Engine.TEXTURETYPE_FLOAT) {
  10477. return this._gl.FLOAT;
  10478. }
  10479. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10480. // Add Half Float Constant.
  10481. return Engine.HALF_FLOAT_OES;
  10482. }
  10483. return this._gl.UNSIGNED_BYTE;
  10484. };
  10485. ;
  10486. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10487. if (this._webGLVersion === 1) {
  10488. return this._gl.RGBA;
  10489. }
  10490. if (type === Engine.TEXTURETYPE_FLOAT) {
  10491. return Engine.RGBA32F;
  10492. }
  10493. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10494. return Engine.RGBA16F;
  10495. }
  10496. return this._gl.RGBA;
  10497. };
  10498. ;
  10499. // Statics
  10500. Engine.isSupported = function () {
  10501. try {
  10502. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10503. if (navigator.isCocoonJS) {
  10504. return true;
  10505. }
  10506. var tempcanvas = document.createElement("canvas");
  10507. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10508. return gl != null && !!window.WebGLRenderingContext;
  10509. }
  10510. catch (e) {
  10511. return false;
  10512. }
  10513. };
  10514. return Engine;
  10515. }());
  10516. Engine.Instances = new Array();
  10517. // Const statics
  10518. Engine._ALPHA_DISABLE = 0;
  10519. Engine._ALPHA_ADD = 1;
  10520. Engine._ALPHA_COMBINE = 2;
  10521. Engine._ALPHA_SUBTRACT = 3;
  10522. Engine._ALPHA_MULTIPLY = 4;
  10523. Engine._ALPHA_MAXIMIZED = 5;
  10524. Engine._ALPHA_ONEONE = 6;
  10525. Engine._ALPHA_PREMULTIPLIED = 7;
  10526. Engine._DELAYLOADSTATE_NONE = 0;
  10527. Engine._DELAYLOADSTATE_LOADED = 1;
  10528. Engine._DELAYLOADSTATE_LOADING = 2;
  10529. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10530. Engine._TEXTUREFORMAT_ALPHA = 0;
  10531. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10532. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10533. Engine._TEXTUREFORMAT_RGB = 4;
  10534. Engine._TEXTUREFORMAT_RGBA = 5;
  10535. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10536. Engine._TEXTURETYPE_FLOAT = 1;
  10537. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10538. // Depht or Stencil test Constants.
  10539. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10540. 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.
  10541. 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.
  10542. 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.
  10543. 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.
  10544. 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.
  10545. 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.
  10546. 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.
  10547. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10548. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10549. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10550. // Stencil Actions Constants.
  10551. Engine._KEEP = 0x1E00;
  10552. Engine._REPLACE = 0x1E01;
  10553. Engine._INCR = 0x1E02;
  10554. Engine._DECR = 0x1E03;
  10555. Engine._INVERT = 0x150A;
  10556. Engine._INCR_WRAP = 0x8507;
  10557. Engine._DECR_WRAP = 0x8508;
  10558. // Updatable statics so stick with vars here
  10559. Engine.CollisionsEpsilon = 0.001;
  10560. Engine.CodeRepository = "src/";
  10561. Engine.ShadersRepository = "src/Shaders/";
  10562. BABYLON.Engine = Engine;
  10563. })(BABYLON || (BABYLON = {}));
  10564. //# sourceMappingURL=babylon.engine.js.map
  10565. /// <reference path="Tools\babylon.decorators.ts" />
  10566. var BABYLON;
  10567. (function (BABYLON) {
  10568. /**
  10569. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10570. */
  10571. var Node = (function () {
  10572. /**
  10573. * @constructor
  10574. * @param {string} name - the name and id to be given to this node
  10575. * @param {BABYLON.Scene} the scene this node will be added to
  10576. */
  10577. function Node(name, scene) {
  10578. this.state = "";
  10579. this.metadata = null;
  10580. this.doNotSerialize = false;
  10581. this.animations = new Array();
  10582. this._ranges = {};
  10583. this._childrenFlag = -1;
  10584. this._isEnabled = true;
  10585. this._isReady = true;
  10586. this._currentRenderId = -1;
  10587. this._parentRenderId = -1;
  10588. /**
  10589. * An event triggered when the mesh is disposed.
  10590. * @type {BABYLON.Observable}
  10591. */
  10592. this.onDisposeObservable = new BABYLON.Observable();
  10593. this.name = name;
  10594. this.id = name;
  10595. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10596. this._initCache();
  10597. }
  10598. Object.defineProperty(Node.prototype, "parent", {
  10599. get: function () {
  10600. return this._parentNode;
  10601. },
  10602. set: function (parent) {
  10603. if (this._parentNode === parent) {
  10604. return;
  10605. }
  10606. if (this._parentNode) {
  10607. var index = this._parentNode._children.indexOf(this);
  10608. if (index !== -1) {
  10609. this._parentNode._children.splice(index, 1);
  10610. }
  10611. }
  10612. this._parentNode = parent;
  10613. if (this._parentNode) {
  10614. if (!this._parentNode._children) {
  10615. this._parentNode._children = new Array();
  10616. }
  10617. this._parentNode._children.push(this);
  10618. }
  10619. },
  10620. enumerable: true,
  10621. configurable: true
  10622. });
  10623. Node.prototype.getClassName = function () {
  10624. return "Node";
  10625. };
  10626. Object.defineProperty(Node.prototype, "onDispose", {
  10627. set: function (callback) {
  10628. if (this._onDisposeObserver) {
  10629. this.onDisposeObservable.remove(this._onDisposeObserver);
  10630. }
  10631. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10632. },
  10633. enumerable: true,
  10634. configurable: true
  10635. });
  10636. Node.prototype.getScene = function () {
  10637. return this._scene;
  10638. };
  10639. Node.prototype.getEngine = function () {
  10640. return this._scene.getEngine();
  10641. };
  10642. // override it in derived class
  10643. Node.prototype.getWorldMatrix = function () {
  10644. return BABYLON.Matrix.Identity();
  10645. };
  10646. // override it in derived class if you add new variables to the cache
  10647. // and call the parent class method
  10648. Node.prototype._initCache = function () {
  10649. this._cache = {};
  10650. this._cache.parent = undefined;
  10651. };
  10652. Node.prototype.updateCache = function (force) {
  10653. if (!force && this.isSynchronized())
  10654. return;
  10655. this._cache.parent = this.parent;
  10656. this._updateCache();
  10657. };
  10658. // override it in derived class if you add new variables to the cache
  10659. // and call the parent class method if !ignoreParentClass
  10660. Node.prototype._updateCache = function (ignoreParentClass) {
  10661. };
  10662. // override it in derived class if you add new variables to the cache
  10663. Node.prototype._isSynchronized = function () {
  10664. return true;
  10665. };
  10666. Node.prototype._markSyncedWithParent = function () {
  10667. this._parentRenderId = this.parent._currentRenderId;
  10668. };
  10669. Node.prototype.isSynchronizedWithParent = function () {
  10670. if (!this.parent) {
  10671. return true;
  10672. }
  10673. if (this._parentRenderId !== this.parent._currentRenderId) {
  10674. return false;
  10675. }
  10676. return this.parent.isSynchronized();
  10677. };
  10678. Node.prototype.isSynchronized = function (updateCache) {
  10679. var check = this.hasNewParent();
  10680. check = check || !this.isSynchronizedWithParent();
  10681. check = check || !this._isSynchronized();
  10682. if (updateCache)
  10683. this.updateCache(true);
  10684. return !check;
  10685. };
  10686. Node.prototype.hasNewParent = function (update) {
  10687. if (this._cache.parent === this.parent)
  10688. return false;
  10689. if (update)
  10690. this._cache.parent = this.parent;
  10691. return true;
  10692. };
  10693. /**
  10694. * Is this node ready to be used/rendered
  10695. * @return {boolean} is it ready
  10696. */
  10697. Node.prototype.isReady = function () {
  10698. return this._isReady;
  10699. };
  10700. /**
  10701. * Is this node enabled.
  10702. * If the node has a parent and is enabled, the parent will be inspected as well.
  10703. * @return {boolean} whether this node (and its parent) is enabled.
  10704. * @see setEnabled
  10705. */
  10706. Node.prototype.isEnabled = function () {
  10707. if (!this._isEnabled) {
  10708. return false;
  10709. }
  10710. if (this.parent) {
  10711. return this.parent.isEnabled();
  10712. }
  10713. return true;
  10714. };
  10715. /**
  10716. * Set the enabled state of this node.
  10717. * @param {boolean} value - the new enabled state
  10718. * @see isEnabled
  10719. */
  10720. Node.prototype.setEnabled = function (value) {
  10721. this._isEnabled = value;
  10722. };
  10723. /**
  10724. * Is this node a descendant of the given node.
  10725. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10726. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10727. * @see parent
  10728. */
  10729. Node.prototype.isDescendantOf = function (ancestor) {
  10730. if (this.parent) {
  10731. if (this.parent === ancestor) {
  10732. return true;
  10733. }
  10734. return this.parent.isDescendantOf(ancestor);
  10735. }
  10736. return false;
  10737. };
  10738. /**
  10739. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10740. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10741. * @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.
  10742. * @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.
  10743. */
  10744. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10745. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10746. if (!this._children) {
  10747. return;
  10748. }
  10749. for (var index = 0; index < this._children.length; index++) {
  10750. var item = this._children[index];
  10751. if (!predicate || predicate(item)) {
  10752. results.push(item);
  10753. }
  10754. if (!directDescendantsOnly) {
  10755. item._getDescendants(results, false, predicate);
  10756. }
  10757. }
  10758. };
  10759. /**
  10760. * Will return all nodes that have this node as ascendant.
  10761. * @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.
  10762. * @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.
  10763. * @return {BABYLON.Node[]} all children nodes of all types.
  10764. */
  10765. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10766. var results = [];
  10767. this._getDescendants(results, directDescendantsOnly, predicate);
  10768. return results;
  10769. };
  10770. /**
  10771. * @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.
  10772. * @Deprecated, legacy support.
  10773. * use getDecendants instead.
  10774. */
  10775. Node.prototype.getChildren = function (predicate) {
  10776. return this.getDescendants(true, predicate);
  10777. };
  10778. /**
  10779. * Get all child-meshes of this node.
  10780. */
  10781. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10782. var results = [];
  10783. this._getDescendants(results, directDecendantsOnly, function (node) {
  10784. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10785. });
  10786. return results;
  10787. };
  10788. Node.prototype._setReady = function (state) {
  10789. if (state === this._isReady) {
  10790. return;
  10791. }
  10792. if (!state) {
  10793. this._isReady = false;
  10794. return;
  10795. }
  10796. this._isReady = true;
  10797. if (this.onReady) {
  10798. this.onReady(this);
  10799. }
  10800. };
  10801. Node.prototype.getAnimationByName = function (name) {
  10802. for (var i = 0; i < this.animations.length; i++) {
  10803. var animation = this.animations[i];
  10804. if (animation.name === name) {
  10805. return animation;
  10806. }
  10807. }
  10808. return null;
  10809. };
  10810. Node.prototype.createAnimationRange = function (name, from, to) {
  10811. // check name not already in use
  10812. if (!this._ranges[name]) {
  10813. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10814. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10815. if (this.animations[i]) {
  10816. this.animations[i].createRange(name, from, to);
  10817. }
  10818. }
  10819. }
  10820. };
  10821. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10822. if (deleteFrames === void 0) { deleteFrames = true; }
  10823. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10824. if (this.animations[i]) {
  10825. this.animations[i].deleteRange(name, deleteFrames);
  10826. }
  10827. }
  10828. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10829. };
  10830. Node.prototype.getAnimationRange = function (name) {
  10831. return this._ranges[name];
  10832. };
  10833. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10834. var range = this.getAnimationRange(name);
  10835. if (!range) {
  10836. return null;
  10837. }
  10838. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10839. };
  10840. Node.prototype.serializeAnimationRanges = function () {
  10841. var serializationRanges = [];
  10842. for (var name in this._ranges) {
  10843. var range = {};
  10844. range.name = name;
  10845. range.from = this._ranges[name].from;
  10846. range.to = this._ranges[name].to;
  10847. serializationRanges.push(range);
  10848. }
  10849. return serializationRanges;
  10850. };
  10851. Node.prototype.dispose = function () {
  10852. this.parent = null;
  10853. // Callback
  10854. this.onDisposeObservable.notifyObservers(this);
  10855. this.onDisposeObservable.clear();
  10856. };
  10857. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10858. if (parsedNode.ranges) {
  10859. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10860. var data = parsedNode.ranges[index];
  10861. node.createAnimationRange(data.name, data.from, data.to);
  10862. }
  10863. }
  10864. };
  10865. return Node;
  10866. }());
  10867. __decorate([
  10868. BABYLON.serialize()
  10869. ], Node.prototype, "name", void 0);
  10870. __decorate([
  10871. BABYLON.serialize()
  10872. ], Node.prototype, "id", void 0);
  10873. __decorate([
  10874. BABYLON.serialize()
  10875. ], Node.prototype, "uniqueId", void 0);
  10876. __decorate([
  10877. BABYLON.serialize()
  10878. ], Node.prototype, "state", void 0);
  10879. __decorate([
  10880. BABYLON.serialize()
  10881. ], Node.prototype, "metadata", void 0);
  10882. BABYLON.Node = Node;
  10883. })(BABYLON || (BABYLON = {}));
  10884. //# sourceMappingURL=babylon.node.js.map
  10885. var BABYLON;
  10886. (function (BABYLON) {
  10887. var FilesInput = (function () {
  10888. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  10889. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  10890. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  10891. this._engine = p_engine;
  10892. this._canvas = p_canvas;
  10893. this._currentScene = p_scene;
  10894. this._sceneLoadedCallback = p_sceneLoadedCallback;
  10895. this._progressCallback = p_progressCallback;
  10896. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  10897. this._textureLoadingCallback = p_textureLoadingCallback;
  10898. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  10899. }
  10900. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  10901. var _this = this;
  10902. if (p_elementToMonitor) {
  10903. this._elementToMonitor = p_elementToMonitor;
  10904. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  10905. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  10906. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  10907. }
  10908. };
  10909. FilesInput.prototype.renderFunction = function () {
  10910. if (this._additionnalRenderLoopLogicCallback) {
  10911. this._additionnalRenderLoopLogicCallback();
  10912. }
  10913. if (this._currentScene) {
  10914. if (this._textureLoadingCallback) {
  10915. var remaining = this._currentScene.getWaitingItemsCount();
  10916. if (remaining > 0) {
  10917. this._textureLoadingCallback(remaining);
  10918. }
  10919. }
  10920. this._currentScene.render();
  10921. }
  10922. };
  10923. FilesInput.prototype.drag = function (e) {
  10924. e.stopPropagation();
  10925. e.preventDefault();
  10926. };
  10927. FilesInput.prototype.drop = function (eventDrop) {
  10928. eventDrop.stopPropagation();
  10929. eventDrop.preventDefault();
  10930. this.loadFiles(eventDrop);
  10931. };
  10932. FilesInput.prototype.loadFiles = function (event) {
  10933. if (this._startingProcessingFilesCallback)
  10934. this._startingProcessingFilesCallback();
  10935. // Handling data transfer via drag'n'drop
  10936. if (event && event.dataTransfer && event.dataTransfer.files) {
  10937. this._filesToLoad = event.dataTransfer.files;
  10938. }
  10939. // Handling files from input files
  10940. if (event && event.target && event.target.files) {
  10941. this._filesToLoad = event.target.files;
  10942. }
  10943. if (this._filesToLoad && this._filesToLoad.length > 0) {
  10944. for (var i = 0; i < this._filesToLoad.length; i++) {
  10945. var name_1 = this._filesToLoad[i].name.toLowerCase();
  10946. var extension = name_1.split('.').pop();
  10947. var type = this._filesToLoad[i].type;
  10948. if (extension === "jpg" || extension === "png" || extension === "bmp" || extension === "jpeg" ||
  10949. type === "image/jpeg" || type === "image/png" || type === "image/bmp") {
  10950. FilesInput.FilesTextures[name_1] = this._filesToLoad[i];
  10951. }
  10952. else {
  10953. if ((extension === "babylon" || extension === "stl" || extension === "obj")
  10954. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  10955. this._sceneFileToLoad = this._filesToLoad[i];
  10956. }
  10957. else {
  10958. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  10959. }
  10960. }
  10961. }
  10962. this.reload();
  10963. }
  10964. };
  10965. FilesInput.prototype.reload = function () {
  10966. var _this = this;
  10967. var that = this;
  10968. // If a ".babylon" file has been provided
  10969. if (this._sceneFileToLoad) {
  10970. if (this._currentScene) {
  10971. if (BABYLON.Tools.errorsCount > 0) {
  10972. BABYLON.Tools.ClearLogCache();
  10973. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  10974. }
  10975. this._engine.stopRenderLoop();
  10976. this._currentScene.dispose();
  10977. }
  10978. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  10979. that._currentScene = newScene;
  10980. // Wait for textures and shaders to be ready
  10981. that._currentScene.executeWhenReady(function () {
  10982. // Attach camera to canvas inputs
  10983. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  10984. that._currentScene.createDefaultCameraOrLight();
  10985. }
  10986. that._currentScene.activeCamera.attachControl(that._canvas);
  10987. if (that._sceneLoadedCallback) {
  10988. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  10989. }
  10990. that._engine.runRenderLoop(function () { that.renderFunction(); });
  10991. });
  10992. }, function (progress) {
  10993. if (_this._progressCallback) {
  10994. _this._progressCallback(progress);
  10995. }
  10996. });
  10997. }
  10998. else {
  10999. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  11000. }
  11001. };
  11002. return FilesInput;
  11003. }());
  11004. FilesInput.FilesTextures = new Array();
  11005. FilesInput.FilesToLoad = new Array();
  11006. BABYLON.FilesInput = FilesInput;
  11007. })(BABYLON || (BABYLON = {}));
  11008. //# sourceMappingURL=babylon.filesInput.js.map
  11009. var BABYLON;
  11010. (function (BABYLON) {
  11011. var IntersectionInfo = (function () {
  11012. function IntersectionInfo(bu, bv, distance) {
  11013. this.bu = bu;
  11014. this.bv = bv;
  11015. this.distance = distance;
  11016. this.faceId = 0;
  11017. this.subMeshId = 0;
  11018. }
  11019. return IntersectionInfo;
  11020. }());
  11021. BABYLON.IntersectionInfo = IntersectionInfo;
  11022. var PickingInfo = (function () {
  11023. function PickingInfo() {
  11024. this.hit = false;
  11025. this.distance = 0;
  11026. this.pickedPoint = null;
  11027. this.pickedMesh = null;
  11028. this.bu = 0;
  11029. this.bv = 0;
  11030. this.faceId = -1;
  11031. this.subMeshId = 0;
  11032. this.pickedSprite = null;
  11033. }
  11034. // Methods
  11035. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  11036. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  11037. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  11038. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11039. return null;
  11040. }
  11041. var indices = this.pickedMesh.getIndices();
  11042. var result;
  11043. if (useVerticesNormals) {
  11044. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11045. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  11046. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  11047. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  11048. normal0 = normal0.scale(this.bu);
  11049. normal1 = normal1.scale(this.bv);
  11050. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  11051. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  11052. }
  11053. else {
  11054. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11055. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  11056. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  11057. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  11058. var p1p2 = vertex1.subtract(vertex2);
  11059. var p3p2 = vertex3.subtract(vertex2);
  11060. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  11061. }
  11062. if (useWorldCoordinates) {
  11063. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  11064. }
  11065. return BABYLON.Vector3.Normalize(result);
  11066. };
  11067. PickingInfo.prototype.getTextureCoordinates = function () {
  11068. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11069. return null;
  11070. }
  11071. var indices = this.pickedMesh.getIndices();
  11072. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11073. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  11074. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  11075. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  11076. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  11077. uv1 = uv1.scale(this.bu);
  11078. uv2 = uv2.scale(this.bv);
  11079. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  11080. };
  11081. return PickingInfo;
  11082. }());
  11083. BABYLON.PickingInfo = PickingInfo;
  11084. })(BABYLON || (BABYLON = {}));
  11085. //# sourceMappingURL=babylon.pickingInfo.js.map
  11086. var BABYLON;
  11087. (function (BABYLON) {
  11088. var BoundingSphere = (function () {
  11089. function BoundingSphere(minimum, maximum) {
  11090. this.minimum = minimum;
  11091. this.maximum = maximum;
  11092. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11093. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11094. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11095. this.radius = distance * 0.5;
  11096. this.centerWorld = BABYLON.Vector3.Zero();
  11097. this._update(BABYLON.Matrix.Identity());
  11098. }
  11099. // Methods
  11100. BoundingSphere.prototype._update = function (world) {
  11101. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11102. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11103. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11104. };
  11105. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11106. for (var i = 0; i < 6; i++) {
  11107. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11108. return false;
  11109. }
  11110. return true;
  11111. };
  11112. BoundingSphere.prototype.intersectsPoint = function (point) {
  11113. var x = this.centerWorld.x - point.x;
  11114. var y = this.centerWorld.y - point.y;
  11115. var z = this.centerWorld.z - point.z;
  11116. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11117. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11118. return false;
  11119. return true;
  11120. };
  11121. // Statics
  11122. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11123. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11124. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11125. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11126. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11127. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11128. return false;
  11129. return true;
  11130. };
  11131. return BoundingSphere;
  11132. }());
  11133. BABYLON.BoundingSphere = BoundingSphere;
  11134. })(BABYLON || (BABYLON = {}));
  11135. //# sourceMappingURL=babylon.boundingSphere.js.map
  11136. var BABYLON;
  11137. (function (BABYLON) {
  11138. var BoundingBox = (function () {
  11139. function BoundingBox(minimum, maximum) {
  11140. this.minimum = minimum;
  11141. this.maximum = maximum;
  11142. this.vectors = new Array();
  11143. this.vectorsWorld = new Array();
  11144. // Bounding vectors
  11145. this.vectors.push(this.minimum.clone());
  11146. this.vectors.push(this.maximum.clone());
  11147. this.vectors.push(this.minimum.clone());
  11148. this.vectors[2].x = this.maximum.x;
  11149. this.vectors.push(this.minimum.clone());
  11150. this.vectors[3].y = this.maximum.y;
  11151. this.vectors.push(this.minimum.clone());
  11152. this.vectors[4].z = this.maximum.z;
  11153. this.vectors.push(this.maximum.clone());
  11154. this.vectors[5].z = this.minimum.z;
  11155. this.vectors.push(this.maximum.clone());
  11156. this.vectors[6].x = this.minimum.x;
  11157. this.vectors.push(this.maximum.clone());
  11158. this.vectors[7].y = this.minimum.y;
  11159. // OBB
  11160. this.center = this.maximum.add(this.minimum).scale(0.5);
  11161. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11162. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11163. // World
  11164. for (var index = 0; index < this.vectors.length; index++) {
  11165. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11166. }
  11167. this.minimumWorld = BABYLON.Vector3.Zero();
  11168. this.maximumWorld = BABYLON.Vector3.Zero();
  11169. this._update(BABYLON.Matrix.Identity());
  11170. }
  11171. // Methods
  11172. BoundingBox.prototype.getWorldMatrix = function () {
  11173. return this._worldMatrix;
  11174. };
  11175. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11176. this._worldMatrix.copyFrom(matrix);
  11177. return this;
  11178. };
  11179. BoundingBox.prototype._update = function (world) {
  11180. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11181. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11182. for (var index = 0; index < this.vectors.length; index++) {
  11183. var v = this.vectorsWorld[index];
  11184. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11185. if (v.x < this.minimumWorld.x)
  11186. this.minimumWorld.x = v.x;
  11187. if (v.y < this.minimumWorld.y)
  11188. this.minimumWorld.y = v.y;
  11189. if (v.z < this.minimumWorld.z)
  11190. this.minimumWorld.z = v.z;
  11191. if (v.x > this.maximumWorld.x)
  11192. this.maximumWorld.x = v.x;
  11193. if (v.y > this.maximumWorld.y)
  11194. this.maximumWorld.y = v.y;
  11195. if (v.z > this.maximumWorld.z)
  11196. this.maximumWorld.z = v.z;
  11197. }
  11198. // OBB
  11199. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  11200. this.center.scaleInPlace(0.5);
  11201. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11202. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11203. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11204. this._worldMatrix = world;
  11205. };
  11206. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11207. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11208. };
  11209. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11210. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11211. };
  11212. BoundingBox.prototype.intersectsPoint = function (point) {
  11213. var delta = -BABYLON.Epsilon;
  11214. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11215. return false;
  11216. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11217. return false;
  11218. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11219. return false;
  11220. return true;
  11221. };
  11222. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11223. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11224. };
  11225. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11226. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11227. return false;
  11228. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11229. return false;
  11230. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11231. return false;
  11232. return true;
  11233. };
  11234. // Statics
  11235. BoundingBox.Intersects = function (box0, box1) {
  11236. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11237. return false;
  11238. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11239. return false;
  11240. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11241. return false;
  11242. return true;
  11243. };
  11244. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11245. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11246. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11247. return (num <= (sphereRadius * sphereRadius));
  11248. };
  11249. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11250. for (var p = 0; p < 6; p++) {
  11251. for (var i = 0; i < 8; i++) {
  11252. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11253. return false;
  11254. }
  11255. }
  11256. }
  11257. return true;
  11258. };
  11259. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11260. for (var p = 0; p < 6; p++) {
  11261. var inCount = 8;
  11262. for (var i = 0; i < 8; i++) {
  11263. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11264. --inCount;
  11265. }
  11266. else {
  11267. break;
  11268. }
  11269. }
  11270. if (inCount === 0)
  11271. return false;
  11272. }
  11273. return true;
  11274. };
  11275. return BoundingBox;
  11276. }());
  11277. BABYLON.BoundingBox = BoundingBox;
  11278. })(BABYLON || (BABYLON = {}));
  11279. //# sourceMappingURL=babylon.boundingBox.js.map
  11280. var BABYLON;
  11281. (function (BABYLON) {
  11282. var computeBoxExtents = function (axis, box) {
  11283. var p = BABYLON.Vector3.Dot(box.center, axis);
  11284. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11285. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11286. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11287. var r = r0 + r1 + r2;
  11288. return {
  11289. min: p - r,
  11290. max: p + r
  11291. };
  11292. };
  11293. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11294. var axisOverlap = function (axis, box0, box1) {
  11295. var result0 = computeBoxExtents(axis, box0);
  11296. var result1 = computeBoxExtents(axis, box1);
  11297. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11298. };
  11299. var BoundingInfo = (function () {
  11300. function BoundingInfo(minimum, maximum) {
  11301. this.minimum = minimum;
  11302. this.maximum = maximum;
  11303. this._isLocked = false;
  11304. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11305. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11306. }
  11307. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11308. get: function () {
  11309. return this._isLocked;
  11310. },
  11311. set: function (value) {
  11312. this._isLocked = value;
  11313. },
  11314. enumerable: true,
  11315. configurable: true
  11316. });
  11317. // Methods
  11318. BoundingInfo.prototype.update = function (world) {
  11319. if (this._isLocked) {
  11320. return;
  11321. }
  11322. this.boundingBox._update(world);
  11323. this.boundingSphere._update(world);
  11324. };
  11325. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11326. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11327. return false;
  11328. return this.boundingBox.isInFrustum(frustumPlanes);
  11329. };
  11330. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11331. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11332. };
  11333. BoundingInfo.prototype._checkCollision = function (collider) {
  11334. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11335. };
  11336. BoundingInfo.prototype.intersectsPoint = function (point) {
  11337. if (!this.boundingSphere.centerWorld) {
  11338. return false;
  11339. }
  11340. if (!this.boundingSphere.intersectsPoint(point)) {
  11341. return false;
  11342. }
  11343. if (!this.boundingBox.intersectsPoint(point)) {
  11344. return false;
  11345. }
  11346. return true;
  11347. };
  11348. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11349. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11350. return false;
  11351. }
  11352. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11353. return false;
  11354. }
  11355. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11356. return false;
  11357. }
  11358. if (!precise) {
  11359. return true;
  11360. }
  11361. var box0 = this.boundingBox;
  11362. var box1 = boundingInfo.boundingBox;
  11363. if (!axisOverlap(box0.directions[0], box0, box1))
  11364. return false;
  11365. if (!axisOverlap(box0.directions[1], box0, box1))
  11366. return false;
  11367. if (!axisOverlap(box0.directions[2], box0, box1))
  11368. return false;
  11369. if (!axisOverlap(box1.directions[0], box0, box1))
  11370. return false;
  11371. if (!axisOverlap(box1.directions[1], box0, box1))
  11372. return false;
  11373. if (!axisOverlap(box1.directions[2], box0, box1))
  11374. return false;
  11375. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11376. return false;
  11377. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11378. return false;
  11379. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11380. return false;
  11381. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11382. return false;
  11383. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11384. return false;
  11385. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11386. return false;
  11387. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11388. return false;
  11389. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11390. return false;
  11391. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11392. return false;
  11393. return true;
  11394. };
  11395. return BoundingInfo;
  11396. }());
  11397. BABYLON.BoundingInfo = BoundingInfo;
  11398. })(BABYLON || (BABYLON = {}));
  11399. //# sourceMappingURL=babylon.boundingInfo.js.map
  11400. var BABYLON;
  11401. (function (BABYLON) {
  11402. var Ray = (function () {
  11403. function Ray(origin, direction, length) {
  11404. if (length === void 0) { length = Number.MAX_VALUE; }
  11405. this.origin = origin;
  11406. this.direction = direction;
  11407. this.length = length;
  11408. }
  11409. // Methods
  11410. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  11411. var d = 0.0;
  11412. var maxValue = Number.MAX_VALUE;
  11413. var inv;
  11414. var min;
  11415. var max;
  11416. var temp;
  11417. if (Math.abs(this.direction.x) < 0.0000001) {
  11418. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  11419. return false;
  11420. }
  11421. }
  11422. else {
  11423. inv = 1.0 / this.direction.x;
  11424. min = (minimum.x - this.origin.x) * inv;
  11425. max = (maximum.x - this.origin.x) * inv;
  11426. if (max === -Infinity) {
  11427. max = Infinity;
  11428. }
  11429. if (min > max) {
  11430. temp = min;
  11431. min = max;
  11432. max = temp;
  11433. }
  11434. d = Math.max(min, d);
  11435. maxValue = Math.min(max, maxValue);
  11436. if (d > maxValue) {
  11437. return false;
  11438. }
  11439. }
  11440. if (Math.abs(this.direction.y) < 0.0000001) {
  11441. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  11442. return false;
  11443. }
  11444. }
  11445. else {
  11446. inv = 1.0 / this.direction.y;
  11447. min = (minimum.y - this.origin.y) * inv;
  11448. max = (maximum.y - this.origin.y) * inv;
  11449. if (max === -Infinity) {
  11450. max = Infinity;
  11451. }
  11452. if (min > max) {
  11453. temp = min;
  11454. min = max;
  11455. max = temp;
  11456. }
  11457. d = Math.max(min, d);
  11458. maxValue = Math.min(max, maxValue);
  11459. if (d > maxValue) {
  11460. return false;
  11461. }
  11462. }
  11463. if (Math.abs(this.direction.z) < 0.0000001) {
  11464. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  11465. return false;
  11466. }
  11467. }
  11468. else {
  11469. inv = 1.0 / this.direction.z;
  11470. min = (minimum.z - this.origin.z) * inv;
  11471. max = (maximum.z - this.origin.z) * inv;
  11472. if (max === -Infinity) {
  11473. max = Infinity;
  11474. }
  11475. if (min > max) {
  11476. temp = min;
  11477. min = max;
  11478. max = temp;
  11479. }
  11480. d = Math.max(min, d);
  11481. maxValue = Math.min(max, maxValue);
  11482. if (d > maxValue) {
  11483. return false;
  11484. }
  11485. }
  11486. return true;
  11487. };
  11488. Ray.prototype.intersectsBox = function (box) {
  11489. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  11490. };
  11491. Ray.prototype.intersectsSphere = function (sphere) {
  11492. var x = sphere.center.x - this.origin.x;
  11493. var y = sphere.center.y - this.origin.y;
  11494. var z = sphere.center.z - this.origin.z;
  11495. var pyth = (x * x) + (y * y) + (z * z);
  11496. var rr = sphere.radius * sphere.radius;
  11497. if (pyth <= rr) {
  11498. return true;
  11499. }
  11500. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  11501. if (dot < 0.0) {
  11502. return false;
  11503. }
  11504. var temp = pyth - (dot * dot);
  11505. return temp <= rr;
  11506. };
  11507. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  11508. if (!this._edge1) {
  11509. this._edge1 = BABYLON.Vector3.Zero();
  11510. this._edge2 = BABYLON.Vector3.Zero();
  11511. this._pvec = BABYLON.Vector3.Zero();
  11512. this._tvec = BABYLON.Vector3.Zero();
  11513. this._qvec = BABYLON.Vector3.Zero();
  11514. }
  11515. vertex1.subtractToRef(vertex0, this._edge1);
  11516. vertex2.subtractToRef(vertex0, this._edge2);
  11517. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  11518. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  11519. if (det === 0) {
  11520. return null;
  11521. }
  11522. var invdet = 1 / det;
  11523. this.origin.subtractToRef(vertex0, this._tvec);
  11524. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  11525. if (bu < 0 || bu > 1.0) {
  11526. return null;
  11527. }
  11528. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  11529. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  11530. if (bv < 0 || bu + bv > 1.0) {
  11531. return null;
  11532. }
  11533. //check if the distance is longer than the predefined length.
  11534. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  11535. if (distance > this.length) {
  11536. return null;
  11537. }
  11538. return new BABYLON.IntersectionInfo(bu, bv, distance);
  11539. };
  11540. Ray.prototype.intersectsPlane = function (plane) {
  11541. var distance;
  11542. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  11543. if (Math.abs(result1) < 9.99999997475243E-07) {
  11544. return null;
  11545. }
  11546. else {
  11547. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  11548. distance = (-plane.d - result2) / result1;
  11549. if (distance < 0.0) {
  11550. if (distance < -9.99999997475243E-07) {
  11551. return null;
  11552. }
  11553. else {
  11554. return 0;
  11555. }
  11556. }
  11557. return distance;
  11558. }
  11559. };
  11560. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  11561. var tm = BABYLON.Tmp.Matrix[0];
  11562. mesh.getWorldMatrix().invertToRef(tm);
  11563. if (this._tmpRay) {
  11564. Ray.TransformToRef(this, tm, this._tmpRay);
  11565. }
  11566. else {
  11567. this._tmpRay = Ray.Transform(this, tm);
  11568. }
  11569. return mesh.intersects(this._tmpRay, fastCheck);
  11570. };
  11571. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  11572. if (results) {
  11573. results.length = 0;
  11574. }
  11575. else {
  11576. results = [];
  11577. }
  11578. for (var i = 0; i < meshes.length; i++) {
  11579. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  11580. if (pickInfo.hit) {
  11581. results.push(pickInfo);
  11582. }
  11583. }
  11584. results.sort(this._comparePickingInfo);
  11585. return results;
  11586. };
  11587. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  11588. if (pickingInfoA.distance < pickingInfoB.distance) {
  11589. return -1;
  11590. }
  11591. else if (pickingInfoA.distance > pickingInfoB.distance) {
  11592. return 1;
  11593. }
  11594. else {
  11595. return 0;
  11596. }
  11597. };
  11598. /**
  11599. * @Deprecated. Use new RayHelper.show() instead.
  11600. * */
  11601. Ray.prototype.show = function (scene, color) {
  11602. console.warn('Ray.show() has been deprecated. Use new RayHelper.show() instead.');
  11603. if (!this._rayHelper) {
  11604. this._rayHelper = new BABYLON.RayHelper(this);
  11605. }
  11606. this._rayHelper.show(scene, color);
  11607. };
  11608. /**
  11609. * @Deprecated. Use new RayHelper.hide() instead.
  11610. * */
  11611. Ray.prototype.hide = function () {
  11612. console.warn('Ray.hide() has been deprecated. Use new RayHelper.hide() instead.');
  11613. if (this._rayHelper) {
  11614. this._rayHelper.hide();
  11615. this._rayHelper = null;
  11616. }
  11617. };
  11618. /**
  11619. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  11620. * @param sega the first point of the segment to test the intersection against
  11621. * @param segb the second point of the segment to test the intersection against
  11622. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  11623. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  11624. */
  11625. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  11626. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  11627. var u = segb.subtract(sega);
  11628. var v = rsegb.subtract(this.origin);
  11629. var w = sega.subtract(this.origin);
  11630. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  11631. var b = BABYLON.Vector3.Dot(u, v);
  11632. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  11633. var d = BABYLON.Vector3.Dot(u, w);
  11634. var e = BABYLON.Vector3.Dot(v, w);
  11635. var D = a * c - b * b; // always >= 0
  11636. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  11637. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  11638. // compute the line parameters of the two closest points
  11639. if (D < Ray.smallnum) {
  11640. sN = 0.0; // force using point P0 on segment S1
  11641. sD = 1.0; // to prevent possible division by 0.0 later
  11642. tN = e;
  11643. tD = c;
  11644. }
  11645. else {
  11646. sN = (b * e - c * d);
  11647. tN = (a * e - b * d);
  11648. if (sN < 0.0) {
  11649. sN = 0.0;
  11650. tN = e;
  11651. tD = c;
  11652. }
  11653. else if (sN > sD) {
  11654. sN = sD;
  11655. tN = e + b;
  11656. tD = c;
  11657. }
  11658. }
  11659. if (tN < 0.0) {
  11660. tN = 0.0;
  11661. // recompute sc for this edge
  11662. if (-d < 0.0) {
  11663. sN = 0.0;
  11664. }
  11665. else if (-d > a)
  11666. sN = sD;
  11667. else {
  11668. sN = -d;
  11669. sD = a;
  11670. }
  11671. }
  11672. else if (tN > tD) {
  11673. tN = tD;
  11674. // recompute sc for this edge
  11675. if ((-d + b) < 0.0) {
  11676. sN = 0;
  11677. }
  11678. else if ((-d + b) > a) {
  11679. sN = sD;
  11680. }
  11681. else {
  11682. sN = (-d + b);
  11683. sD = a;
  11684. }
  11685. }
  11686. // finally do the division to get sc and tc
  11687. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  11688. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  11689. // get the difference of the two closest points
  11690. var qtc = v.multiplyByFloats(tc, tc, tc);
  11691. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  11692. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  11693. if (isIntersected) {
  11694. return qtc.length();
  11695. }
  11696. return -1;
  11697. };
  11698. // Statics
  11699. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  11700. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  11701. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  11702. var direction = end.subtract(start);
  11703. direction.normalize();
  11704. return new Ray(start, direction);
  11705. };
  11706. /**
  11707. * 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
  11708. * transformed to the given world matrix.
  11709. * @param origin The origin point
  11710. * @param end The end point
  11711. * @param world a matrix to transform the ray to. Default is the identity matrix.
  11712. */
  11713. Ray.CreateNewFromTo = function (origin, end, world) {
  11714. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  11715. var direction = end.subtract(origin);
  11716. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  11717. direction.normalize();
  11718. return Ray.Transform(new Ray(origin, direction, length), world);
  11719. };
  11720. Ray.Transform = function (ray, matrix) {
  11721. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  11722. Ray.TransformToRef(ray, matrix, result);
  11723. return result;
  11724. };
  11725. Ray.TransformToRef = function (ray, matrix, result) {
  11726. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  11727. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  11728. result.length = ray.length;
  11729. var dir = result.direction;
  11730. var len = dir.length();
  11731. if (!(len === 0 || len === 1)) {
  11732. var num = 1.0 / len;
  11733. dir.x *= num;
  11734. dir.y *= num;
  11735. dir.z *= num;
  11736. result.length *= len;
  11737. }
  11738. };
  11739. return Ray;
  11740. }());
  11741. Ray.smallnum = 0.00000001;
  11742. Ray.rayl = 10e8;
  11743. BABYLON.Ray = Ray;
  11744. })(BABYLON || (BABYLON = {}));
  11745. //# sourceMappingURL=babylon.ray.js.map
  11746. var BABYLON;
  11747. (function (BABYLON) {
  11748. var RayHelper = (function () {
  11749. function RayHelper(ray) {
  11750. this.ray = ray;
  11751. }
  11752. RayHelper.prototype.show = function (scene, color) {
  11753. if (!this._renderFunction) {
  11754. var ray = this.ray;
  11755. this._renderFunction = this._render.bind(this);
  11756. this._scene = scene;
  11757. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  11758. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  11759. this._scene.registerBeforeRender(this._renderFunction);
  11760. }
  11761. if (color) {
  11762. this._renderLine.color.copyFrom(color);
  11763. }
  11764. };
  11765. RayHelper.prototype.hide = function () {
  11766. if (this._renderFunction) {
  11767. this._scene.unregisterBeforeRender(this._renderFunction);
  11768. this._scene = null;
  11769. this._renderFunction = null;
  11770. this._renderLine.dispose();
  11771. this._renderLine = null;
  11772. this._renderPoints = null;
  11773. }
  11774. };
  11775. RayHelper.prototype._render = function () {
  11776. var ray = this.ray;
  11777. var point = this._renderPoints[1];
  11778. var len = Math.min(ray.length, 1000000);
  11779. point.copyFrom(ray.direction);
  11780. point.scaleInPlace(len);
  11781. point.addInPlace(ray.origin);
  11782. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  11783. };
  11784. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  11785. this._attachedToMesh = mesh;
  11786. var ray = this.ray;
  11787. if (!ray.direction) {
  11788. ray.direction = BABYLON.Vector3.Zero();
  11789. }
  11790. if (!ray.origin) {
  11791. ray.origin = BABYLON.Vector3.Zero();
  11792. }
  11793. if (length) {
  11794. ray.length = length;
  11795. }
  11796. if (!meshSpaceOrigin) {
  11797. meshSpaceOrigin = BABYLON.Vector3.Zero();
  11798. }
  11799. if (!meshSpaceDirection) {
  11800. // -1 so that this will work with Mesh.lookAt
  11801. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  11802. }
  11803. if (!this._meshSpaceDirection) {
  11804. this._meshSpaceDirection = meshSpaceDirection.clone();
  11805. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  11806. }
  11807. else {
  11808. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  11809. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  11810. }
  11811. if (!this._updateToMeshFunction) {
  11812. this._updateToMeshFunction = this._updateToMesh.bind(this);
  11813. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  11814. }
  11815. this._updateToMesh();
  11816. };
  11817. RayHelper.prototype.detachFromMesh = function () {
  11818. if (this._attachedToMesh) {
  11819. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  11820. this._attachedToMesh = null;
  11821. this._updateToMeshFunction = null;
  11822. }
  11823. };
  11824. RayHelper.prototype._updateToMesh = function () {
  11825. var ray = this.ray;
  11826. if (this._attachedToMesh._isDisposed) {
  11827. this.detachFromMesh();
  11828. return;
  11829. }
  11830. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  11831. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  11832. };
  11833. RayHelper.prototype.dispose = function () {
  11834. this.hide();
  11835. this.detachFromMesh();
  11836. this.ray = null;
  11837. };
  11838. return RayHelper;
  11839. }());
  11840. BABYLON.RayHelper = RayHelper;
  11841. })(BABYLON || (BABYLON = {}));
  11842. //# sourceMappingURL=babylon.rayHelper.js.map
  11843. var BABYLON;
  11844. (function (BABYLON) {
  11845. var AbstractMesh = (function (_super) {
  11846. __extends(AbstractMesh, _super);
  11847. // Constructor
  11848. function AbstractMesh(name, scene) {
  11849. var _this = _super.call(this, name, scene) || this;
  11850. _this._facetNb = 0; // facet number
  11851. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11852. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11853. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11854. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11855. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11856. _this._subDiv = {
  11857. max: 1,
  11858. X: 1,
  11859. Y: 1,
  11860. Z: 1
  11861. };
  11862. // Events
  11863. /**
  11864. * An event triggered when this mesh collides with another one
  11865. * @type {BABYLON.Observable}
  11866. */
  11867. _this.onCollideObservable = new BABYLON.Observable();
  11868. /**
  11869. * An event triggered when the collision's position changes
  11870. * @type {BABYLON.Observable}
  11871. */
  11872. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11873. /**
  11874. * An event triggered after the world matrix is updated
  11875. * @type {BABYLON.Observable}
  11876. */
  11877. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11878. // Properties
  11879. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11880. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11881. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11882. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  11883. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11884. _this.visibility = 1.0;
  11885. _this.alphaIndex = Number.MAX_VALUE;
  11886. _this.infiniteDistance = false;
  11887. _this.isVisible = true;
  11888. _this.isPickable = true;
  11889. _this.showBoundingBox = false;
  11890. _this.showSubMeshesBoundingBox = false;
  11891. _this.isBlocker = false;
  11892. _this.renderingGroupId = 0;
  11893. _this.receiveShadows = false;
  11894. _this.renderOutline = false;
  11895. _this.outlineColor = BABYLON.Color3.Red();
  11896. _this.outlineWidth = 0.02;
  11897. _this.renderOverlay = false;
  11898. _this.overlayColor = BABYLON.Color3.Red();
  11899. _this.overlayAlpha = 0.5;
  11900. _this.hasVertexAlpha = false;
  11901. _this.useVertexColors = true;
  11902. _this.applyFog = true;
  11903. _this.computeBonesUsingShaders = true;
  11904. _this.scalingDeterminant = 1;
  11905. _this.numBoneInfluencers = 4;
  11906. _this.useOctreeForRenderingSelection = true;
  11907. _this.useOctreeForPicking = true;
  11908. _this.useOctreeForCollisions = true;
  11909. _this.layerMask = 0x0FFFFFFF;
  11910. /**
  11911. * True if the mesh must be rendered in any case.
  11912. */
  11913. _this.alwaysSelectAsActiveMesh = false;
  11914. // Collisions
  11915. _this._checkCollisions = false;
  11916. _this._collisionMask = -1;
  11917. _this._collisionGroup = -1;
  11918. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11919. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11920. _this._collider = new BABYLON.Collider();
  11921. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11922. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11923. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11924. // Edges
  11925. _this.edgesWidth = 1;
  11926. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11927. // Cache
  11928. _this._localWorld = BABYLON.Matrix.Zero();
  11929. _this._worldMatrix = BABYLON.Matrix.Zero();
  11930. _this._absolutePosition = BABYLON.Vector3.Zero();
  11931. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11932. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11933. _this._isDirty = false;
  11934. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11935. _this._isDisposed = false;
  11936. _this._renderId = 0;
  11937. _this._intersectionsInProgress = new Array();
  11938. _this._isWorldMatrixFrozen = false;
  11939. _this._unIndexed = false;
  11940. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11941. if (collidedMesh === void 0) { collidedMesh = null; }
  11942. //TODO move this to the collision coordinator!
  11943. if (_this.getScene().workerCollisions)
  11944. newPosition.multiplyInPlace(_this._collider.radius);
  11945. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11946. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11947. _this.position.addInPlace(_this._diffPositionForCollisions);
  11948. }
  11949. if (collidedMesh) {
  11950. _this.onCollideObservable.notifyObservers(collidedMesh);
  11951. }
  11952. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11953. };
  11954. _this.getScene().addMesh(_this);
  11955. return _this;
  11956. }
  11957. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11958. get: function () {
  11959. return AbstractMesh._BILLBOARDMODE_NONE;
  11960. },
  11961. enumerable: true,
  11962. configurable: true
  11963. });
  11964. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11965. get: function () {
  11966. return AbstractMesh._BILLBOARDMODE_X;
  11967. },
  11968. enumerable: true,
  11969. configurable: true
  11970. });
  11971. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11972. get: function () {
  11973. return AbstractMesh._BILLBOARDMODE_Y;
  11974. },
  11975. enumerable: true,
  11976. configurable: true
  11977. });
  11978. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11979. get: function () {
  11980. return AbstractMesh._BILLBOARDMODE_Z;
  11981. },
  11982. enumerable: true,
  11983. configurable: true
  11984. });
  11985. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11986. get: function () {
  11987. return AbstractMesh._BILLBOARDMODE_ALL;
  11988. },
  11989. enumerable: true,
  11990. configurable: true
  11991. });
  11992. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11993. /**
  11994. * Read-only : the number of facets in the mesh
  11995. */
  11996. get: function () {
  11997. return this._facetNb;
  11998. },
  11999. enumerable: true,
  12000. configurable: true
  12001. });
  12002. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12003. /**
  12004. * The number (integer) of subdivisions per axis in the partioning space
  12005. */
  12006. get: function () {
  12007. return this._partitioningSubdivisions;
  12008. },
  12009. set: function (nb) {
  12010. this._partitioningSubdivisions = nb;
  12011. },
  12012. enumerable: true,
  12013. configurable: true
  12014. });
  12015. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12016. /**
  12017. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12018. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12019. */
  12020. get: function () {
  12021. return this._partitioningBBoxRatio;
  12022. },
  12023. set: function (ratio) {
  12024. this._partitioningBBoxRatio = ratio;
  12025. },
  12026. enumerable: true,
  12027. configurable: true
  12028. });
  12029. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12030. /**
  12031. * Read-only boolean : is the feature facetData enabled ?
  12032. */
  12033. get: function () {
  12034. return this._facetDataEnabled;
  12035. },
  12036. enumerable: true,
  12037. configurable: true
  12038. });
  12039. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12040. set: function (callback) {
  12041. if (this._onCollideObserver) {
  12042. this.onCollideObservable.remove(this._onCollideObserver);
  12043. }
  12044. this._onCollideObserver = this.onCollideObservable.add(callback);
  12045. },
  12046. enumerable: true,
  12047. configurable: true
  12048. });
  12049. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12050. set: function (callback) {
  12051. if (this._onCollisionPositionChangeObserver) {
  12052. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12053. }
  12054. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12055. },
  12056. enumerable: true,
  12057. configurable: true
  12058. });
  12059. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12060. get: function () {
  12061. return this._collisionMask;
  12062. },
  12063. set: function (mask) {
  12064. this._collisionMask = !isNaN(mask) ? mask : -1;
  12065. },
  12066. enumerable: true,
  12067. configurable: true
  12068. });
  12069. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12070. get: function () {
  12071. return this._collisionGroup;
  12072. },
  12073. set: function (mask) {
  12074. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12075. },
  12076. enumerable: true,
  12077. configurable: true
  12078. });
  12079. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12080. get: function () {
  12081. return this._skeleton;
  12082. },
  12083. set: function (value) {
  12084. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12085. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12086. }
  12087. if (value && value.needInitialSkinMatrix) {
  12088. value._registerMeshWithPoseMatrix(this);
  12089. }
  12090. this._skeleton = value;
  12091. if (!this._skeleton) {
  12092. this._bonesTransformMatrices = null;
  12093. }
  12094. },
  12095. enumerable: true,
  12096. configurable: true
  12097. });
  12098. /**
  12099. * Returns the string "AbstractMesh"
  12100. */
  12101. AbstractMesh.prototype.getClassName = function () {
  12102. return "AbstractMesh";
  12103. };
  12104. /**
  12105. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12106. */
  12107. AbstractMesh.prototype.toString = function (fullDetails) {
  12108. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12109. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12110. if (this._skeleton) {
  12111. ret += ", skeleton: " + this._skeleton.name;
  12112. }
  12113. if (fullDetails) {
  12114. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12115. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12116. }
  12117. return ret;
  12118. };
  12119. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12120. /**
  12121. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12122. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12123. * Default : (0.0, 0.0, 0.0)
  12124. */
  12125. get: function () {
  12126. return this._rotation;
  12127. },
  12128. set: function (newRotation) {
  12129. this._rotation = newRotation;
  12130. },
  12131. enumerable: true,
  12132. configurable: true
  12133. });
  12134. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12135. /**
  12136. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12137. * Default : (1.0, 1.0, 1.0)
  12138. */
  12139. get: function () {
  12140. return this._scaling;
  12141. },
  12142. set: function (newScaling) {
  12143. this._scaling = newScaling;
  12144. if (this.physicsImpostor) {
  12145. this.physicsImpostor.forceUpdate();
  12146. }
  12147. },
  12148. enumerable: true,
  12149. configurable: true
  12150. });
  12151. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12152. /**
  12153. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12154. * It's null by default.
  12155. * 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)
  12156. */
  12157. get: function () {
  12158. return this._rotationQuaternion;
  12159. },
  12160. set: function (quaternion) {
  12161. this._rotationQuaternion = quaternion;
  12162. //reset the rotation vector.
  12163. if (quaternion && this.rotation.length()) {
  12164. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12165. }
  12166. },
  12167. enumerable: true,
  12168. configurable: true
  12169. });
  12170. // Methods
  12171. /**
  12172. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12173. * Returns the AbstractMesh.
  12174. */
  12175. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12176. this._poseMatrix.copyFrom(matrix);
  12177. return this;
  12178. };
  12179. /**
  12180. * Returns the mesh Pose matrix.
  12181. * Returned object : Matrix
  12182. */
  12183. AbstractMesh.prototype.getPoseMatrix = function () {
  12184. return this._poseMatrix;
  12185. };
  12186. /**
  12187. * Disables the mesh edger rendering mode.
  12188. * Returns the AbstractMesh.
  12189. */
  12190. AbstractMesh.prototype.disableEdgesRendering = function () {
  12191. if (this._edgesRenderer !== undefined) {
  12192. this._edgesRenderer.dispose();
  12193. this._edgesRenderer = undefined;
  12194. }
  12195. return this;
  12196. };
  12197. /**
  12198. * Enables the edge rendering mode on the mesh.
  12199. * This mode makes the mesh edges visible.
  12200. * Returns the AbstractMesh.
  12201. */
  12202. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12203. if (epsilon === void 0) { epsilon = 0.95; }
  12204. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12205. this.disableEdgesRendering();
  12206. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12207. return this;
  12208. };
  12209. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12210. /**
  12211. * Returns true if the mesh is blocked. Used by the class Mesh.
  12212. * Returns the boolean `false` by default.
  12213. */
  12214. get: function () {
  12215. return false;
  12216. },
  12217. enumerable: true,
  12218. configurable: true
  12219. });
  12220. /**
  12221. * Returns the mesh itself by default, used by the class Mesh.
  12222. * Returned type : AbstractMesh
  12223. */
  12224. AbstractMesh.prototype.getLOD = function (camera) {
  12225. return this;
  12226. };
  12227. /**
  12228. * Returns 0 by default, used by the class Mesh.
  12229. * Returns an integer.
  12230. */
  12231. AbstractMesh.prototype.getTotalVertices = function () {
  12232. return 0;
  12233. };
  12234. /**
  12235. * Returns null by default, used by the class Mesh.
  12236. * Returned type : integer array
  12237. */
  12238. AbstractMesh.prototype.getIndices = function () {
  12239. return null;
  12240. };
  12241. /**
  12242. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12243. * Returned type : float array or Float32Array
  12244. */
  12245. AbstractMesh.prototype.getVerticesData = function (kind) {
  12246. return null;
  12247. };
  12248. /** Returns false by default, used by the class Mesh.
  12249. * Returns a boolean
  12250. */
  12251. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12252. return false;
  12253. };
  12254. /**
  12255. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12256. * Returns a BoundingInfo
  12257. */
  12258. AbstractMesh.prototype.getBoundingInfo = function () {
  12259. if (this._masterMesh) {
  12260. return this._masterMesh.getBoundingInfo();
  12261. }
  12262. if (!this._boundingInfo) {
  12263. this._updateBoundingInfo();
  12264. }
  12265. return this._boundingInfo;
  12266. };
  12267. /**
  12268. * Sets a mesh new object BoundingInfo.
  12269. * Returns the AbstractMesh.
  12270. */
  12271. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12272. this._boundingInfo = boundingInfo;
  12273. return this;
  12274. };
  12275. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12276. get: function () {
  12277. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12278. },
  12279. enumerable: true,
  12280. configurable: true
  12281. });
  12282. AbstractMesh.prototype._preActivate = function () {
  12283. };
  12284. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12285. };
  12286. AbstractMesh.prototype._activate = function (renderId) {
  12287. this._renderId = renderId;
  12288. };
  12289. /**
  12290. * Returns the last update of the World matrix
  12291. * Returns a Matrix.
  12292. */
  12293. AbstractMesh.prototype.getWorldMatrix = function () {
  12294. if (this._masterMesh) {
  12295. return this._masterMesh.getWorldMatrix();
  12296. }
  12297. if (this._currentRenderId !== this.getScene().getRenderId()) {
  12298. this.computeWorldMatrix();
  12299. }
  12300. return this._worldMatrix;
  12301. };
  12302. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12303. /**
  12304. * Returns directly the last state of the mesh World matrix.
  12305. * A Matrix is returned.
  12306. */
  12307. get: function () {
  12308. return this._worldMatrix;
  12309. },
  12310. enumerable: true,
  12311. configurable: true
  12312. });
  12313. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12314. /**
  12315. * Returns the current mesh absolute position.
  12316. * Retuns a Vector3.
  12317. */
  12318. get: function () {
  12319. return this._absolutePosition;
  12320. },
  12321. enumerable: true,
  12322. configurable: true
  12323. });
  12324. /**
  12325. * Prevents the World matrix to be computed any longer.
  12326. * Returns the AbstractMesh.
  12327. */
  12328. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12329. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12330. this.computeWorldMatrix(true);
  12331. this._isWorldMatrixFrozen = true;
  12332. return this;
  12333. };
  12334. /**
  12335. * Allows back the World matrix computation.
  12336. * Returns the AbstractMesh.
  12337. */
  12338. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12339. this._isWorldMatrixFrozen = false;
  12340. this.computeWorldMatrix(true);
  12341. return this;
  12342. };
  12343. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12344. /**
  12345. * True if the World matrix has been frozen.
  12346. * Returns a boolean.
  12347. */
  12348. get: function () {
  12349. return this._isWorldMatrixFrozen;
  12350. },
  12351. enumerable: true,
  12352. configurable: true
  12353. });
  12354. /**
  12355. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12356. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12357. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12358. * The passed axis is also normalized.
  12359. * Returns the AbstractMesh.
  12360. */
  12361. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12362. axis.normalize();
  12363. if (!this.rotationQuaternion) {
  12364. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12365. this.rotation = BABYLON.Vector3.Zero();
  12366. }
  12367. var rotationQuaternion;
  12368. if (!space || space === BABYLON.Space.LOCAL) {
  12369. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12370. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12371. }
  12372. else {
  12373. if (this.parent) {
  12374. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12375. invertParentWorldMatrix.invert();
  12376. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12377. }
  12378. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12379. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12380. }
  12381. return this;
  12382. };
  12383. /**
  12384. * Translates the mesh along the axis vector for the passed distance in the given space.
  12385. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12386. * Returns the AbstractMesh.
  12387. */
  12388. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12389. var displacementVector = axis.scale(distance);
  12390. if (!space || space === BABYLON.Space.LOCAL) {
  12391. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12392. this.setPositionWithLocalVector(tempV3);
  12393. }
  12394. else {
  12395. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12396. }
  12397. return this;
  12398. };
  12399. /**
  12400. * Adds a rotation step to the mesh current rotation.
  12401. * x, y, z are Euler angles expressed in radians.
  12402. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12403. * This means this rotation is made in the mesh local space only.
  12404. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12405. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12406. * ```javascript
  12407. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12408. * ```
  12409. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12410. * 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.
  12411. * Returns the AbstractMesh.
  12412. */
  12413. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12414. var rotationQuaternion;
  12415. if (this.rotationQuaternion) {
  12416. rotationQuaternion = this.rotationQuaternion;
  12417. }
  12418. else {
  12419. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12420. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12421. }
  12422. var accumulation = BABYLON.Tmp.Quaternion[0];
  12423. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12424. rotationQuaternion.multiplyInPlace(accumulation);
  12425. if (!this.rotationQuaternion) {
  12426. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12427. }
  12428. return this;
  12429. };
  12430. /**
  12431. * Retuns the mesh absolute position in the World.
  12432. * Returns a Vector3.
  12433. */
  12434. AbstractMesh.prototype.getAbsolutePosition = function () {
  12435. this.computeWorldMatrix();
  12436. return this._absolutePosition;
  12437. };
  12438. /**
  12439. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12440. * Returns the AbstractMesh.
  12441. */
  12442. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12443. if (!absolutePosition) {
  12444. return;
  12445. }
  12446. var absolutePositionX;
  12447. var absolutePositionY;
  12448. var absolutePositionZ;
  12449. if (absolutePosition.x === undefined) {
  12450. if (arguments.length < 3) {
  12451. return;
  12452. }
  12453. absolutePositionX = arguments[0];
  12454. absolutePositionY = arguments[1];
  12455. absolutePositionZ = arguments[2];
  12456. }
  12457. else {
  12458. absolutePositionX = absolutePosition.x;
  12459. absolutePositionY = absolutePosition.y;
  12460. absolutePositionZ = absolutePosition.z;
  12461. }
  12462. if (this.parent) {
  12463. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12464. invertParentWorldMatrix.invert();
  12465. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12466. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12467. }
  12468. else {
  12469. this.position.x = absolutePositionX;
  12470. this.position.y = absolutePositionY;
  12471. this.position.z = absolutePositionZ;
  12472. }
  12473. return this;
  12474. };
  12475. // ================================== Point of View Movement =================================
  12476. /**
  12477. * Perform relative position change from the point of view of behind the front of the mesh.
  12478. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12479. * Supports definition of mesh facing forward or backward.
  12480. * @param {number} amountRight
  12481. * @param {number} amountUp
  12482. * @param {number} amountForward
  12483. *
  12484. * Returns the AbstractMesh.
  12485. */
  12486. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12487. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12488. return this;
  12489. };
  12490. /**
  12491. * Calculate relative position change from the point of view of behind the front of the mesh.
  12492. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12493. * Supports definition of mesh facing forward or backward.
  12494. * @param {number} amountRight
  12495. * @param {number} amountUp
  12496. * @param {number} amountForward
  12497. *
  12498. * Returns a new Vector3.
  12499. */
  12500. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12501. var rotMatrix = new BABYLON.Matrix();
  12502. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12503. rotQuaternion.toRotationMatrix(rotMatrix);
  12504. var translationDelta = BABYLON.Vector3.Zero();
  12505. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12506. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12507. return translationDelta;
  12508. };
  12509. // ================================== Point of View Rotation =================================
  12510. /**
  12511. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12512. * Supports definition of mesh facing forward or backward.
  12513. * @param {number} flipBack
  12514. * @param {number} twirlClockwise
  12515. * @param {number} tiltRight
  12516. *
  12517. * Returns the AbstractMesh.
  12518. */
  12519. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12520. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12521. return this;
  12522. };
  12523. /**
  12524. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12525. * Supports definition of mesh facing forward or backward.
  12526. * @param {number} flipBack
  12527. * @param {number} twirlClockwise
  12528. * @param {number} tiltRight
  12529. *
  12530. * Returns a new Vector3.
  12531. */
  12532. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12533. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12534. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12535. };
  12536. /**
  12537. * Sets a new pivot matrix to the mesh.
  12538. * Returns the AbstractMesh.
  12539. */
  12540. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12541. this._pivotMatrix = matrix;
  12542. this._cache.pivotMatrixUpdated = true;
  12543. return this;
  12544. };
  12545. /**
  12546. * Returns the mesh pivot matrix.
  12547. * Default : Identity.
  12548. * A Matrix is returned.
  12549. */
  12550. AbstractMesh.prototype.getPivotMatrix = function () {
  12551. return this._pivotMatrix;
  12552. };
  12553. AbstractMesh.prototype._isSynchronized = function () {
  12554. if (this._isDirty) {
  12555. return false;
  12556. }
  12557. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12558. return false;
  12559. if (this._cache.pivotMatrixUpdated) {
  12560. return false;
  12561. }
  12562. if (this.infiniteDistance) {
  12563. return false;
  12564. }
  12565. if (!this._cache.position.equals(this.position))
  12566. return false;
  12567. if (this.rotationQuaternion) {
  12568. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12569. return false;
  12570. }
  12571. if (!this._cache.rotation.equals(this.rotation))
  12572. return false;
  12573. if (!this._cache.scaling.equals(this.scaling))
  12574. return false;
  12575. return true;
  12576. };
  12577. AbstractMesh.prototype._initCache = function () {
  12578. _super.prototype._initCache.call(this);
  12579. this._cache.localMatrixUpdated = false;
  12580. this._cache.position = BABYLON.Vector3.Zero();
  12581. this._cache.scaling = BABYLON.Vector3.Zero();
  12582. this._cache.rotation = BABYLON.Vector3.Zero();
  12583. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12584. this._cache.billboardMode = -1;
  12585. };
  12586. AbstractMesh.prototype.markAsDirty = function (property) {
  12587. if (property === "rotation") {
  12588. this.rotationQuaternion = null;
  12589. }
  12590. this._currentRenderId = Number.MAX_VALUE;
  12591. this._isDirty = true;
  12592. return this;
  12593. };
  12594. /**
  12595. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12596. * Returns the AbstractMesh.
  12597. */
  12598. AbstractMesh.prototype._updateBoundingInfo = function () {
  12599. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12600. this._boundingInfo.update(this.worldMatrixFromCache);
  12601. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12602. return this;
  12603. };
  12604. /**
  12605. * Update a mesh's children BoundingInfo objects only.
  12606. * Returns the AbstractMesh.
  12607. */
  12608. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12609. if (!this.subMeshes) {
  12610. return;
  12611. }
  12612. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12613. var subMesh = this.subMeshes[subIndex];
  12614. if (!subMesh.IsGlobal) {
  12615. subMesh.updateBoundingInfo(matrix);
  12616. }
  12617. }
  12618. return this;
  12619. };
  12620. /**
  12621. * Computes the mesh World matrix and returns it.
  12622. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12623. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12624. * If the parameter `force`is set to `true`, the actual computation is done.
  12625. * Returns the mesh World Matrix.
  12626. */
  12627. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12628. if (this._isWorldMatrixFrozen) {
  12629. return this._worldMatrix;
  12630. }
  12631. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  12632. this._currentRenderId = this.getScene().getRenderId();
  12633. return this._worldMatrix;
  12634. }
  12635. this._cache.position.copyFrom(this.position);
  12636. this._cache.scaling.copyFrom(this.scaling);
  12637. this._cache.pivotMatrixUpdated = false;
  12638. this._cache.billboardMode = this.billboardMode;
  12639. this._currentRenderId = this.getScene().getRenderId();
  12640. this._isDirty = false;
  12641. // Scaling
  12642. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12643. // Rotation
  12644. //rotate, if quaternion is set and rotation was used
  12645. if (this.rotationQuaternion) {
  12646. var len = this.rotation.length();
  12647. if (len) {
  12648. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12649. this.rotation.copyFromFloats(0, 0, 0);
  12650. }
  12651. }
  12652. if (this.rotationQuaternion) {
  12653. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12654. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12655. }
  12656. else {
  12657. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12658. this._cache.rotation.copyFrom(this.rotation);
  12659. }
  12660. // Translation
  12661. if (this.infiniteDistance && !this.parent) {
  12662. var camera = this.getScene().activeCamera;
  12663. if (camera) {
  12664. var cameraWorldMatrix = camera.getWorldMatrix();
  12665. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12666. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12667. }
  12668. }
  12669. else {
  12670. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12671. }
  12672. // Composing transformations
  12673. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12674. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12675. // Mesh referal
  12676. var completeMeshReferalMatrix = BABYLON.Tmp.Matrix[6];
  12677. if (this._meshToBoneReferal && this.parent && this.parent.getWorldMatrix) {
  12678. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), completeMeshReferalMatrix);
  12679. }
  12680. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12681. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12682. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12683. // Need to decompose each rotation here
  12684. var currentPosition = BABYLON.Tmp.Vector3[3];
  12685. if (this.parent && this.parent.getWorldMatrix) {
  12686. if (this._meshToBoneReferal) {
  12687. BABYLON.Vector3.TransformCoordinatesToRef(this.position, completeMeshReferalMatrix, currentPosition);
  12688. }
  12689. else {
  12690. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12691. }
  12692. }
  12693. else {
  12694. currentPosition.copyFrom(this.position);
  12695. }
  12696. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12697. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12698. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12699. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12700. }
  12701. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12702. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12703. }
  12704. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12705. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12706. }
  12707. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12708. }
  12709. else {
  12710. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12711. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12712. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12713. }
  12714. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12715. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12716. }
  12717. // Local world
  12718. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12719. // Parent
  12720. if (this.parent && this.parent.getWorldMatrix) {
  12721. this._markSyncedWithParent();
  12722. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12723. if (this._meshToBoneReferal) {
  12724. BABYLON.Tmp.Matrix[5].copyFrom(completeMeshReferalMatrix);
  12725. }
  12726. else {
  12727. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12728. }
  12729. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12730. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12731. this._worldMatrix.copyFrom(this._localWorld);
  12732. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12733. }
  12734. else {
  12735. if (this._meshToBoneReferal) {
  12736. this._localWorld.multiplyToRef(completeMeshReferalMatrix, this._worldMatrix);
  12737. }
  12738. else {
  12739. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12740. }
  12741. }
  12742. }
  12743. else {
  12744. this._worldMatrix.copyFrom(this._localWorld);
  12745. }
  12746. // Bounding info
  12747. this._updateBoundingInfo();
  12748. // Absolute position
  12749. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12750. // Callbacks
  12751. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12752. if (!this._poseMatrix) {
  12753. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12754. }
  12755. return this._worldMatrix;
  12756. };
  12757. /**
  12758. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12759. * @param func: callback function to add
  12760. *
  12761. * Returns the AbstractMesh.
  12762. */
  12763. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12764. this.onAfterWorldMatrixUpdateObservable.add(func);
  12765. return this;
  12766. };
  12767. /**
  12768. * Removes a registered callback function.
  12769. * Returns the AbstractMesh.
  12770. */
  12771. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12772. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12773. return this;
  12774. };
  12775. /**
  12776. * Sets the mesh position in its local space.
  12777. * Returns the AbstractMesh.
  12778. */
  12779. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12780. this.computeWorldMatrix();
  12781. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12782. return this;
  12783. };
  12784. /**
  12785. * Returns the mesh position in the local space from the current World matrix values.
  12786. * Returns a new Vector3.
  12787. */
  12788. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12789. this.computeWorldMatrix();
  12790. var invLocalWorldMatrix = this._localWorld.clone();
  12791. invLocalWorldMatrix.invert();
  12792. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12793. };
  12794. /**
  12795. * Translates the mesh along the passed Vector3 in its local space.
  12796. * Returns the AbstractMesh.
  12797. */
  12798. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12799. this.computeWorldMatrix(true);
  12800. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12801. return this;
  12802. };
  12803. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12804. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12805. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12806. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12807. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12808. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12809. /// <returns>Mesh oriented towards targetMesh</returns>
  12810. if (yawCor === void 0) { yawCor = 0; }
  12811. if (pitchCor === void 0) { pitchCor = 0; }
  12812. if (rollCor === void 0) { rollCor = 0; }
  12813. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12814. var dv = AbstractMesh._lookAtVectorCache;
  12815. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12816. targetPoint.subtractToRef(pos, dv);
  12817. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12818. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12819. var pitch = Math.atan2(dv.y, len);
  12820. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12821. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12822. return this;
  12823. };
  12824. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12825. this._meshToBoneReferal = affectedMesh;
  12826. this.parent = bone;
  12827. if (bone.getWorldMatrix().determinant() < 0) {
  12828. this.scalingDeterminant *= -1;
  12829. }
  12830. return this;
  12831. };
  12832. AbstractMesh.prototype.detachFromBone = function () {
  12833. if (this.parent.getWorldMatrix().determinant() < 0) {
  12834. this.scalingDeterminant *= -1;
  12835. }
  12836. this._meshToBoneReferal = null;
  12837. this.parent = null;
  12838. return this;
  12839. };
  12840. /**
  12841. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12842. * A mesh is in the frustum if its bounding box intersects the frustum.
  12843. * Boolean returned.
  12844. */
  12845. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12846. return this._boundingInfo.isInFrustum(frustumPlanes);
  12847. };
  12848. /**
  12849. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12850. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12851. * Boolean returned.
  12852. */
  12853. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12854. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12855. ;
  12856. };
  12857. /**
  12858. * True if the mesh intersects another mesh or a SolidParticle object.
  12859. * 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)
  12860. * Returns a boolean.
  12861. */
  12862. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12863. if (!this._boundingInfo || !mesh._boundingInfo) {
  12864. return false;
  12865. }
  12866. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12867. };
  12868. /**
  12869. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12870. * Returns a boolean.
  12871. */
  12872. AbstractMesh.prototype.intersectsPoint = function (point) {
  12873. if (!this._boundingInfo) {
  12874. return false;
  12875. }
  12876. return this._boundingInfo.intersectsPoint(point);
  12877. };
  12878. // Physics
  12879. /**
  12880. * @Deprecated. Use new PhysicsImpostor instead.
  12881. * */
  12882. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  12883. //legacy support
  12884. if (impostor.impostor) {
  12885. options = impostor;
  12886. impostor = impostor.impostor;
  12887. }
  12888. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  12889. return this.physicsImpostor.physicsBody;
  12890. };
  12891. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12892. return this.physicsImpostor;
  12893. };
  12894. /**
  12895. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  12896. */
  12897. AbstractMesh.prototype.getPhysicsMass = function () {
  12898. return this.physicsImpostor.getParam("mass");
  12899. };
  12900. /**
  12901. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  12902. */
  12903. AbstractMesh.prototype.getPhysicsFriction = function () {
  12904. return this.physicsImpostor.getParam("friction");
  12905. };
  12906. /**
  12907. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  12908. */
  12909. AbstractMesh.prototype.getPhysicsRestitution = function () {
  12910. return this.physicsImpostor.getParam("restitution");
  12911. };
  12912. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12913. if (!camera) {
  12914. camera = this.getScene().activeCamera;
  12915. }
  12916. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12917. };
  12918. /**
  12919. * Returns the distance from the mesh to the active camera.
  12920. * Returns a float.
  12921. */
  12922. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12923. if (!camera) {
  12924. camera = this.getScene().activeCamera;
  12925. }
  12926. return this.absolutePosition.subtract(camera.position).length();
  12927. };
  12928. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12929. if (!this.physicsImpostor) {
  12930. return;
  12931. }
  12932. this.physicsImpostor.applyImpulse(force, contactPoint);
  12933. return this;
  12934. };
  12935. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12936. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12937. return;
  12938. }
  12939. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12940. mainPivot: pivot1,
  12941. connectedPivot: pivot2,
  12942. nativeParams: options
  12943. });
  12944. return this;
  12945. };
  12946. /**
  12947. * @Deprecated
  12948. */
  12949. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  12950. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  12951. this.updatePhysicsBody();
  12952. };
  12953. /**
  12954. * @Deprecated
  12955. * Calling this function is not needed anymore.
  12956. * The physics engine takes care of transofmration automatically.
  12957. */
  12958. AbstractMesh.prototype.updatePhysicsBody = function () {
  12959. //Unneeded
  12960. };
  12961. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12962. // Collisions
  12963. /**
  12964. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12965. * Default `false`.
  12966. */
  12967. get: function () {
  12968. return this._checkCollisions;
  12969. },
  12970. set: function (collisionEnabled) {
  12971. this._checkCollisions = collisionEnabled;
  12972. if (this.getScene().workerCollisions) {
  12973. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12974. }
  12975. },
  12976. enumerable: true,
  12977. configurable: true
  12978. });
  12979. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12980. var globalPosition = this.getAbsolutePosition();
  12981. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12982. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12983. this._collider.radius = this.ellipsoid;
  12984. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12985. return this;
  12986. };
  12987. // Submeshes octree
  12988. /**
  12989. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12990. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12991. * Returns an Octree of submeshes.
  12992. */
  12993. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12994. if (maxCapacity === void 0) { maxCapacity = 64; }
  12995. if (maxDepth === void 0) { maxDepth = 2; }
  12996. if (!this._submeshesOctree) {
  12997. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12998. }
  12999. this.computeWorldMatrix(true);
  13000. // Update octree
  13001. var bbox = this.getBoundingInfo().boundingBox;
  13002. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13003. return this._submeshesOctree;
  13004. };
  13005. // Collisions
  13006. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13007. this._generatePointsArray();
  13008. // Transformation
  13009. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13010. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13011. subMesh._lastColliderWorldVertices = [];
  13012. subMesh._trianglePlanes = [];
  13013. var start = subMesh.verticesStart;
  13014. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13015. for (var i = start; i < end; i++) {
  13016. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13017. }
  13018. }
  13019. // Collide
  13020. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13021. if (collider.collisionFound) {
  13022. collider.collidedMesh = this;
  13023. }
  13024. return this;
  13025. };
  13026. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13027. var subMeshes;
  13028. var len;
  13029. // Octrees
  13030. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13031. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13032. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13033. len = intersections.length;
  13034. subMeshes = intersections.data;
  13035. }
  13036. else {
  13037. subMeshes = this.subMeshes;
  13038. len = subMeshes.length;
  13039. }
  13040. for (var index = 0; index < len; index++) {
  13041. var subMesh = subMeshes[index];
  13042. // Bounding test
  13043. if (len > 1 && !subMesh._checkCollision(collider))
  13044. continue;
  13045. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13046. }
  13047. return this;
  13048. };
  13049. AbstractMesh.prototype._checkCollision = function (collider) {
  13050. // Bounding box test
  13051. if (!this._boundingInfo._checkCollision(collider))
  13052. return this;
  13053. // Transformation matrix
  13054. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13055. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13056. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13057. return this;
  13058. };
  13059. // Picking
  13060. AbstractMesh.prototype._generatePointsArray = function () {
  13061. return false;
  13062. };
  13063. /**
  13064. * Checks if the passed Ray intersects with the mesh.
  13065. * Returns an object PickingInfo.
  13066. */
  13067. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13068. var pickingInfo = new BABYLON.PickingInfo();
  13069. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13070. return pickingInfo;
  13071. }
  13072. if (!this._generatePointsArray()) {
  13073. return pickingInfo;
  13074. }
  13075. var intersectInfo = null;
  13076. // Octrees
  13077. var subMeshes;
  13078. var len;
  13079. if (this._submeshesOctree && this.useOctreeForPicking) {
  13080. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13081. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13082. len = intersections.length;
  13083. subMeshes = intersections.data;
  13084. }
  13085. else {
  13086. subMeshes = this.subMeshes;
  13087. len = subMeshes.length;
  13088. }
  13089. for (var index = 0; index < len; index++) {
  13090. var subMesh = subMeshes[index];
  13091. // Bounding test
  13092. if (len > 1 && !subMesh.canIntersects(ray))
  13093. continue;
  13094. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13095. if (currentIntersectInfo) {
  13096. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13097. intersectInfo = currentIntersectInfo;
  13098. intersectInfo.subMeshId = index;
  13099. if (fastCheck) {
  13100. break;
  13101. }
  13102. }
  13103. }
  13104. }
  13105. if (intersectInfo) {
  13106. // Get picked point
  13107. var world = this.getWorldMatrix();
  13108. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13109. var direction = ray.direction.clone();
  13110. direction = direction.scale(intersectInfo.distance);
  13111. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13112. var pickedPoint = worldOrigin.add(worldDirection);
  13113. // Return result
  13114. pickingInfo.hit = true;
  13115. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13116. pickingInfo.pickedPoint = pickedPoint;
  13117. pickingInfo.pickedMesh = this;
  13118. pickingInfo.bu = intersectInfo.bu;
  13119. pickingInfo.bv = intersectInfo.bv;
  13120. pickingInfo.faceId = intersectInfo.faceId;
  13121. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13122. return pickingInfo;
  13123. }
  13124. return pickingInfo;
  13125. };
  13126. /**
  13127. * Clones the mesh, used by the class Mesh.
  13128. * Just returns `null` for an AbstractMesh.
  13129. */
  13130. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13131. return null;
  13132. };
  13133. /**
  13134. * Disposes all the mesh submeshes.
  13135. * Returns the AbstractMesh.
  13136. */
  13137. AbstractMesh.prototype.releaseSubMeshes = function () {
  13138. if (this.subMeshes) {
  13139. while (this.subMeshes.length) {
  13140. this.subMeshes[0].dispose();
  13141. }
  13142. }
  13143. else {
  13144. this.subMeshes = new Array();
  13145. }
  13146. return this;
  13147. };
  13148. /**
  13149. * Disposes the AbstractMesh.
  13150. * Some internal references are kept for further use.
  13151. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13152. * Returns nothing.
  13153. */
  13154. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13155. var _this = this;
  13156. var index;
  13157. // Action manager
  13158. if (this.actionManager) {
  13159. this.actionManager.dispose();
  13160. this.actionManager = null;
  13161. }
  13162. // Skeleton
  13163. this.skeleton = null;
  13164. // Animations
  13165. this.getScene().stopAnimation(this);
  13166. // Physics
  13167. if (this.physicsImpostor) {
  13168. this.physicsImpostor.dispose();
  13169. }
  13170. // Intersections in progress
  13171. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13172. var other = this._intersectionsInProgress[index];
  13173. var pos = other._intersectionsInProgress.indexOf(this);
  13174. other._intersectionsInProgress.splice(pos, 1);
  13175. }
  13176. this._intersectionsInProgress = [];
  13177. // Lights
  13178. var lights = this.getScene().lights;
  13179. lights.forEach(function (light) {
  13180. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13181. if (meshIndex !== -1) {
  13182. light.includedOnlyMeshes.splice(meshIndex, 1);
  13183. }
  13184. meshIndex = light.excludedMeshes.indexOf(_this);
  13185. if (meshIndex !== -1) {
  13186. light.excludedMeshes.splice(meshIndex, 1);
  13187. }
  13188. // Shadow generators
  13189. var generator = light.getShadowGenerator();
  13190. if (generator) {
  13191. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  13192. if (meshIndex !== -1) {
  13193. generator.getShadowMap().renderList.splice(meshIndex, 1);
  13194. }
  13195. }
  13196. });
  13197. // Edges
  13198. if (this._edgesRenderer) {
  13199. this._edgesRenderer.dispose();
  13200. this._edgesRenderer = null;
  13201. }
  13202. // SubMeshes
  13203. if (this.getClassName() !== "InstancedMesh") {
  13204. this.releaseSubMeshes();
  13205. }
  13206. // Engine
  13207. this.getScene().getEngine().wipeCaches();
  13208. // Remove from scene
  13209. this.getScene().removeMesh(this);
  13210. if (!doNotRecurse) {
  13211. // Particles
  13212. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13213. if (this.getScene().particleSystems[index].emitter === this) {
  13214. this.getScene().particleSystems[index].dispose();
  13215. index--;
  13216. }
  13217. }
  13218. // Children
  13219. var objects = this.getDescendants(true);
  13220. for (index = 0; index < objects.length; index++) {
  13221. objects[index].dispose();
  13222. }
  13223. }
  13224. else {
  13225. var childMeshes = this.getChildMeshes(true);
  13226. for (index = 0; index < childMeshes.length; index++) {
  13227. var child = childMeshes[index];
  13228. child.parent = null;
  13229. child.computeWorldMatrix(true);
  13230. }
  13231. }
  13232. // facet data
  13233. if (this._facetDataEnabled) {
  13234. this.disableFacetData();
  13235. }
  13236. this.onAfterWorldMatrixUpdateObservable.clear();
  13237. this.onCollideObservable.clear();
  13238. this.onCollisionPositionChangeObservable.clear();
  13239. this._isDisposed = true;
  13240. _super.prototype.dispose.call(this);
  13241. };
  13242. /**
  13243. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13244. * This Vector3 is expressed in the World space.
  13245. */
  13246. AbstractMesh.prototype.getDirection = function (localAxis) {
  13247. var result = BABYLON.Vector3.Zero();
  13248. this.getDirectionToRef(localAxis, result);
  13249. return result;
  13250. };
  13251. /**
  13252. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13253. * localAxis is expressed in the mesh local space.
  13254. * result is computed in the Wordl space from the mesh World matrix.
  13255. * Returns the AbstractMesh.
  13256. */
  13257. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13258. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13259. return this;
  13260. };
  13261. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13262. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13263. if (this.getScene().getRenderId() == 0) {
  13264. this.computeWorldMatrix(true);
  13265. }
  13266. var wm = this.getWorldMatrix();
  13267. if (space == BABYLON.Space.WORLD) {
  13268. var tmat = BABYLON.Tmp.Matrix[0];
  13269. wm.invertToRef(tmat);
  13270. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13271. }
  13272. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13273. this._pivotMatrix.m[12] = -point.x;
  13274. this._pivotMatrix.m[13] = -point.y;
  13275. this._pivotMatrix.m[14] = -point.z;
  13276. this._cache.pivotMatrixUpdated = true;
  13277. return this;
  13278. };
  13279. /**
  13280. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13281. */
  13282. AbstractMesh.prototype.getPivotPoint = function () {
  13283. var point = BABYLON.Vector3.Zero();
  13284. this.getPivotPointToRef(point);
  13285. return point;
  13286. };
  13287. /**
  13288. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13289. * Returns the AbstractMesh.
  13290. */
  13291. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13292. result.x = -this._pivotMatrix.m[12];
  13293. result.y = -this._pivotMatrix.m[13];
  13294. result.z = -this._pivotMatrix.m[14];
  13295. return this;
  13296. };
  13297. /**
  13298. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13299. */
  13300. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13301. var point = BABYLON.Vector3.Zero();
  13302. this.getAbsolutePivotPointToRef(point);
  13303. return point;
  13304. };
  13305. /**
  13306. * Defines the passed mesh as the parent of the current mesh.
  13307. * If keepWorldPositionRotation is set to `true` (default `false`), the current mesh position and rotation are kept.
  13308. * Returns the AbstractMesh.
  13309. */
  13310. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  13311. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13312. var child = this;
  13313. var parent = mesh;
  13314. if (mesh == null) {
  13315. if (child.parent && keepWorldPositionRotation) {
  13316. var rotation = BABYLON.Tmp.Quaternion[0];
  13317. var position = BABYLON.Tmp.Vector3[0];
  13318. var scale = BABYLON.Tmp.Vector3[1];
  13319. child.getWorldMatrix().decompose(scale, rotation, position);
  13320. if (child.rotationQuaternion) {
  13321. child.rotationQuaternion.copyFrom(rotation);
  13322. }
  13323. else {
  13324. rotation.toEulerAnglesToRef(child.rotation);
  13325. }
  13326. child.position.x = position.x;
  13327. child.position.y = position.y;
  13328. child.position.z = position.z;
  13329. }
  13330. }
  13331. else {
  13332. if (keepWorldPositionRotation) {
  13333. var rotation = BABYLON.Tmp.Quaternion[0];
  13334. var position = BABYLON.Tmp.Vector3[0];
  13335. var scale = BABYLON.Tmp.Vector3[1];
  13336. var m1 = BABYLON.Tmp.Matrix[0];
  13337. var m2 = BABYLON.Tmp.Matrix[1];
  13338. parent.getWorldMatrix().decompose(scale, rotation, position);
  13339. rotation.toRotationMatrix(m1);
  13340. m2.setTranslation(position);
  13341. m2.multiplyToRef(m1, m1);
  13342. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13343. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13344. m.decompose(scale, rotation, position);
  13345. if (child.rotationQuaternion) {
  13346. child.rotationQuaternion.copyFrom(rotation);
  13347. }
  13348. else {
  13349. rotation.toEulerAnglesToRef(child.rotation);
  13350. }
  13351. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13352. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13353. m.decompose(scale, rotation, position);
  13354. child.position.x = position.x;
  13355. child.position.y = position.y;
  13356. child.position.z = position.z;
  13357. }
  13358. }
  13359. child.parent = parent;
  13360. return this;
  13361. };
  13362. /**
  13363. * Adds the passed mesh as a child to the current mesh.
  13364. * If keepWorldPositionRotation is set to `true` (default `false`), the child world position and rotation are kept.
  13365. * Returns the AbstractMesh.
  13366. */
  13367. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  13368. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13369. mesh.setParent(this, keepWorldPositionRotation);
  13370. return this;
  13371. };
  13372. /**
  13373. * Removes the passed mesh from the current mesh children list.
  13374. * Returns the AbstractMesh.
  13375. */
  13376. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  13377. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13378. mesh.setParent(null, keepWorldPositionRotation);
  13379. return this;
  13380. };
  13381. /**
  13382. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13383. * Returns the AbstractMesh.
  13384. */
  13385. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13386. result.x = this._pivotMatrix.m[12];
  13387. result.y = this._pivotMatrix.m[13];
  13388. result.z = this._pivotMatrix.m[14];
  13389. this.getPivotPointToRef(result);
  13390. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13391. return this;
  13392. };
  13393. // Facet data
  13394. /**
  13395. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13396. * Returns the AbstractMesh.
  13397. */
  13398. AbstractMesh.prototype._initFacetData = function () {
  13399. if (!this._facetNormals) {
  13400. this._facetNormals = new Array();
  13401. }
  13402. if (!this._facetPositions) {
  13403. this._facetPositions = new Array();
  13404. }
  13405. if (!this._facetPartitioning) {
  13406. this._facetPartitioning = new Array();
  13407. }
  13408. this._facetNb = this.getIndices().length / 3;
  13409. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13410. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13411. for (var f = 0; f < this._facetNb; f++) {
  13412. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13413. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13414. }
  13415. this._facetDataEnabled = true;
  13416. return this;
  13417. };
  13418. /**
  13419. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13420. * This method can be called within the render loop.
  13421. * 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.
  13422. * Returns the AbstractMesh.
  13423. */
  13424. AbstractMesh.prototype.updateFacetData = function () {
  13425. if (!this._facetDataEnabled) {
  13426. this._initFacetData();
  13427. }
  13428. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13429. var indices = this.getIndices();
  13430. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13431. var bInfo = this.getBoundingInfo();
  13432. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13433. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13434. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13435. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13436. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13437. this._subDiv.max = this._partitioningSubdivisions;
  13438. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13439. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13440. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13441. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13442. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13443. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13444. // set the parameters for ComputeNormals()
  13445. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13446. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13447. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13448. this._facetParameters.bInfo = bInfo;
  13449. this._facetParameters.bbSize = this._bbSize;
  13450. this._facetParameters.subDiv = this._subDiv;
  13451. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13452. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13453. return this;
  13454. };
  13455. /**
  13456. * Returns the facetLocalNormals array.
  13457. * The normals are expressed in the mesh local space.
  13458. */
  13459. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13460. if (!this._facetNormals) {
  13461. this.updateFacetData();
  13462. }
  13463. return this._facetNormals;
  13464. };
  13465. /**
  13466. * Returns the facetLocalPositions array.
  13467. * The facet positions are expressed in the mesh local space.
  13468. */
  13469. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13470. if (!this._facetPositions) {
  13471. this.updateFacetData();
  13472. }
  13473. return this._facetPositions;
  13474. };
  13475. /**
  13476. * Returns the facetLocalPartioning array.
  13477. */
  13478. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13479. if (!this._facetPartitioning) {
  13480. this.updateFacetData();
  13481. }
  13482. return this._facetPartitioning;
  13483. };
  13484. /**
  13485. * Returns the i-th facet position in the world system.
  13486. * This method allocates a new Vector3 per call.
  13487. */
  13488. AbstractMesh.prototype.getFacetPosition = function (i) {
  13489. var pos = BABYLON.Vector3.Zero();
  13490. this.getFacetPositionToRef(i, pos);
  13491. return pos;
  13492. };
  13493. /**
  13494. * Sets the reference Vector3 with the i-th facet position in the world system.
  13495. * Returns the AbstractMesh.
  13496. */
  13497. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13498. var localPos = (this.getFacetLocalPositions())[i];
  13499. var world = this.getWorldMatrix();
  13500. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13501. return this;
  13502. };
  13503. /**
  13504. * Returns the i-th facet normal in the world system.
  13505. * This method allocates a new Vector3 per call.
  13506. */
  13507. AbstractMesh.prototype.getFacetNormal = function (i) {
  13508. var norm = BABYLON.Vector3.Zero();
  13509. this.getFacetNormalToRef(i, norm);
  13510. return norm;
  13511. };
  13512. /**
  13513. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13514. * Returns the AbstractMesh.
  13515. */
  13516. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13517. var localNorm = (this.getFacetLocalNormals())[i];
  13518. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13519. return this;
  13520. };
  13521. /**
  13522. * 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).
  13523. */
  13524. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13525. var bInfo = this.getBoundingInfo();
  13526. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13527. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13528. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13529. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13530. return null;
  13531. }
  13532. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13533. };
  13534. /**
  13535. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13536. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13537. * 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.
  13538. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13539. * 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.
  13540. */
  13541. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13542. if (checkFace === void 0) { checkFace = false; }
  13543. if (facing === void 0) { facing = true; }
  13544. var world = this.getWorldMatrix();
  13545. var invMat = BABYLON.Tmp.Matrix[5];
  13546. world.invertToRef(invMat);
  13547. var invVect = BABYLON.Tmp.Vector3[8];
  13548. var closest = null;
  13549. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13550. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13551. if (projected) {
  13552. // tranform the local computed projected vector to world coordinates
  13553. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13554. }
  13555. return closest;
  13556. };
  13557. /**
  13558. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13559. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13560. * 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.
  13561. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13562. * 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.
  13563. */
  13564. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13565. if (checkFace === void 0) { checkFace = false; }
  13566. if (facing === void 0) { facing = true; }
  13567. var closest = null;
  13568. var tmpx = 0.0;
  13569. var tmpy = 0.0;
  13570. var tmpz = 0.0;
  13571. var d = 0.0; // tmp dot facet normal * facet position
  13572. var t0 = 0.0;
  13573. var projx = 0.0;
  13574. var projy = 0.0;
  13575. var projz = 0.0;
  13576. // Get all the facets in the same partitioning block than (x, y, z)
  13577. var facetPositions = this.getFacetLocalPositions();
  13578. var facetNormals = this.getFacetLocalNormals();
  13579. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13580. if (!facetsInBlock) {
  13581. return null;
  13582. }
  13583. // Get the closest facet to (x, y, z)
  13584. var shortest = Number.MAX_VALUE; // init distance vars
  13585. var tmpDistance = shortest;
  13586. var fib; // current facet in the block
  13587. var norm; // current facet normal
  13588. var p0; // current facet barycenter position
  13589. // loop on all the facets in the current partitioning block
  13590. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13591. fib = facetsInBlock[idx];
  13592. norm = facetNormals[fib];
  13593. p0 = facetPositions[fib];
  13594. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13595. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13596. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13597. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13598. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13599. projx = x + norm.x * t0;
  13600. projy = y + norm.y * t0;
  13601. projz = z + norm.z * t0;
  13602. tmpx = projx - x;
  13603. tmpy = projy - y;
  13604. tmpz = projz - z;
  13605. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13606. if (tmpDistance < shortest) {
  13607. shortest = tmpDistance;
  13608. closest = fib;
  13609. if (projected) {
  13610. projected.x = projx;
  13611. projected.y = projy;
  13612. projected.z = projz;
  13613. }
  13614. }
  13615. }
  13616. }
  13617. return closest;
  13618. };
  13619. /**
  13620. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13621. */
  13622. AbstractMesh.prototype.getFacetDataParameters = function () {
  13623. return this._facetParameters;
  13624. };
  13625. /**
  13626. * Disables the feature FacetData and frees the related memory.
  13627. * Returns the AbstractMesh.
  13628. */
  13629. AbstractMesh.prototype.disableFacetData = function () {
  13630. if (this._facetDataEnabled) {
  13631. this._facetDataEnabled = false;
  13632. this._facetPositions = null;
  13633. this._facetNormals = null;
  13634. this._facetPartitioning = null;
  13635. this._facetParameters = null;
  13636. }
  13637. return this;
  13638. };
  13639. return AbstractMesh;
  13640. }(BABYLON.Node));
  13641. // Statics
  13642. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13643. AbstractMesh._BILLBOARDMODE_X = 1;
  13644. AbstractMesh._BILLBOARDMODE_Y = 2;
  13645. AbstractMesh._BILLBOARDMODE_Z = 4;
  13646. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13647. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13648. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13649. BABYLON.AbstractMesh = AbstractMesh;
  13650. })(BABYLON || (BABYLON = {}));
  13651. //# sourceMappingURL=babylon.abstractMesh.js.map
  13652. var BABYLON;
  13653. (function (BABYLON) {
  13654. var Light = (function (_super) {
  13655. __extends(Light, _super);
  13656. /**
  13657. * Creates a Light object in the scene.
  13658. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13659. */
  13660. function Light(name, scene) {
  13661. var _this = _super.call(this, name, scene) || this;
  13662. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13663. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13664. _this.intensity = 1.0;
  13665. _this.range = Number.MAX_VALUE;
  13666. _this.includeOnlyWithLayerMask = 0;
  13667. _this.includedOnlyMeshes = new Array();
  13668. _this.excludedMeshes = new Array();
  13669. _this.excludeWithLayerMask = 0;
  13670. _this.lightmapMode = 0;
  13671. // PBR Properties.
  13672. _this.radius = 0.00001;
  13673. _this._excludedMeshesIds = new Array();
  13674. _this._includedOnlyMeshesIds = new Array();
  13675. _this.getScene().addLight(_this);
  13676. return _this;
  13677. }
  13678. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13679. /**
  13680. * If every light affecting the material is in this lightmapMode,
  13681. * material.lightmapTexture adds or multiplies
  13682. * (depends on material.useLightmapAsShadowmap)
  13683. * after every other light calculations.
  13684. */
  13685. get: function () {
  13686. return Light._LIGHTMAP_DEFAULT;
  13687. },
  13688. enumerable: true,
  13689. configurable: true
  13690. });
  13691. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13692. /**
  13693. * material.lightmapTexture as only diffuse lighting from this light
  13694. * adds pnly specular lighting from this light
  13695. * adds dynamic shadows
  13696. */
  13697. get: function () {
  13698. return Light._LIGHTMAP_SPECULAR;
  13699. },
  13700. enumerable: true,
  13701. configurable: true
  13702. });
  13703. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13704. /**
  13705. * material.lightmapTexture as only lighting
  13706. * no light calculation from this light
  13707. * only adds dynamic shadows from this light
  13708. */
  13709. get: function () {
  13710. return Light._LIGHTMAP_SHADOWSONLY;
  13711. },
  13712. enumerable: true,
  13713. configurable: true
  13714. });
  13715. /**
  13716. * Returns the string "Light".
  13717. */
  13718. Light.prototype.getClassName = function () {
  13719. return "Light";
  13720. };
  13721. /**
  13722. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13723. */
  13724. Light.prototype.toString = function (fullDetails) {
  13725. var ret = "Name: " + this.name;
  13726. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13727. if (this.animations) {
  13728. for (var i = 0; i < this.animations.length; i++) {
  13729. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13730. }
  13731. }
  13732. if (fullDetails) {
  13733. }
  13734. return ret;
  13735. };
  13736. /**
  13737. * Returns the Light associated shadow generator.
  13738. */
  13739. Light.prototype.getShadowGenerator = function () {
  13740. return this._shadowGenerator;
  13741. };
  13742. /**
  13743. * Returns a Vector3, the absolute light position in the World.
  13744. */
  13745. Light.prototype.getAbsolutePosition = function () {
  13746. return BABYLON.Vector3.Zero();
  13747. };
  13748. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  13749. };
  13750. Light.prototype._getWorldMatrix = function () {
  13751. return BABYLON.Matrix.Identity();
  13752. };
  13753. /**
  13754. * Boolean : True if the light will affect the passed mesh.
  13755. */
  13756. Light.prototype.canAffectMesh = function (mesh) {
  13757. if (!mesh) {
  13758. return true;
  13759. }
  13760. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13761. return false;
  13762. }
  13763. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13764. return false;
  13765. }
  13766. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13767. return false;
  13768. }
  13769. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13770. return false;
  13771. }
  13772. return true;
  13773. };
  13774. /**
  13775. * Returns the light World matrix.
  13776. */
  13777. Light.prototype.getWorldMatrix = function () {
  13778. this._currentRenderId = this.getScene().getRenderId();
  13779. var worldMatrix = this._getWorldMatrix();
  13780. if (this.parent && this.parent.getWorldMatrix) {
  13781. if (!this._parentedWorldMatrix) {
  13782. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13783. }
  13784. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13785. this._markSyncedWithParent();
  13786. return this._parentedWorldMatrix;
  13787. }
  13788. return worldMatrix;
  13789. };
  13790. /**
  13791. * Disposes the light.
  13792. */
  13793. Light.prototype.dispose = function () {
  13794. if (this._shadowGenerator) {
  13795. this._shadowGenerator.dispose();
  13796. this._shadowGenerator = null;
  13797. }
  13798. // Animations
  13799. this.getScene().stopAnimation(this);
  13800. // Remove from scene
  13801. this.getScene().removeLight(this);
  13802. _super.prototype.dispose.call(this);
  13803. };
  13804. /**
  13805. * Returns the light type ID (integer).
  13806. */
  13807. Light.prototype.getTypeID = function () {
  13808. return 0;
  13809. };
  13810. /**
  13811. * Returns a new Light object, named "name", from the current one.
  13812. */
  13813. Light.prototype.clone = function (name) {
  13814. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13815. };
  13816. /**
  13817. * Serializes the current light into a Serialization object.
  13818. * Returns the serialized object.
  13819. */
  13820. Light.prototype.serialize = function () {
  13821. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13822. // Type
  13823. serializationObject.type = this.getTypeID();
  13824. // Parent
  13825. if (this.parent) {
  13826. serializationObject.parentId = this.parent.id;
  13827. }
  13828. // Inclusion / exclusions
  13829. if (this.excludedMeshes.length > 0) {
  13830. serializationObject.excludedMeshesIds = [];
  13831. this.excludedMeshes.forEach(function (mesh) {
  13832. serializationObject.excludedMeshesIds.push(mesh.id);
  13833. });
  13834. }
  13835. if (this.includedOnlyMeshes.length > 0) {
  13836. serializationObject.includedOnlyMeshesIds = [];
  13837. this.includedOnlyMeshes.forEach(function (mesh) {
  13838. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13839. });
  13840. }
  13841. // Animations
  13842. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13843. serializationObject.ranges = this.serializeAnimationRanges();
  13844. return serializationObject;
  13845. };
  13846. /**
  13847. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13848. * This new light is named "name" and added to the passed scene.
  13849. */
  13850. Light.GetConstructorFromName = function (type, name, scene) {
  13851. switch (type) {
  13852. case 0:
  13853. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13854. case 1:
  13855. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13856. case 2:
  13857. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13858. case 3:
  13859. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13860. }
  13861. };
  13862. /**
  13863. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13864. */
  13865. Light.Parse = function (parsedLight, scene) {
  13866. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13867. // Inclusion / exclusions
  13868. if (parsedLight.excludedMeshesIds) {
  13869. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13870. }
  13871. if (parsedLight.includedOnlyMeshesIds) {
  13872. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13873. }
  13874. // Parent
  13875. if (parsedLight.parentId) {
  13876. light._waitingParentId = parsedLight.parentId;
  13877. }
  13878. // Animations
  13879. if (parsedLight.animations) {
  13880. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13881. var parsedAnimation = parsedLight.animations[animationIndex];
  13882. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13883. }
  13884. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13885. }
  13886. if (parsedLight.autoAnimate) {
  13887. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13888. }
  13889. return light;
  13890. };
  13891. return Light;
  13892. }(BABYLON.Node));
  13893. //lightmapMode Consts
  13894. Light._LIGHTMAP_DEFAULT = 0;
  13895. Light._LIGHTMAP_SPECULAR = 1;
  13896. Light._LIGHTMAP_SHADOWSONLY = 2;
  13897. __decorate([
  13898. BABYLON.serializeAsColor3()
  13899. ], Light.prototype, "diffuse", void 0);
  13900. __decorate([
  13901. BABYLON.serializeAsColor3()
  13902. ], Light.prototype, "specular", void 0);
  13903. __decorate([
  13904. BABYLON.serialize()
  13905. ], Light.prototype, "intensity", void 0);
  13906. __decorate([
  13907. BABYLON.serialize()
  13908. ], Light.prototype, "range", void 0);
  13909. __decorate([
  13910. BABYLON.serialize()
  13911. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  13912. __decorate([
  13913. BABYLON.serialize()
  13914. ], Light.prototype, "excludeWithLayerMask", void 0);
  13915. __decorate([
  13916. BABYLON.serialize()
  13917. ], Light.prototype, "lightmapMode", void 0);
  13918. __decorate([
  13919. BABYLON.serialize()
  13920. ], Light.prototype, "radius", void 0);
  13921. BABYLON.Light = Light;
  13922. })(BABYLON || (BABYLON = {}));
  13923. //# sourceMappingURL=babylon.light.js.map
  13924. var BABYLON;
  13925. (function (BABYLON) {
  13926. var PointLight = (function (_super) {
  13927. __extends(PointLight, _super);
  13928. /**
  13929. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  13930. * A PointLight emits the light in every direction.
  13931. * It can cast shadows.
  13932. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  13933. * ```javascript
  13934. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  13935. * ```
  13936. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13937. */
  13938. function PointLight(name, position, scene) {
  13939. var _this = _super.call(this, name, scene) || this;
  13940. _this.position = position;
  13941. return _this;
  13942. }
  13943. /**
  13944. * Returns the string "PointLight"
  13945. */
  13946. PointLight.prototype.getClassName = function () {
  13947. return "PointLight";
  13948. };
  13949. /**
  13950. * Returns a Vector3, the PointLight absolute position in the World.
  13951. */
  13952. PointLight.prototype.getAbsolutePosition = function () {
  13953. return this.transformedPosition ? this.transformedPosition : this.position;
  13954. };
  13955. /**
  13956. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  13957. */
  13958. PointLight.prototype.computeTransformedPosition = function () {
  13959. if (this.parent && this.parent.getWorldMatrix) {
  13960. if (!this.transformedPosition) {
  13961. this.transformedPosition = BABYLON.Vector3.Zero();
  13962. }
  13963. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  13964. return true;
  13965. }
  13966. return false;
  13967. };
  13968. /**
  13969. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  13970. * Returns the PointLight.
  13971. */
  13972. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  13973. if (this.parent && this.parent.getWorldMatrix) {
  13974. this.computeTransformedPosition();
  13975. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0);
  13976. return this;
  13977. }
  13978. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  13979. return this;
  13980. };
  13981. /**
  13982. * Boolean : returns true by default.
  13983. */
  13984. PointLight.prototype.needCube = function () {
  13985. return true;
  13986. };
  13987. /**
  13988. * Boolean : returns false by default.
  13989. */
  13990. PointLight.prototype.supportsVSM = function () {
  13991. return false;
  13992. };
  13993. /**
  13994. * Boolean : returns false by default.
  13995. */
  13996. PointLight.prototype.needRefreshPerFrame = function () {
  13997. return false;
  13998. };
  13999. /**
  14000. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  14001. */
  14002. PointLight.prototype.getShadowDirection = function (faceIndex) {
  14003. switch (faceIndex) {
  14004. case 0:
  14005. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  14006. case 1:
  14007. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  14008. case 2:
  14009. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  14010. case 3:
  14011. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  14012. case 4:
  14013. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  14014. case 5:
  14015. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  14016. }
  14017. return BABYLON.Vector3.Zero();
  14018. };
  14019. /**
  14020. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  14021. * - fov = PI / 2
  14022. * - aspect ratio : 1.0
  14023. * - z-near and far equal to the active camera minZ and maxZ.
  14024. * Returns the PointLight.
  14025. */
  14026. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14027. var activeCamera = this.getScene().activeCamera;
  14028. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  14029. return this;
  14030. };
  14031. PointLight.prototype._getWorldMatrix = function () {
  14032. if (!this._worldMatrix) {
  14033. this._worldMatrix = BABYLON.Matrix.Identity();
  14034. }
  14035. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14036. return this._worldMatrix;
  14037. };
  14038. /**
  14039. * Returns the integer 0.
  14040. */
  14041. PointLight.prototype.getTypeID = function () {
  14042. return 0;
  14043. };
  14044. return PointLight;
  14045. }(BABYLON.Light));
  14046. __decorate([
  14047. BABYLON.serializeAsVector3()
  14048. ], PointLight.prototype, "position", void 0);
  14049. BABYLON.PointLight = PointLight;
  14050. })(BABYLON || (BABYLON = {}));
  14051. //# sourceMappingURL=babylon.pointLight.js.map
  14052. var BABYLON;
  14053. (function (BABYLON) {
  14054. var SpotLight = (function (_super) {
  14055. __extends(SpotLight, _super);
  14056. /**
  14057. * Creates a SpotLight object in the scene with the passed parameters :
  14058. * - `position` (Vector3) is the initial SpotLight position,
  14059. * - `direction` (Vector3) is the initial SpotLight direction,
  14060. * - `angle` (float, in radians) is the spot light cone angle,
  14061. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  14062. * A spot light is a simply light oriented cone.
  14063. * It can cast shadows.
  14064. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14065. */
  14066. function SpotLight(name, position, direction, angle, exponent, scene) {
  14067. var _this = _super.call(this, name, scene) || this;
  14068. _this.position = position;
  14069. _this.direction = direction;
  14070. _this.angle = angle;
  14071. _this.exponent = exponent;
  14072. return _this;
  14073. }
  14074. /**
  14075. * Returns the string "SpotLight".
  14076. */
  14077. SpotLight.prototype.getClassName = function () {
  14078. return "SpotLight";
  14079. };
  14080. /**
  14081. * Returns the SpotLight absolute position in the World (Vector3).
  14082. */
  14083. SpotLight.prototype.getAbsolutePosition = function () {
  14084. return this.transformedPosition ? this.transformedPosition : this.position;
  14085. };
  14086. /**
  14087. * 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.
  14088. * Returns the SpotLight.
  14089. */
  14090. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14091. var activeCamera = this.getScene().activeCamera;
  14092. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  14093. return this;
  14094. };
  14095. /**
  14096. * Boolean : false by default.
  14097. */
  14098. SpotLight.prototype.needCube = function () {
  14099. return false;
  14100. };
  14101. /**
  14102. * Boolean : true by default.
  14103. */
  14104. SpotLight.prototype.supportsVSM = function () {
  14105. return true;
  14106. };
  14107. /**
  14108. * Boolean : false by default.
  14109. */
  14110. SpotLight.prototype.needRefreshPerFrame = function () {
  14111. return false;
  14112. };
  14113. /**
  14114. * Returns the SpotLight direction (Vector3) for any passed face index.
  14115. */
  14116. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  14117. return this.direction;
  14118. };
  14119. /**
  14120. * Updates the SpotLight direction towards the passed target (Vector3).
  14121. * Returns the updated direction.
  14122. */
  14123. SpotLight.prototype.setDirectionToTarget = function (target) {
  14124. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14125. return this.direction;
  14126. };
  14127. /**
  14128. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  14129. */
  14130. SpotLight.prototype.computeTransformedPosition = function () {
  14131. if (this.parent && this.parent.getWorldMatrix) {
  14132. if (!this.transformedPosition) {
  14133. this.transformedPosition = BABYLON.Vector3.Zero();
  14134. }
  14135. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14136. return true;
  14137. }
  14138. return false;
  14139. };
  14140. /**
  14141. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  14142. * Return the SpotLight.
  14143. */
  14144. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  14145. var normalizeDirection;
  14146. if (this.parent && this.parent.getWorldMatrix) {
  14147. if (!this._transformedDirection) {
  14148. this._transformedDirection = BABYLON.Vector3.Zero();
  14149. }
  14150. this.computeTransformedPosition();
  14151. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14152. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  14153. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  14154. }
  14155. else {
  14156. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  14157. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14158. }
  14159. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  14160. return this;
  14161. };
  14162. SpotLight.prototype._getWorldMatrix = function () {
  14163. if (!this._worldMatrix) {
  14164. this._worldMatrix = BABYLON.Matrix.Identity();
  14165. }
  14166. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14167. return this._worldMatrix;
  14168. };
  14169. /**
  14170. * Returns the integer 2.
  14171. */
  14172. SpotLight.prototype.getTypeID = function () {
  14173. return 2;
  14174. };
  14175. /**
  14176. * Returns the SpotLight rotation (Vector3).
  14177. */
  14178. SpotLight.prototype.getRotation = function () {
  14179. this.direction.normalize();
  14180. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  14181. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  14182. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  14183. };
  14184. return SpotLight;
  14185. }(BABYLON.Light));
  14186. __decorate([
  14187. BABYLON.serializeAsVector3()
  14188. ], SpotLight.prototype, "position", void 0);
  14189. __decorate([
  14190. BABYLON.serializeAsVector3()
  14191. ], SpotLight.prototype, "direction", void 0);
  14192. __decorate([
  14193. BABYLON.serialize()
  14194. ], SpotLight.prototype, "angle", void 0);
  14195. __decorate([
  14196. BABYLON.serialize()
  14197. ], SpotLight.prototype, "exponent", void 0);
  14198. BABYLON.SpotLight = SpotLight;
  14199. })(BABYLON || (BABYLON = {}));
  14200. //# sourceMappingURL=babylon.spotLight.js.map
  14201. var BABYLON;
  14202. (function (BABYLON) {
  14203. var HemisphericLight = (function (_super) {
  14204. __extends(HemisphericLight, _super);
  14205. /**
  14206. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  14207. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  14208. * The HemisphericLight can't cast shadows.
  14209. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14210. */
  14211. function HemisphericLight(name, direction, scene) {
  14212. var _this = _super.call(this, name, scene) || this;
  14213. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  14214. _this.direction = direction;
  14215. return _this;
  14216. }
  14217. /**
  14218. * Returns the string "HemisphericLight".
  14219. */
  14220. HemisphericLight.prototype.getClassName = function () {
  14221. return "HemisphericLight";
  14222. };
  14223. /**
  14224. * Sets the HemisphericLight direction towards the passed target (Vector3).
  14225. * Returns the updated direction.
  14226. */
  14227. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  14228. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  14229. return this.direction;
  14230. };
  14231. HemisphericLight.prototype.getShadowGenerator = function () {
  14232. return null;
  14233. };
  14234. /**
  14235. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  14236. * Returns the HemisphericLight.
  14237. */
  14238. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  14239. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14240. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0);
  14241. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  14242. return this;
  14243. };
  14244. HemisphericLight.prototype._getWorldMatrix = function () {
  14245. if (!this._worldMatrix) {
  14246. this._worldMatrix = BABYLON.Matrix.Identity();
  14247. }
  14248. return this._worldMatrix;
  14249. };
  14250. /**
  14251. * Returns the integer 3.
  14252. */
  14253. HemisphericLight.prototype.getTypeID = function () {
  14254. return 3;
  14255. };
  14256. return HemisphericLight;
  14257. }(BABYLON.Light));
  14258. __decorate([
  14259. BABYLON.serializeAsColor3()
  14260. ], HemisphericLight.prototype, "groundColor", void 0);
  14261. __decorate([
  14262. BABYLON.serializeAsVector3()
  14263. ], HemisphericLight.prototype, "direction", void 0);
  14264. BABYLON.HemisphericLight = HemisphericLight;
  14265. })(BABYLON || (BABYLON = {}));
  14266. //# sourceMappingURL=babylon.hemisphericLight.js.map
  14267. /// <reference path="babylon.light.ts" />
  14268. var BABYLON;
  14269. (function (BABYLON) {
  14270. var DirectionalLight = (function (_super) {
  14271. __extends(DirectionalLight, _super);
  14272. /**
  14273. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  14274. * The directional light is emitted from everywhere in the given direction.
  14275. * It can cast shawdows.
  14276. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14277. */
  14278. function DirectionalLight(name, direction, scene) {
  14279. var _this = _super.call(this, name, scene) || this;
  14280. _this.shadowOrthoScale = 0.5;
  14281. _this.autoUpdateExtends = true;
  14282. // Cache
  14283. _this._orthoLeft = Number.MAX_VALUE;
  14284. _this._orthoRight = Number.MIN_VALUE;
  14285. _this._orthoTop = Number.MIN_VALUE;
  14286. _this._orthoBottom = Number.MAX_VALUE;
  14287. _this.position = direction.scale(-1.0);
  14288. _this.direction = direction;
  14289. return _this;
  14290. }
  14291. /**
  14292. * Returns the string "DirectionalLight".
  14293. */
  14294. DirectionalLight.prototype.getClassName = function () {
  14295. return "DirectionalLight";
  14296. };
  14297. /**
  14298. * Returns the DirectionalLight absolute position in the World.
  14299. */
  14300. DirectionalLight.prototype.getAbsolutePosition = function () {
  14301. return this.transformedPosition ? this.transformedPosition : this.position;
  14302. };
  14303. /**
  14304. * Sets the DirectionalLight direction toward the passed target (Vector3).
  14305. * Returns the updated DirectionalLight direction (Vector3).
  14306. */
  14307. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  14308. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14309. return this.direction;
  14310. };
  14311. /**
  14312. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  14313. * Returns the DirectionalLight.
  14314. */
  14315. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14316. var activeCamera = this.getScene().activeCamera;
  14317. // Check extends
  14318. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  14319. var tempVector3 = BABYLON.Vector3.Zero();
  14320. this._orthoLeft = Number.MAX_VALUE;
  14321. this._orthoRight = Number.MIN_VALUE;
  14322. this._orthoTop = Number.MIN_VALUE;
  14323. this._orthoBottom = Number.MAX_VALUE;
  14324. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  14325. var mesh = renderList[meshIndex];
  14326. if (!mesh) {
  14327. continue;
  14328. }
  14329. var boundingInfo = mesh.getBoundingInfo();
  14330. if (!boundingInfo) {
  14331. continue;
  14332. }
  14333. var boundingBox = boundingInfo.boundingBox;
  14334. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  14335. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  14336. if (tempVector3.x < this._orthoLeft)
  14337. this._orthoLeft = tempVector3.x;
  14338. if (tempVector3.y < this._orthoBottom)
  14339. this._orthoBottom = tempVector3.y;
  14340. if (tempVector3.x > this._orthoRight)
  14341. this._orthoRight = tempVector3.x;
  14342. if (tempVector3.y > this._orthoTop)
  14343. this._orthoTop = tempVector3.y;
  14344. }
  14345. }
  14346. }
  14347. var xOffset = this._orthoRight - this._orthoLeft;
  14348. var yOffset = this._orthoTop - this._orthoBottom;
  14349. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  14350. return this;
  14351. };
  14352. /**
  14353. * Boolean : true by default.
  14354. */
  14355. DirectionalLight.prototype.supportsVSM = function () {
  14356. return true;
  14357. };
  14358. /**
  14359. * Boolean : true by default.
  14360. */
  14361. DirectionalLight.prototype.needRefreshPerFrame = function () {
  14362. return true;
  14363. };
  14364. /**
  14365. * Boolean : false by default.
  14366. */
  14367. DirectionalLight.prototype.needCube = function () {
  14368. return false;
  14369. };
  14370. /**
  14371. * Returns the light direction (Vector3) for any passed face index.
  14372. */
  14373. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  14374. return this.direction;
  14375. };
  14376. /**
  14377. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  14378. */
  14379. DirectionalLight.prototype.computeTransformedPosition = function () {
  14380. if (this.parent && this.parent.getWorldMatrix) {
  14381. if (!this.transformedPosition) {
  14382. this.transformedPosition = BABYLON.Vector3.Zero();
  14383. }
  14384. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14385. return true;
  14386. }
  14387. return false;
  14388. };
  14389. /**
  14390. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  14391. * Returns the DirectionalLight.
  14392. */
  14393. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  14394. if (this.parent && this.parent.getWorldMatrix) {
  14395. if (!this._transformedDirection) {
  14396. this._transformedDirection = BABYLON.Vector3.Zero();
  14397. }
  14398. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14399. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  14400. return this;
  14401. }
  14402. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  14403. return this;
  14404. };
  14405. DirectionalLight.prototype._getWorldMatrix = function () {
  14406. if (!this._worldMatrix) {
  14407. this._worldMatrix = BABYLON.Matrix.Identity();
  14408. }
  14409. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14410. return this._worldMatrix;
  14411. };
  14412. /**
  14413. * Returns the integer 1.
  14414. */
  14415. DirectionalLight.prototype.getTypeID = function () {
  14416. return 1;
  14417. };
  14418. return DirectionalLight;
  14419. }(BABYLON.Light));
  14420. __decorate([
  14421. BABYLON.serializeAsVector3()
  14422. ], DirectionalLight.prototype, "position", void 0);
  14423. __decorate([
  14424. BABYLON.serializeAsVector3()
  14425. ], DirectionalLight.prototype, "direction", void 0);
  14426. __decorate([
  14427. BABYLON.serialize()
  14428. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  14429. __decorate([
  14430. BABYLON.serialize()
  14431. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  14432. BABYLON.DirectionalLight = DirectionalLight;
  14433. })(BABYLON || (BABYLON = {}));
  14434. //# sourceMappingURL=babylon.directionalLight.js.map
  14435. var BABYLON;
  14436. (function (BABYLON) {
  14437. var ShadowGenerator = (function () {
  14438. /**
  14439. * Creates a ShadowGenerator object.
  14440. * A ShadowGenerator is the required tool to use the shadows.
  14441. * Each light casting shadows needs to use its own ShadowGenerator.
  14442. * Required parameters :
  14443. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  14444. * - `light` : the light object generating the shadows.
  14445. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  14446. */
  14447. function ShadowGenerator(mapSize, light) {
  14448. var _this = this;
  14449. // Members
  14450. this._filter = ShadowGenerator.FILTER_NONE;
  14451. this.blurScale = 2;
  14452. this._blurBoxOffset = 0;
  14453. this._bias = 0.00005;
  14454. this._lightDirection = BABYLON.Vector3.Zero();
  14455. this.forceBackFacesOnly = false;
  14456. this._darkness = 0;
  14457. this._transparencyShadow = false;
  14458. this._viewMatrix = BABYLON.Matrix.Zero();
  14459. this._projectionMatrix = BABYLON.Matrix.Zero();
  14460. this._transformMatrix = BABYLON.Matrix.Zero();
  14461. this._worldViewProjection = BABYLON.Matrix.Zero();
  14462. this._currentFaceIndex = 0;
  14463. this._currentFaceIndexCache = 0;
  14464. this._useFullFloat = true;
  14465. this._light = light;
  14466. this._scene = light.getScene();
  14467. this._mapSize = mapSize;
  14468. light._shadowGenerator = this;
  14469. // Texture type fallback from float to int if not supported.
  14470. var textureType;
  14471. var caps = this._scene.getEngine().getCaps();
  14472. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  14473. this._useFullFloat = true;
  14474. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  14475. }
  14476. else {
  14477. this._useFullFloat = false;
  14478. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  14479. }
  14480. // Render target
  14481. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  14482. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14483. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14484. this._shadowMap.anisotropicFilteringLevel = 1;
  14485. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  14486. this._shadowMap.renderParticles = false;
  14487. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  14488. _this._currentFaceIndex = faceIndex;
  14489. });
  14490. this._shadowMap.onAfterUnbindObservable.add(function () {
  14491. if (!_this.useBlurVarianceShadowMap) {
  14492. return;
  14493. }
  14494. if (!_this._shadowMap2) {
  14495. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  14496. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14497. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14498. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  14499. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  14500. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  14501. effect.setTexture("textureSampler", _this._shadowMap);
  14502. });
  14503. _this.blurBoxOffset = 1;
  14504. }
  14505. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  14506. });
  14507. // Custom render function
  14508. var renderSubMesh = function (subMesh) {
  14509. var mesh = subMesh.getRenderingMesh();
  14510. var scene = _this._scene;
  14511. var engine = scene.getEngine();
  14512. // Culling
  14513. engine.setState(subMesh.getMaterial().backFaceCulling);
  14514. // Managing instances
  14515. var batch = mesh._getInstancesRenderList(subMesh._id);
  14516. if (batch.mustReturn) {
  14517. return;
  14518. }
  14519. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14520. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  14521. engine.enableEffect(_this._effect);
  14522. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  14523. var material = subMesh.getMaterial();
  14524. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  14525. _this._effect.setVector3("lightPosition", _this.getLight().position);
  14526. if (_this.getLight().needCube()) {
  14527. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  14528. }
  14529. // Alpha test
  14530. if (material && material.needAlphaTesting()) {
  14531. var alphaTexture = material.getAlphaTestTexture();
  14532. _this._effect.setTexture("diffuseSampler", alphaTexture);
  14533. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  14534. }
  14535. // Bones
  14536. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  14537. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  14538. }
  14539. if (_this.forceBackFacesOnly) {
  14540. engine.setState(true, 0, false, true);
  14541. }
  14542. // Draw
  14543. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  14544. if (_this.forceBackFacesOnly) {
  14545. engine.setState(true, 0, false, false);
  14546. }
  14547. }
  14548. else {
  14549. // Need to reset refresh rate of the shadowMap
  14550. _this._shadowMap.resetRefreshCounter();
  14551. }
  14552. };
  14553. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  14554. var index;
  14555. for (index = 0; index < opaqueSubMeshes.length; index++) {
  14556. renderSubMesh(opaqueSubMeshes.data[index]);
  14557. }
  14558. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  14559. renderSubMesh(alphaTestSubMeshes.data[index]);
  14560. }
  14561. if (_this._transparencyShadow) {
  14562. for (index = 0; index < transparentSubMeshes.length; index++) {
  14563. renderSubMesh(transparentSubMeshes.data[index]);
  14564. }
  14565. }
  14566. };
  14567. this._shadowMap.onClearObservable.add(function (engine) {
  14568. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  14569. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  14570. }
  14571. else {
  14572. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  14573. }
  14574. });
  14575. }
  14576. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  14577. // Static
  14578. get: function () {
  14579. return ShadowGenerator._FILTER_NONE;
  14580. },
  14581. enumerable: true,
  14582. configurable: true
  14583. });
  14584. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  14585. get: function () {
  14586. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  14587. },
  14588. enumerable: true,
  14589. configurable: true
  14590. });
  14591. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  14592. get: function () {
  14593. return ShadowGenerator._FILTER_POISSONSAMPLING;
  14594. },
  14595. enumerable: true,
  14596. configurable: true
  14597. });
  14598. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  14599. get: function () {
  14600. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  14601. },
  14602. enumerable: true,
  14603. configurable: true
  14604. });
  14605. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  14606. get: function () {
  14607. return this._bias;
  14608. },
  14609. set: function (bias) {
  14610. this._bias = bias;
  14611. },
  14612. enumerable: true,
  14613. configurable: true
  14614. });
  14615. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  14616. get: function () {
  14617. return this._blurBoxOffset;
  14618. },
  14619. set: function (value) {
  14620. var _this = this;
  14621. if (this._blurBoxOffset === value) {
  14622. return;
  14623. }
  14624. this._blurBoxOffset = value;
  14625. if (this._boxBlurPostprocess) {
  14626. this._boxBlurPostprocess.dispose();
  14627. }
  14628. 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);
  14629. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  14630. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  14631. });
  14632. },
  14633. enumerable: true,
  14634. configurable: true
  14635. });
  14636. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  14637. get: function () {
  14638. return this._filter;
  14639. },
  14640. set: function (value) {
  14641. if (this._filter === value) {
  14642. return;
  14643. }
  14644. this._filter = value;
  14645. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  14646. this._shadowMap.anisotropicFilteringLevel = 16;
  14647. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  14648. }
  14649. else {
  14650. this._shadowMap.anisotropicFilteringLevel = 1;
  14651. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  14652. }
  14653. },
  14654. enumerable: true,
  14655. configurable: true
  14656. });
  14657. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  14658. get: function () {
  14659. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  14660. },
  14661. set: function (value) {
  14662. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  14663. },
  14664. enumerable: true,
  14665. configurable: true
  14666. });
  14667. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  14668. get: function () {
  14669. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  14670. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  14671. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  14672. },
  14673. set: function (value) {
  14674. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  14675. },
  14676. enumerable: true,
  14677. configurable: true
  14678. });
  14679. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  14680. get: function () {
  14681. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  14682. },
  14683. set: function (value) {
  14684. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  14685. },
  14686. enumerable: true,
  14687. configurable: true
  14688. });
  14689. /**
  14690. * Boolean : true when the ShadowGenerator is finally computed.
  14691. */
  14692. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  14693. var defines = [];
  14694. if (this._useFullFloat) {
  14695. defines.push("#define FULLFLOAT");
  14696. }
  14697. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  14698. defines.push("#define VSM");
  14699. }
  14700. if (this.getLight().needCube()) {
  14701. defines.push("#define CUBEMAP");
  14702. }
  14703. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14704. var mesh = subMesh.getMesh();
  14705. var material = subMesh.getMaterial();
  14706. // Alpha test
  14707. if (material && material.needAlphaTesting()) {
  14708. defines.push("#define ALPHATEST");
  14709. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14710. attribs.push(BABYLON.VertexBuffer.UVKind);
  14711. defines.push("#define UV1");
  14712. }
  14713. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14714. var alphaTexture = material.getAlphaTestTexture();
  14715. if (alphaTexture.coordinatesIndex === 1) {
  14716. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14717. defines.push("#define UV2");
  14718. }
  14719. }
  14720. }
  14721. // Bones
  14722. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  14723. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14724. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14725. if (mesh.numBoneInfluencers > 4) {
  14726. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  14727. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  14728. }
  14729. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  14730. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14731. }
  14732. else {
  14733. defines.push("#define NUM_BONE_INFLUENCERS 0");
  14734. }
  14735. // Instances
  14736. if (useInstances) {
  14737. defines.push("#define INSTANCES");
  14738. attribs.push("world0");
  14739. attribs.push("world1");
  14740. attribs.push("world2");
  14741. attribs.push("world3");
  14742. }
  14743. // Get correct effect
  14744. var join = defines.join("\n");
  14745. if (this._cachedDefines !== join) {
  14746. this._cachedDefines = join;
  14747. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  14748. }
  14749. return this._effect.isReady();
  14750. };
  14751. /**
  14752. * Returns a RenderTargetTexture object : the shadow map texture.
  14753. */
  14754. ShadowGenerator.prototype.getShadowMap = function () {
  14755. return this._shadowMap;
  14756. };
  14757. /**
  14758. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  14759. */
  14760. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  14761. if (this._shadowMap2) {
  14762. return this._shadowMap2;
  14763. }
  14764. return this._shadowMap;
  14765. };
  14766. /**
  14767. * Returns the associated light object.
  14768. */
  14769. ShadowGenerator.prototype.getLight = function () {
  14770. return this._light;
  14771. };
  14772. // Methods
  14773. /**
  14774. * Returns a Matrix object : the updated transformation matrix.
  14775. */
  14776. ShadowGenerator.prototype.getTransformMatrix = function () {
  14777. var scene = this._scene;
  14778. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  14779. return this._transformMatrix;
  14780. }
  14781. this._currentRenderID = scene.getRenderId();
  14782. this._currentFaceIndexCache = this._currentFaceIndex;
  14783. var lightPosition = this._light.position;
  14784. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  14785. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  14786. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  14787. }
  14788. if (this._light.computeTransformedPosition()) {
  14789. lightPosition = this._light.transformedPosition;
  14790. }
  14791. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  14792. this._cachedPosition = lightPosition.clone();
  14793. this._cachedDirection = this._lightDirection.clone();
  14794. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  14795. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  14796. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14797. }
  14798. return this._transformMatrix;
  14799. };
  14800. /**
  14801. * Returns the darkness value (float).
  14802. */
  14803. ShadowGenerator.prototype.getDarkness = function () {
  14804. return this._darkness;
  14805. };
  14806. /**
  14807. * Sets the ShadowGenerator darkness value (float <= 1.0).
  14808. * Returns the ShadowGenerator.
  14809. */
  14810. ShadowGenerator.prototype.setDarkness = function (darkness) {
  14811. if (darkness >= 1.0)
  14812. this._darkness = 1.0;
  14813. else if (darkness <= 0.0)
  14814. this._darkness = 0.0;
  14815. else
  14816. this._darkness = darkness;
  14817. return this;
  14818. };
  14819. /**
  14820. * Sets the ability to have transparent shadow (boolean).
  14821. * Returns the ShadowGenerator.
  14822. */
  14823. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  14824. this._transparencyShadow = hasShadow;
  14825. return this;
  14826. };
  14827. ShadowGenerator.prototype._packHalf = function (depth) {
  14828. var scale = depth * 255.0;
  14829. var fract = scale - Math.floor(scale);
  14830. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  14831. };
  14832. /**
  14833. * Disposes the ShadowGenerator.
  14834. * Returns nothing.
  14835. */
  14836. ShadowGenerator.prototype.dispose = function () {
  14837. this._shadowMap.dispose();
  14838. if (this._shadowMap2) {
  14839. this._shadowMap2.dispose();
  14840. }
  14841. if (this._downSamplePostprocess) {
  14842. this._downSamplePostprocess.dispose();
  14843. }
  14844. if (this._boxBlurPostprocess) {
  14845. this._boxBlurPostprocess.dispose();
  14846. }
  14847. this._light._shadowGenerator = null;
  14848. };
  14849. /**
  14850. * Serializes the ShadowGenerator and returns a serializationObject.
  14851. */
  14852. ShadowGenerator.prototype.serialize = function () {
  14853. var serializationObject = {};
  14854. serializationObject.lightId = this._light.id;
  14855. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  14856. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  14857. serializationObject.usePoissonSampling = this.usePoissonSampling;
  14858. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  14859. serializationObject.renderList = [];
  14860. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  14861. var mesh = this.getShadowMap().renderList[meshIndex];
  14862. serializationObject.renderList.push(mesh.id);
  14863. }
  14864. return serializationObject;
  14865. };
  14866. /**
  14867. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  14868. */
  14869. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  14870. //casting to point light, as light is missing the position attr and typescript complains.
  14871. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14872. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14873. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14874. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  14875. meshes.forEach(function (mesh) {
  14876. shadowGenerator.getShadowMap().renderList.push(mesh);
  14877. });
  14878. }
  14879. if (parsedShadowGenerator.usePoissonSampling) {
  14880. shadowGenerator.usePoissonSampling = true;
  14881. }
  14882. else if (parsedShadowGenerator.useVarianceShadowMap) {
  14883. shadowGenerator.useVarianceShadowMap = true;
  14884. }
  14885. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  14886. shadowGenerator.useBlurVarianceShadowMap = true;
  14887. if (parsedShadowGenerator.blurScale) {
  14888. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  14889. }
  14890. if (parsedShadowGenerator.blurBoxOffset) {
  14891. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  14892. }
  14893. }
  14894. if (parsedShadowGenerator.bias !== undefined) {
  14895. shadowGenerator.bias = parsedShadowGenerator.bias;
  14896. }
  14897. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  14898. return shadowGenerator;
  14899. };
  14900. return ShadowGenerator;
  14901. }());
  14902. ShadowGenerator._FILTER_NONE = 0;
  14903. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  14904. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  14905. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  14906. BABYLON.ShadowGenerator = ShadowGenerator;
  14907. })(BABYLON || (BABYLON = {}));
  14908. //# sourceMappingURL=babylon.shadowGenerator.js.map
  14909. var BABYLON;
  14910. (function (BABYLON) {
  14911. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  14912. if (boxMin.x > sphereCenter.x + sphereRadius)
  14913. return false;
  14914. if (sphereCenter.x - sphereRadius > boxMax.x)
  14915. return false;
  14916. if (boxMin.y > sphereCenter.y + sphereRadius)
  14917. return false;
  14918. if (sphereCenter.y - sphereRadius > boxMax.y)
  14919. return false;
  14920. if (boxMin.z > sphereCenter.z + sphereRadius)
  14921. return false;
  14922. if (sphereCenter.z - sphereRadius > boxMax.z)
  14923. return false;
  14924. return true;
  14925. };
  14926. var getLowestRoot = (function () {
  14927. var result = { root: 0, found: false };
  14928. return function (a, b, c, maxR) {
  14929. result.root = 0;
  14930. result.found = false;
  14931. var determinant = b * b - 4.0 * a * c;
  14932. if (determinant < 0)
  14933. return result;
  14934. var sqrtD = Math.sqrt(determinant);
  14935. var r1 = (-b - sqrtD) / (2.0 * a);
  14936. var r2 = (-b + sqrtD) / (2.0 * a);
  14937. if (r1 > r2) {
  14938. var temp = r2;
  14939. r2 = r1;
  14940. r1 = temp;
  14941. }
  14942. if (r1 > 0 && r1 < maxR) {
  14943. result.root = r1;
  14944. result.found = true;
  14945. return result;
  14946. }
  14947. if (r2 > 0 && r2 < maxR) {
  14948. result.root = r2;
  14949. result.found = true;
  14950. return result;
  14951. }
  14952. return result;
  14953. };
  14954. })();
  14955. var Collider = (function () {
  14956. function Collider() {
  14957. this.radius = new BABYLON.Vector3(1, 1, 1);
  14958. this.retry = 0;
  14959. this.basePointWorld = BABYLON.Vector3.Zero();
  14960. this.velocityWorld = BABYLON.Vector3.Zero();
  14961. this.normalizedVelocity = BABYLON.Vector3.Zero();
  14962. this._collisionPoint = BABYLON.Vector3.Zero();
  14963. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  14964. this._tempVector = BABYLON.Vector3.Zero();
  14965. this._tempVector2 = BABYLON.Vector3.Zero();
  14966. this._tempVector3 = BABYLON.Vector3.Zero();
  14967. this._tempVector4 = BABYLON.Vector3.Zero();
  14968. this._edge = BABYLON.Vector3.Zero();
  14969. this._baseToVertex = BABYLON.Vector3.Zero();
  14970. this._destinationPoint = BABYLON.Vector3.Zero();
  14971. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  14972. this._displacementVector = BABYLON.Vector3.Zero();
  14973. this._collisionMask = -1;
  14974. }
  14975. Object.defineProperty(Collider.prototype, "collisionMask", {
  14976. get: function () {
  14977. return this._collisionMask;
  14978. },
  14979. set: function (mask) {
  14980. this._collisionMask = !isNaN(mask) ? mask : -1;
  14981. },
  14982. enumerable: true,
  14983. configurable: true
  14984. });
  14985. // Methods
  14986. Collider.prototype._initialize = function (source, dir, e) {
  14987. this.velocity = dir;
  14988. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  14989. this.basePoint = source;
  14990. source.multiplyToRef(this.radius, this.basePointWorld);
  14991. dir.multiplyToRef(this.radius, this.velocityWorld);
  14992. this.velocityWorldLength = this.velocityWorld.length();
  14993. this.epsilon = e;
  14994. this.collisionFound = false;
  14995. };
  14996. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  14997. pa.subtractToRef(point, this._tempVector);
  14998. pb.subtractToRef(point, this._tempVector2);
  14999. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  15000. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15001. if (d < 0)
  15002. return false;
  15003. pc.subtractToRef(point, this._tempVector3);
  15004. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  15005. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15006. if (d < 0)
  15007. return false;
  15008. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  15009. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15010. return d >= 0;
  15011. };
  15012. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  15013. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  15014. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  15015. if (distance > this.velocityWorldLength + max + sphereRadius) {
  15016. return false;
  15017. }
  15018. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  15019. return false;
  15020. return true;
  15021. };
  15022. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  15023. var t0;
  15024. var embeddedInPlane = false;
  15025. //defensive programming, actually not needed.
  15026. if (!trianglePlaneArray) {
  15027. trianglePlaneArray = [];
  15028. }
  15029. if (!trianglePlaneArray[faceIndex]) {
  15030. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  15031. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  15032. }
  15033. var trianglePlane = trianglePlaneArray[faceIndex];
  15034. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  15035. return;
  15036. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  15037. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  15038. if (normalDotVelocity == 0) {
  15039. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  15040. return;
  15041. embeddedInPlane = true;
  15042. t0 = 0;
  15043. }
  15044. else {
  15045. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15046. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15047. if (t0 > t1) {
  15048. var temp = t1;
  15049. t1 = t0;
  15050. t0 = temp;
  15051. }
  15052. if (t0 > 1.0 || t1 < 0.0)
  15053. return;
  15054. if (t0 < 0)
  15055. t0 = 0;
  15056. if (t0 > 1.0)
  15057. t0 = 1.0;
  15058. }
  15059. this._collisionPoint.copyFromFloats(0, 0, 0);
  15060. var found = false;
  15061. var t = 1.0;
  15062. if (!embeddedInPlane) {
  15063. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  15064. this.velocity.scaleToRef(t0, this._tempVector);
  15065. this._planeIntersectionPoint.addInPlace(this._tempVector);
  15066. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  15067. found = true;
  15068. t = t0;
  15069. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  15070. }
  15071. }
  15072. if (!found) {
  15073. var velocitySquaredLength = this.velocity.lengthSquared();
  15074. var a = velocitySquaredLength;
  15075. this.basePoint.subtractToRef(p1, this._tempVector);
  15076. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15077. var c = this._tempVector.lengthSquared() - 1.0;
  15078. var lowestRoot = getLowestRoot(a, b, c, t);
  15079. if (lowestRoot.found) {
  15080. t = lowestRoot.root;
  15081. found = true;
  15082. this._collisionPoint.copyFrom(p1);
  15083. }
  15084. this.basePoint.subtractToRef(p2, this._tempVector);
  15085. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15086. c = this._tempVector.lengthSquared() - 1.0;
  15087. lowestRoot = getLowestRoot(a, b, c, t);
  15088. if (lowestRoot.found) {
  15089. t = lowestRoot.root;
  15090. found = true;
  15091. this._collisionPoint.copyFrom(p2);
  15092. }
  15093. this.basePoint.subtractToRef(p3, this._tempVector);
  15094. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15095. c = this._tempVector.lengthSquared() - 1.0;
  15096. lowestRoot = getLowestRoot(a, b, c, t);
  15097. if (lowestRoot.found) {
  15098. t = lowestRoot.root;
  15099. found = true;
  15100. this._collisionPoint.copyFrom(p3);
  15101. }
  15102. p2.subtractToRef(p1, this._edge);
  15103. p1.subtractToRef(this.basePoint, this._baseToVertex);
  15104. var edgeSquaredLength = this._edge.lengthSquared();
  15105. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15106. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15107. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15108. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15109. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15110. lowestRoot = getLowestRoot(a, b, c, t);
  15111. if (lowestRoot.found) {
  15112. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15113. if (f >= 0.0 && f <= 1.0) {
  15114. t = lowestRoot.root;
  15115. found = true;
  15116. this._edge.scaleInPlace(f);
  15117. p1.addToRef(this._edge, this._collisionPoint);
  15118. }
  15119. }
  15120. p3.subtractToRef(p2, this._edge);
  15121. p2.subtractToRef(this.basePoint, this._baseToVertex);
  15122. edgeSquaredLength = this._edge.lengthSquared();
  15123. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15124. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15125. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15126. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15127. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15128. lowestRoot = getLowestRoot(a, b, c, t);
  15129. if (lowestRoot.found) {
  15130. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15131. if (f >= 0.0 && f <= 1.0) {
  15132. t = lowestRoot.root;
  15133. found = true;
  15134. this._edge.scaleInPlace(f);
  15135. p2.addToRef(this._edge, this._collisionPoint);
  15136. }
  15137. }
  15138. p1.subtractToRef(p3, this._edge);
  15139. p3.subtractToRef(this.basePoint, this._baseToVertex);
  15140. edgeSquaredLength = this._edge.lengthSquared();
  15141. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15142. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15143. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15144. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15145. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15146. lowestRoot = getLowestRoot(a, b, c, t);
  15147. if (lowestRoot.found) {
  15148. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15149. if (f >= 0.0 && f <= 1.0) {
  15150. t = lowestRoot.root;
  15151. found = true;
  15152. this._edge.scaleInPlace(f);
  15153. p3.addToRef(this._edge, this._collisionPoint);
  15154. }
  15155. }
  15156. }
  15157. if (found) {
  15158. var distToCollision = t * this.velocity.length();
  15159. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  15160. if (!this.intersectionPoint) {
  15161. this.intersectionPoint = this._collisionPoint.clone();
  15162. }
  15163. else {
  15164. this.intersectionPoint.copyFrom(this._collisionPoint);
  15165. }
  15166. this.nearestDistance = distToCollision;
  15167. this.collisionFound = true;
  15168. }
  15169. }
  15170. };
  15171. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  15172. for (var i = indexStart; i < indexEnd; i += 3) {
  15173. var p1 = pts[indices[i] - decal];
  15174. var p2 = pts[indices[i + 1] - decal];
  15175. var p3 = pts[indices[i + 2] - decal];
  15176. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  15177. }
  15178. };
  15179. Collider.prototype._getResponse = function (pos, vel) {
  15180. pos.addToRef(vel, this._destinationPoint);
  15181. vel.scaleInPlace((this.nearestDistance / vel.length()));
  15182. this.basePoint.addToRef(vel, pos);
  15183. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  15184. this._slidePlaneNormal.normalize();
  15185. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  15186. pos.addInPlace(this._displacementVector);
  15187. this.intersectionPoint.addInPlace(this._displacementVector);
  15188. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  15189. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  15190. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  15191. };
  15192. return Collider;
  15193. }());
  15194. BABYLON.Collider = Collider;
  15195. })(BABYLON || (BABYLON = {}));
  15196. //# sourceMappingURL=babylon.collider.js.map
  15197. var BABYLON;
  15198. (function (BABYLON) {
  15199. //WebWorker code will be inserted to this variable.
  15200. BABYLON.CollisionWorker = "";
  15201. var WorkerTaskType;
  15202. (function (WorkerTaskType) {
  15203. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  15204. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  15205. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  15206. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  15207. var WorkerReplyType;
  15208. (function (WorkerReplyType) {
  15209. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  15210. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  15211. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  15212. var CollisionCoordinatorWorker = (function () {
  15213. function CollisionCoordinatorWorker() {
  15214. var _this = this;
  15215. this._scaledPosition = BABYLON.Vector3.Zero();
  15216. this._scaledVelocity = BABYLON.Vector3.Zero();
  15217. this.onMeshUpdated = function (mesh) {
  15218. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  15219. };
  15220. this.onGeometryUpdated = function (geometry) {
  15221. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  15222. };
  15223. this._afterRender = function () {
  15224. if (!_this._init)
  15225. return;
  15226. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  15227. return;
  15228. }
  15229. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  15230. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  15231. if (_this._runningUpdated > 4) {
  15232. return;
  15233. }
  15234. ++_this._runningUpdated;
  15235. var payload = {
  15236. updatedMeshes: _this._addUpdateMeshesList,
  15237. updatedGeometries: _this._addUpdateGeometriesList,
  15238. removedGeometries: _this._toRemoveGeometryArray,
  15239. removedMeshes: _this._toRemoveMeshesArray
  15240. };
  15241. var message = {
  15242. payload: payload,
  15243. taskType: WorkerTaskType.UPDATE
  15244. };
  15245. var serializable = [];
  15246. for (var id in payload.updatedGeometries) {
  15247. if (payload.updatedGeometries.hasOwnProperty(id)) {
  15248. //prepare transferables
  15249. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  15250. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  15251. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  15252. }
  15253. }
  15254. _this._worker.postMessage(message, serializable);
  15255. _this._addUpdateMeshesList = {};
  15256. _this._addUpdateGeometriesList = {};
  15257. _this._toRemoveGeometryArray = [];
  15258. _this._toRemoveMeshesArray = [];
  15259. };
  15260. this._onMessageFromWorker = function (e) {
  15261. var returnData = e.data;
  15262. if (returnData.error != WorkerReplyType.SUCCESS) {
  15263. //TODO what errors can be returned from the worker?
  15264. BABYLON.Tools.Warn("error returned from worker!");
  15265. return;
  15266. }
  15267. switch (returnData.taskType) {
  15268. case WorkerTaskType.INIT:
  15269. _this._init = true;
  15270. //Update the worked with ALL of the scene's current state
  15271. _this._scene.meshes.forEach(function (mesh) {
  15272. _this.onMeshAdded(mesh);
  15273. });
  15274. _this._scene.getGeometries().forEach(function (geometry) {
  15275. _this.onGeometryAdded(geometry);
  15276. });
  15277. break;
  15278. case WorkerTaskType.UPDATE:
  15279. _this._runningUpdated--;
  15280. break;
  15281. case WorkerTaskType.COLLIDE:
  15282. _this._runningCollisionTask = false;
  15283. var returnPayload = returnData.payload;
  15284. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  15285. return;
  15286. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  15287. //cleanup
  15288. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  15289. break;
  15290. }
  15291. };
  15292. this._collisionsCallbackArray = [];
  15293. this._init = false;
  15294. this._runningUpdated = 0;
  15295. this._runningCollisionTask = false;
  15296. this._addUpdateMeshesList = {};
  15297. this._addUpdateGeometriesList = {};
  15298. this._toRemoveGeometryArray = [];
  15299. this._toRemoveMeshesArray = [];
  15300. }
  15301. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15302. if (!this._init)
  15303. return;
  15304. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  15305. return;
  15306. position.divideToRef(collider.radius, this._scaledPosition);
  15307. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15308. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  15309. var payload = {
  15310. collider: {
  15311. position: this._scaledPosition.asArray(),
  15312. velocity: this._scaledVelocity.asArray(),
  15313. radius: collider.radius.asArray()
  15314. },
  15315. collisionId: collisionIndex,
  15316. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  15317. maximumRetry: maximumRetry
  15318. };
  15319. var message = {
  15320. payload: payload,
  15321. taskType: WorkerTaskType.COLLIDE
  15322. };
  15323. this._worker.postMessage(message);
  15324. };
  15325. CollisionCoordinatorWorker.prototype.init = function (scene) {
  15326. this._scene = scene;
  15327. this._scene.registerAfterRender(this._afterRender);
  15328. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  15329. this._worker = new Worker(workerUrl);
  15330. this._worker.onmessage = this._onMessageFromWorker;
  15331. var message = {
  15332. payload: {},
  15333. taskType: WorkerTaskType.INIT
  15334. };
  15335. this._worker.postMessage(message);
  15336. };
  15337. CollisionCoordinatorWorker.prototype.destroy = function () {
  15338. this._scene.unregisterAfterRender(this._afterRender);
  15339. this._worker.terminate();
  15340. };
  15341. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  15342. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  15343. this.onMeshUpdated(mesh);
  15344. };
  15345. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  15346. this._toRemoveMeshesArray.push(mesh.uniqueId);
  15347. };
  15348. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  15349. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  15350. geometry.onGeometryUpdated = this.onGeometryUpdated;
  15351. this.onGeometryUpdated(geometry);
  15352. };
  15353. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  15354. this._toRemoveGeometryArray.push(geometry.id);
  15355. };
  15356. return CollisionCoordinatorWorker;
  15357. }());
  15358. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  15359. var submeshes = [];
  15360. if (mesh.subMeshes) {
  15361. submeshes = mesh.subMeshes.map(function (sm, idx) {
  15362. return {
  15363. position: idx,
  15364. verticesStart: sm.verticesStart,
  15365. verticesCount: sm.verticesCount,
  15366. indexStart: sm.indexStart,
  15367. indexCount: sm.indexCount,
  15368. hasMaterial: !!sm.getMaterial(),
  15369. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15370. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  15371. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15372. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  15373. };
  15374. });
  15375. }
  15376. var geometryId = null;
  15377. if (mesh instanceof BABYLON.Mesh) {
  15378. geometryId = mesh.geometry ? mesh.geometry.id : null;
  15379. }
  15380. else if (mesh instanceof BABYLON.InstancedMesh) {
  15381. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  15382. }
  15383. return {
  15384. uniqueId: mesh.uniqueId,
  15385. id: mesh.id,
  15386. name: mesh.name,
  15387. geometryId: geometryId,
  15388. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15389. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  15390. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15391. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  15392. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  15393. subMeshes: submeshes,
  15394. checkCollisions: mesh.checkCollisions
  15395. };
  15396. };
  15397. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  15398. return {
  15399. id: geometry.id,
  15400. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  15401. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  15402. indices: new Uint32Array(geometry.getIndices() || []),
  15403. };
  15404. };
  15405. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  15406. var CollisionCoordinatorLegacy = (function () {
  15407. function CollisionCoordinatorLegacy() {
  15408. this._scaledPosition = BABYLON.Vector3.Zero();
  15409. this._scaledVelocity = BABYLON.Vector3.Zero();
  15410. this._finalPosition = BABYLON.Vector3.Zero();
  15411. }
  15412. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15413. position.divideToRef(collider.radius, this._scaledPosition);
  15414. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15415. collider.collidedMesh = null;
  15416. collider.retry = 0;
  15417. collider.initialVelocity = this._scaledVelocity;
  15418. collider.initialPosition = this._scaledPosition;
  15419. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  15420. this._finalPosition.multiplyInPlace(collider.radius);
  15421. //run the callback
  15422. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  15423. };
  15424. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  15425. this._scene = scene;
  15426. };
  15427. CollisionCoordinatorLegacy.prototype.destroy = function () {
  15428. //Legacy need no destruction method.
  15429. };
  15430. //No update in legacy mode
  15431. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  15432. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  15433. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  15434. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  15435. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  15436. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  15437. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  15438. if (excludedMesh === void 0) { excludedMesh = null; }
  15439. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  15440. if (collider.retry >= maximumRetry) {
  15441. finalPosition.copyFrom(position);
  15442. return;
  15443. }
  15444. // Check if this is a mesh else camera or -1
  15445. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  15446. collider._initialize(position, velocity, closeDistance);
  15447. // Check all meshes
  15448. for (var index = 0; index < this._scene.meshes.length; index++) {
  15449. var mesh = this._scene.meshes[index];
  15450. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  15451. mesh._checkCollision(collider);
  15452. }
  15453. }
  15454. if (!collider.collisionFound) {
  15455. position.addToRef(velocity, finalPosition);
  15456. return;
  15457. }
  15458. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  15459. collider._getResponse(position, velocity);
  15460. }
  15461. if (velocity.length() <= closeDistance) {
  15462. finalPosition.copyFrom(position);
  15463. return;
  15464. }
  15465. collider.retry++;
  15466. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  15467. };
  15468. return CollisionCoordinatorLegacy;
  15469. }());
  15470. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  15471. })(BABYLON || (BABYLON = {}));
  15472. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  15473. var BABYLON;
  15474. (function (BABYLON) {
  15475. var Camera = (function (_super) {
  15476. __extends(Camera, _super);
  15477. function Camera(name, position, scene) {
  15478. var _this = _super.call(this, name, scene) || this;
  15479. _this.upVector = BABYLON.Vector3.Up();
  15480. _this.orthoLeft = null;
  15481. _this.orthoRight = null;
  15482. _this.orthoBottom = null;
  15483. _this.orthoTop = null;
  15484. _this.fov = 0.8;
  15485. _this.minZ = 1.0;
  15486. _this.maxZ = 10000.0;
  15487. _this.inertia = 0.9;
  15488. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15489. _this.isIntermediate = false;
  15490. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15491. _this.layerMask = 0x0FFFFFFF;
  15492. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15493. // Camera rig members
  15494. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15495. _this._rigCameras = new Array();
  15496. // Cache
  15497. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15498. _this._projectionMatrix = new BABYLON.Matrix();
  15499. _this._doNotComputeProjectionMatrix = false;
  15500. _this._postProcesses = new Array();
  15501. _this._transformMatrix = BABYLON.Matrix.Zero();
  15502. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15503. _this._activeMeshes = new BABYLON.SmartArray(256);
  15504. _this._globalPosition = BABYLON.Vector3.Zero();
  15505. _this._refreshFrustumPlanes = true;
  15506. _this.getScene().addCamera(_this);
  15507. if (!_this.getScene().activeCamera) {
  15508. _this.getScene().activeCamera = _this;
  15509. }
  15510. _this.position = position;
  15511. return _this;
  15512. }
  15513. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15514. get: function () {
  15515. return Camera._PERSPECTIVE_CAMERA;
  15516. },
  15517. enumerable: true,
  15518. configurable: true
  15519. });
  15520. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15521. get: function () {
  15522. return Camera._ORTHOGRAPHIC_CAMERA;
  15523. },
  15524. enumerable: true,
  15525. configurable: true
  15526. });
  15527. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15528. get: function () {
  15529. return Camera._FOVMODE_VERTICAL_FIXED;
  15530. },
  15531. enumerable: true,
  15532. configurable: true
  15533. });
  15534. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15535. get: function () {
  15536. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15537. },
  15538. enumerable: true,
  15539. configurable: true
  15540. });
  15541. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15542. get: function () {
  15543. return Camera._RIG_MODE_NONE;
  15544. },
  15545. enumerable: true,
  15546. configurable: true
  15547. });
  15548. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15549. get: function () {
  15550. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15551. },
  15552. enumerable: true,
  15553. configurable: true
  15554. });
  15555. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15556. get: function () {
  15557. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15558. },
  15559. enumerable: true,
  15560. configurable: true
  15561. });
  15562. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15563. get: function () {
  15564. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15565. },
  15566. enumerable: true,
  15567. configurable: true
  15568. });
  15569. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15570. get: function () {
  15571. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15572. },
  15573. enumerable: true,
  15574. configurable: true
  15575. });
  15576. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15577. get: function () {
  15578. return Camera._RIG_MODE_VR;
  15579. },
  15580. enumerable: true,
  15581. configurable: true
  15582. });
  15583. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15584. get: function () {
  15585. return Camera._RIG_MODE_WEBVR;
  15586. },
  15587. enumerable: true,
  15588. configurable: true
  15589. });
  15590. Camera.prototype.getClassName = function () {
  15591. return "Camera";
  15592. };
  15593. /**
  15594. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15595. */
  15596. Camera.prototype.toString = function (fullDetails) {
  15597. var ret = "Name: " + this.name;
  15598. ret += ", type: " + this.getClassName();
  15599. if (this.animations) {
  15600. for (var i = 0; i < this.animations.length; i++) {
  15601. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15602. }
  15603. }
  15604. if (fullDetails) {
  15605. }
  15606. return ret;
  15607. };
  15608. Object.defineProperty(Camera.prototype, "globalPosition", {
  15609. get: function () {
  15610. return this._globalPosition;
  15611. },
  15612. enumerable: true,
  15613. configurable: true
  15614. });
  15615. Camera.prototype.getActiveMeshes = function () {
  15616. return this._activeMeshes;
  15617. };
  15618. Camera.prototype.isActiveMesh = function (mesh) {
  15619. return (this._activeMeshes.indexOf(mesh) !== -1);
  15620. };
  15621. //Cache
  15622. Camera.prototype._initCache = function () {
  15623. _super.prototype._initCache.call(this);
  15624. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15625. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15626. this._cache.mode = undefined;
  15627. this._cache.minZ = undefined;
  15628. this._cache.maxZ = undefined;
  15629. this._cache.fov = undefined;
  15630. this._cache.fovMode = undefined;
  15631. this._cache.aspectRatio = undefined;
  15632. this._cache.orthoLeft = undefined;
  15633. this._cache.orthoRight = undefined;
  15634. this._cache.orthoBottom = undefined;
  15635. this._cache.orthoTop = undefined;
  15636. this._cache.renderWidth = undefined;
  15637. this._cache.renderHeight = undefined;
  15638. };
  15639. Camera.prototype._updateCache = function (ignoreParentClass) {
  15640. if (!ignoreParentClass) {
  15641. _super.prototype._updateCache.call(this);
  15642. }
  15643. var engine = this.getEngine();
  15644. this._cache.position.copyFrom(this.position);
  15645. this._cache.upVector.copyFrom(this.upVector);
  15646. this._cache.mode = this.mode;
  15647. this._cache.minZ = this.minZ;
  15648. this._cache.maxZ = this.maxZ;
  15649. this._cache.fov = this.fov;
  15650. this._cache.fovMode = this.fovMode;
  15651. this._cache.aspectRatio = engine.getAspectRatio(this);
  15652. this._cache.orthoLeft = this.orthoLeft;
  15653. this._cache.orthoRight = this.orthoRight;
  15654. this._cache.orthoBottom = this.orthoBottom;
  15655. this._cache.orthoTop = this.orthoTop;
  15656. this._cache.renderWidth = engine.getRenderWidth();
  15657. this._cache.renderHeight = engine.getRenderHeight();
  15658. };
  15659. Camera.prototype._updateFromScene = function () {
  15660. this.updateCache();
  15661. this.update();
  15662. };
  15663. // Synchronized
  15664. Camera.prototype._isSynchronized = function () {
  15665. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15666. };
  15667. Camera.prototype._isSynchronizedViewMatrix = function () {
  15668. if (!_super.prototype._isSynchronized.call(this))
  15669. return false;
  15670. return this._cache.position.equals(this.position)
  15671. && this._cache.upVector.equals(this.upVector)
  15672. && this.isSynchronizedWithParent();
  15673. };
  15674. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15675. var check = this._cache.mode === this.mode
  15676. && this._cache.minZ === this.minZ
  15677. && this._cache.maxZ === this.maxZ;
  15678. if (!check) {
  15679. return false;
  15680. }
  15681. var engine = this.getEngine();
  15682. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15683. check = this._cache.fov === this.fov
  15684. && this._cache.fovMode === this.fovMode
  15685. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15686. }
  15687. else {
  15688. check = this._cache.orthoLeft === this.orthoLeft
  15689. && this._cache.orthoRight === this.orthoRight
  15690. && this._cache.orthoBottom === this.orthoBottom
  15691. && this._cache.orthoTop === this.orthoTop
  15692. && this._cache.renderWidth === engine.getRenderWidth()
  15693. && this._cache.renderHeight === engine.getRenderHeight();
  15694. }
  15695. return check;
  15696. };
  15697. // Controls
  15698. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15699. };
  15700. Camera.prototype.detachControl = function (element) {
  15701. };
  15702. Camera.prototype.update = function () {
  15703. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15704. this._updateRigCameras();
  15705. }
  15706. this._checkInputs();
  15707. };
  15708. Camera.prototype._checkInputs = function () {
  15709. };
  15710. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15711. // invalidate framebuffer
  15712. if (this._postProcesses.length > 0) {
  15713. this._postProcesses[0].markTextureDirty();
  15714. }
  15715. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15716. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15717. var cam = this._rigCameras[i];
  15718. var rigPostProcess = cam._rigPostProcess;
  15719. // for VR rig, there does not have to be a post process
  15720. if (rigPostProcess) {
  15721. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15722. if (isPass) {
  15723. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15724. cam.isIntermediate = this._postProcesses.length === 0;
  15725. }
  15726. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15727. rigPostProcess.markTextureDirty();
  15728. }
  15729. else {
  15730. cam._postProcesses = this._postProcesses.slice(0);
  15731. }
  15732. }
  15733. };
  15734. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15735. if (insertAt === void 0) { insertAt = null; }
  15736. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15737. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15738. return 0;
  15739. }
  15740. if (insertAt == null || insertAt < 0) {
  15741. this._postProcesses.push(postProcess);
  15742. }
  15743. else {
  15744. this._postProcesses.splice(insertAt, 0, postProcess);
  15745. }
  15746. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15747. return this._postProcesses.indexOf(postProcess);
  15748. };
  15749. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15750. if (atIndices === void 0) { atIndices = null; }
  15751. var result = [];
  15752. var i;
  15753. var index;
  15754. if (!atIndices) {
  15755. var idx = this._postProcesses.indexOf(postProcess);
  15756. if (idx !== -1) {
  15757. this._postProcesses.splice(idx, 1);
  15758. }
  15759. }
  15760. else {
  15761. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15762. // iterate descending, so can just splice as we go
  15763. for (i = atIndices.length - 1; i >= 0; i--) {
  15764. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15765. result.push(i);
  15766. continue;
  15767. }
  15768. index = atIndices[i];
  15769. this._postProcesses.splice(index, 1);
  15770. }
  15771. }
  15772. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15773. return result;
  15774. };
  15775. Camera.prototype.getWorldMatrix = function () {
  15776. if (!this._worldMatrix) {
  15777. this._worldMatrix = BABYLON.Matrix.Identity();
  15778. }
  15779. var viewMatrix = this.getViewMatrix();
  15780. viewMatrix.invertToRef(this._worldMatrix);
  15781. return this._worldMatrix;
  15782. };
  15783. Camera.prototype._getViewMatrix = function () {
  15784. return BABYLON.Matrix.Identity();
  15785. };
  15786. Camera.prototype.getViewMatrix = function (force) {
  15787. this._computedViewMatrix = this._computeViewMatrix(force);
  15788. if (!force && this._isSynchronizedViewMatrix()) {
  15789. return this._computedViewMatrix;
  15790. }
  15791. this._refreshFrustumPlanes = true;
  15792. if (!this.parent || !this.parent.getWorldMatrix) {
  15793. this._globalPosition.copyFrom(this.position);
  15794. }
  15795. else {
  15796. if (!this._worldMatrix) {
  15797. this._worldMatrix = BABYLON.Matrix.Identity();
  15798. }
  15799. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15800. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15801. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15802. this._computedViewMatrix.invert();
  15803. this._markSyncedWithParent();
  15804. }
  15805. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15806. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15807. }
  15808. this._currentRenderId = this.getScene().getRenderId();
  15809. return this._computedViewMatrix;
  15810. };
  15811. Camera.prototype._computeViewMatrix = function (force) {
  15812. if (!force && this._isSynchronizedViewMatrix()) {
  15813. return this._computedViewMatrix;
  15814. }
  15815. this._computedViewMatrix = this._getViewMatrix();
  15816. this._currentRenderId = this.getScene().getRenderId();
  15817. return this._computedViewMatrix;
  15818. };
  15819. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15820. this._doNotComputeProjectionMatrix = true;
  15821. if (projection !== undefined) {
  15822. this._projectionMatrix = projection;
  15823. }
  15824. };
  15825. ;
  15826. Camera.prototype.unfreezeProjectionMatrix = function () {
  15827. this._doNotComputeProjectionMatrix = false;
  15828. };
  15829. ;
  15830. Camera.prototype.getProjectionMatrix = function (force) {
  15831. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15832. return this._projectionMatrix;
  15833. }
  15834. this._refreshFrustumPlanes = true;
  15835. var engine = this.getEngine();
  15836. var scene = this.getScene();
  15837. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15838. if (this.minZ <= 0) {
  15839. this.minZ = 0.1;
  15840. }
  15841. if (scene.useRightHandedSystem) {
  15842. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15843. }
  15844. else {
  15845. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15846. }
  15847. return this._projectionMatrix;
  15848. }
  15849. var halfWidth = engine.getRenderWidth() / 2.0;
  15850. var halfHeight = engine.getRenderHeight() / 2.0;
  15851. if (scene.useRightHandedSystem) {
  15852. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15853. }
  15854. else {
  15855. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15856. }
  15857. return this._projectionMatrix;
  15858. };
  15859. Camera.prototype.getTranformationMatrix = function () {
  15860. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15861. return this._transformMatrix;
  15862. };
  15863. Camera.prototype.updateFrustumPlanes = function () {
  15864. if (!this._refreshFrustumPlanes) {
  15865. return;
  15866. }
  15867. this.getTranformationMatrix();
  15868. if (!this._frustumPlanes) {
  15869. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15870. }
  15871. else {
  15872. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15873. }
  15874. this._refreshFrustumPlanes = false;
  15875. };
  15876. Camera.prototype.isInFrustum = function (target) {
  15877. this.updateFrustumPlanes();
  15878. return target.isInFrustum(this._frustumPlanes);
  15879. };
  15880. Camera.prototype.isCompletelyInFrustum = function (target) {
  15881. this.updateFrustumPlanes();
  15882. return target.isCompletelyInFrustum(this._frustumPlanes);
  15883. };
  15884. Camera.prototype.dispose = function () {
  15885. // Animations
  15886. this.getScene().stopAnimation(this);
  15887. // Remove from scene
  15888. this.getScene().removeCamera(this);
  15889. while (this._rigCameras.length > 0) {
  15890. this._rigCameras.pop().dispose();
  15891. }
  15892. // Postprocesses
  15893. var i = this._postProcesses.length;
  15894. while (--i >= 0) {
  15895. this._postProcesses[i].dispose(this);
  15896. }
  15897. _super.prototype.dispose.call(this);
  15898. };
  15899. // ---- Camera rigs section ----
  15900. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15901. while (this._rigCameras.length > 0) {
  15902. this._rigCameras.pop().dispose();
  15903. }
  15904. this.cameraRigMode = mode;
  15905. this._cameraRigParams = {};
  15906. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15907. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15908. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15909. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15910. // create the rig cameras, unless none
  15911. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15912. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15913. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15914. }
  15915. switch (this.cameraRigMode) {
  15916. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15917. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15918. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15919. break;
  15920. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15921. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15922. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15923. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15924. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15925. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15926. break;
  15927. case Camera.RIG_MODE_VR:
  15928. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15929. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15930. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15931. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15932. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15933. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15934. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15935. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15936. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15937. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15938. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15939. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15940. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15941. if (metrics.compensateDistortion) {
  15942. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15943. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15944. }
  15945. break;
  15946. case Camera.RIG_MODE_WEBVR:
  15947. if (rigParams.vrDisplay) {
  15948. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15949. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15950. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15951. this._rigCameras[0].setCameraRigParameter("left", true);
  15952. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15953. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  15954. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15955. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15956. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15957. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15958. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15959. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  15960. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15961. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15962. }
  15963. break;
  15964. }
  15965. this._cascadePostProcessesToRigCams();
  15966. this.
  15967. update();
  15968. };
  15969. Camera.prototype._getVRProjectionMatrix = function () {
  15970. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15971. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15972. return this._projectionMatrix;
  15973. };
  15974. Camera.prototype._getWebVRProjectionMatrix = function () {
  15975. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  15976. //babylon compatible matrix
  15977. [8, 9, 10, 11].forEach(function (num) {
  15978. projectionArray[num] *= -1;
  15979. });
  15980. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  15981. return this._projectionMatrix;
  15982. };
  15983. //Can be used, but we'll use the free camera's view matrix calculation
  15984. Camera.prototype._getWebVRViewMatrix = function () {
  15985. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  15986. //babylon compatible matrix
  15987. [8, 9, 10, 11].forEach(function (num) {
  15988. projectionArray[num] *= -1;
  15989. });
  15990. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  15991. return this._webvrViewMatrix;
  15992. };
  15993. Camera.prototype.setCameraRigParameter = function (name, value) {
  15994. if (!this._cameraRigParams) {
  15995. this._cameraRigParams = {};
  15996. }
  15997. this._cameraRigParams[name] = value;
  15998. //provisionnally:
  15999. if (name === "interaxialDistance") {
  16000. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16001. }
  16002. };
  16003. /**
  16004. * needs to be overridden by children so sub has required properties to be copied
  16005. */
  16006. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16007. return null;
  16008. };
  16009. /**
  16010. * May need to be overridden by children
  16011. */
  16012. Camera.prototype._updateRigCameras = function () {
  16013. for (var i = 0; i < this._rigCameras.length; i++) {
  16014. this._rigCameras[i].minZ = this.minZ;
  16015. this._rigCameras[i].maxZ = this.maxZ;
  16016. this._rigCameras[i].fov = this.fov;
  16017. }
  16018. // only update viewport when ANAGLYPH
  16019. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16020. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16021. }
  16022. };
  16023. Camera.prototype._setupInputs = function () {
  16024. };
  16025. Camera.prototype.serialize = function () {
  16026. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16027. // Type
  16028. serializationObject.type = this.getClassName();
  16029. // Parent
  16030. if (this.parent) {
  16031. serializationObject.parentId = this.parent.id;
  16032. }
  16033. if (this.inputs) {
  16034. this.inputs.serialize(serializationObject);
  16035. }
  16036. // Animations
  16037. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16038. serializationObject.ranges = this.serializeAnimationRanges();
  16039. return serializationObject;
  16040. };
  16041. Camera.prototype.clone = function (name) {
  16042. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16043. };
  16044. Camera.prototype.getDirection = function (localAxis) {
  16045. var result = BABYLON.Vector3.Zero();
  16046. this.getDirectionToRef(localAxis, result);
  16047. return result;
  16048. };
  16049. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16050. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16051. };
  16052. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16053. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16054. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16055. switch (type) {
  16056. case "ArcRotateCamera":
  16057. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16058. case "DeviceOrientationCamera":
  16059. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16060. case "FollowCamera":
  16061. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16062. case "ArcFollowCamera":
  16063. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16064. case "GamepadCamera":
  16065. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16066. case "TouchCamera":
  16067. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16068. case "VirtualJoysticksCamera":
  16069. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16070. case "WebVRFreeCamera":
  16071. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16072. case "WebVRGamepadCamera":
  16073. return function () { return new BABYLON.WebVRGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16074. case "VRDeviceOrientationFreeCamera":
  16075. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16076. case "VRDeviceOrientationGamepadCamera":
  16077. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16078. case "AnaglyphArcRotateCamera":
  16079. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16080. case "AnaglyphFreeCamera":
  16081. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16082. case "AnaglyphGamepadCamera":
  16083. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16084. case "AnaglyphUniversalCamera":
  16085. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16086. case "StereoscopicArcRotateCamera":
  16087. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16088. case "StereoscopicFreeCamera":
  16089. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16090. case "StereoscopicGamepadCamera":
  16091. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16092. case "StereoscopicUniversalCamera":
  16093. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16094. case "FreeCamera":
  16095. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16096. default:
  16097. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16098. }
  16099. };
  16100. Camera.Parse = function (parsedCamera, scene) {
  16101. var type = parsedCamera.type;
  16102. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16103. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16104. // Parent
  16105. if (parsedCamera.parentId) {
  16106. camera._waitingParentId = parsedCamera.parentId;
  16107. }
  16108. //If camera has an input manager, let it parse inputs settings
  16109. if (camera.inputs) {
  16110. camera.inputs.parse(parsedCamera);
  16111. camera._setupInputs();
  16112. }
  16113. // Target
  16114. if (parsedCamera.target) {
  16115. if (camera.setTarget) {
  16116. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16117. }
  16118. }
  16119. // Apply 3d rig, when found
  16120. if (parsedCamera.cameraRigMode) {
  16121. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16122. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16123. }
  16124. // Animations
  16125. if (parsedCamera.animations) {
  16126. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16127. var parsedAnimation = parsedCamera.animations[animationIndex];
  16128. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16129. }
  16130. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16131. }
  16132. if (parsedCamera.autoAnimate) {
  16133. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16134. }
  16135. return camera;
  16136. };
  16137. return Camera;
  16138. }(BABYLON.Node));
  16139. // Statics
  16140. Camera._PERSPECTIVE_CAMERA = 0;
  16141. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16142. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16143. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16144. Camera._RIG_MODE_NONE = 0;
  16145. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16146. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16147. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16148. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16149. Camera._RIG_MODE_VR = 20;
  16150. Camera._RIG_MODE_WEBVR = 21;
  16151. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16152. __decorate([
  16153. BABYLON.serializeAsVector3()
  16154. ], Camera.prototype, "position", void 0);
  16155. __decorate([
  16156. BABYLON.serializeAsVector3()
  16157. ], Camera.prototype, "upVector", void 0);
  16158. __decorate([
  16159. BABYLON.serialize()
  16160. ], Camera.prototype, "orthoLeft", void 0);
  16161. __decorate([
  16162. BABYLON.serialize()
  16163. ], Camera.prototype, "orthoRight", void 0);
  16164. __decorate([
  16165. BABYLON.serialize()
  16166. ], Camera.prototype, "orthoBottom", void 0);
  16167. __decorate([
  16168. BABYLON.serialize()
  16169. ], Camera.prototype, "orthoTop", void 0);
  16170. __decorate([
  16171. BABYLON.serialize()
  16172. ], Camera.prototype, "fov", void 0);
  16173. __decorate([
  16174. BABYLON.serialize()
  16175. ], Camera.prototype, "minZ", void 0);
  16176. __decorate([
  16177. BABYLON.serialize()
  16178. ], Camera.prototype, "maxZ", void 0);
  16179. __decorate([
  16180. BABYLON.serialize()
  16181. ], Camera.prototype, "inertia", void 0);
  16182. __decorate([
  16183. BABYLON.serialize()
  16184. ], Camera.prototype, "mode", void 0);
  16185. __decorate([
  16186. BABYLON.serialize()
  16187. ], Camera.prototype, "layerMask", void 0);
  16188. __decorate([
  16189. BABYLON.serialize()
  16190. ], Camera.prototype, "fovMode", void 0);
  16191. __decorate([
  16192. BABYLON.serialize()
  16193. ], Camera.prototype, "cameraRigMode", void 0);
  16194. __decorate([
  16195. BABYLON.serialize()
  16196. ], Camera.prototype, "interaxialDistance", void 0);
  16197. __decorate([
  16198. BABYLON.serialize()
  16199. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16200. BABYLON.Camera = Camera;
  16201. })(BABYLON || (BABYLON = {}));
  16202. //# sourceMappingURL=babylon.camera.js.map
  16203. var BABYLON;
  16204. (function (BABYLON) {
  16205. BABYLON.CameraInputTypes = {};
  16206. var CameraInputsManager = (function () {
  16207. function CameraInputsManager(camera) {
  16208. this.attached = {};
  16209. this.camera = camera;
  16210. this.checkInputs = function () { };
  16211. }
  16212. CameraInputsManager.prototype.add = function (input) {
  16213. var type = input.getSimpleName();
  16214. if (this.attached[type]) {
  16215. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  16216. return;
  16217. }
  16218. this.attached[type] = input;
  16219. input.camera = this.camera;
  16220. //for checkInputs, we are dynamically creating a function
  16221. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  16222. if (input.checkInputs) {
  16223. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16224. }
  16225. if (this.attachedElement) {
  16226. input.attachControl(this.attachedElement);
  16227. }
  16228. };
  16229. CameraInputsManager.prototype.remove = function (inputToRemove) {
  16230. for (var cam in this.attached) {
  16231. var input = this.attached[cam];
  16232. if (input === inputToRemove) {
  16233. input.detachControl(this.attachedElement);
  16234. delete this.attached[cam];
  16235. this.rebuildInputCheck();
  16236. }
  16237. }
  16238. };
  16239. CameraInputsManager.prototype.removeByType = function (inputType) {
  16240. for (var cam in this.attached) {
  16241. var input = this.attached[cam];
  16242. if (input.getTypeName() === inputType) {
  16243. input.detachControl(this.attachedElement);
  16244. delete this.attached[cam];
  16245. this.rebuildInputCheck();
  16246. }
  16247. }
  16248. };
  16249. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  16250. var current = this.checkInputs;
  16251. return function () {
  16252. current();
  16253. fn();
  16254. };
  16255. };
  16256. CameraInputsManager.prototype.attachInput = function (input) {
  16257. input.attachControl(this.attachedElement, this.noPreventDefault);
  16258. };
  16259. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  16260. if (this.attachedElement) {
  16261. return;
  16262. }
  16263. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  16264. this.attachedElement = element;
  16265. this.noPreventDefault = noPreventDefault;
  16266. for (var cam in this.attached) {
  16267. var input = this.attached[cam];
  16268. this.attached[cam].attachControl(element, noPreventDefault);
  16269. }
  16270. };
  16271. CameraInputsManager.prototype.detachElement = function (element) {
  16272. if (this.attachedElement !== element) {
  16273. return;
  16274. }
  16275. for (var cam in this.attached) {
  16276. var input = this.attached[cam];
  16277. this.attached[cam].detachControl(element);
  16278. }
  16279. this.attachedElement = null;
  16280. };
  16281. CameraInputsManager.prototype.rebuildInputCheck = function () {
  16282. this.checkInputs = function () { };
  16283. for (var cam in this.attached) {
  16284. var input = this.attached[cam];
  16285. if (input.checkInputs) {
  16286. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16287. }
  16288. }
  16289. };
  16290. CameraInputsManager.prototype.clear = function () {
  16291. if (this.attachedElement) {
  16292. this.detachElement(this.attachedElement);
  16293. }
  16294. this.attached = {};
  16295. this.attachedElement = null;
  16296. this.checkInputs = function () { };
  16297. };
  16298. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  16299. var inputs = {};
  16300. for (var cam in this.attached) {
  16301. var input = this.attached[cam];
  16302. var res = BABYLON.SerializationHelper.Serialize(input);
  16303. inputs[input.getTypeName()] = res;
  16304. }
  16305. serializedCamera.inputsmgr = inputs;
  16306. };
  16307. CameraInputsManager.prototype.parse = function (parsedCamera) {
  16308. var parsedInputs = parsedCamera.inputsmgr;
  16309. if (parsedInputs) {
  16310. this.clear();
  16311. for (var n in parsedInputs) {
  16312. var construct = BABYLON.CameraInputTypes[n];
  16313. if (construct) {
  16314. var parsedinput = parsedInputs[n];
  16315. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  16316. this.add(input);
  16317. }
  16318. }
  16319. }
  16320. else {
  16321. //2016-03-08 this part is for managing backward compatibility
  16322. for (var n in this.attached) {
  16323. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  16324. if (construct) {
  16325. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  16326. this.remove(this.attached[n]);
  16327. this.add(input);
  16328. }
  16329. }
  16330. }
  16331. };
  16332. return CameraInputsManager;
  16333. }());
  16334. BABYLON.CameraInputsManager = CameraInputsManager;
  16335. })(BABYLON || (BABYLON = {}));
  16336. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  16337. var BABYLON;
  16338. (function (BABYLON) {
  16339. var FreeCameraMouseInput = (function () {
  16340. function FreeCameraMouseInput(touchEnabled) {
  16341. if (touchEnabled === void 0) { touchEnabled = true; }
  16342. this.touchEnabled = touchEnabled;
  16343. this.buttons = [0, 1, 2];
  16344. this.angularSensibility = 2000.0;
  16345. }
  16346. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  16347. var _this = this;
  16348. var engine = this.camera.getEngine();
  16349. if (!this._pointerInput) {
  16350. this._pointerInput = function (p, s) {
  16351. var evt = p.event;
  16352. if (!_this.touchEnabled && evt.pointerType === "touch") {
  16353. return;
  16354. }
  16355. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  16356. return;
  16357. }
  16358. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16359. try {
  16360. evt.srcElement.setPointerCapture(evt.pointerId);
  16361. }
  16362. catch (e) {
  16363. }
  16364. _this.previousPosition = {
  16365. x: evt.clientX,
  16366. y: evt.clientY
  16367. };
  16368. if (!noPreventDefault) {
  16369. evt.preventDefault();
  16370. element.focus();
  16371. }
  16372. }
  16373. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16374. try {
  16375. evt.srcElement.releasePointerCapture(evt.pointerId);
  16376. }
  16377. catch (e) {
  16378. }
  16379. _this.previousPosition = null;
  16380. if (!noPreventDefault) {
  16381. evt.preventDefault();
  16382. }
  16383. }
  16384. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16385. if (!_this.previousPosition || engine.isPointerLock) {
  16386. return;
  16387. }
  16388. var offsetX = evt.clientX - _this.previousPosition.x;
  16389. var offsetY = evt.clientY - _this.previousPosition.y;
  16390. if (_this.camera.getScene().useRightHandedSystem) {
  16391. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16392. }
  16393. else {
  16394. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16395. }
  16396. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16397. _this.previousPosition = {
  16398. x: evt.clientX,
  16399. y: evt.clientY
  16400. };
  16401. if (!noPreventDefault) {
  16402. evt.preventDefault();
  16403. }
  16404. }
  16405. };
  16406. }
  16407. this._onMouseMove = function (evt) {
  16408. if (!engine.isPointerLock) {
  16409. return;
  16410. }
  16411. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  16412. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  16413. if (_this.camera.getScene().useRightHandedSystem) {
  16414. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16415. }
  16416. else {
  16417. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16418. }
  16419. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16420. _this.previousPosition = null;
  16421. if (!noPreventDefault) {
  16422. evt.preventDefault();
  16423. }
  16424. };
  16425. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16426. element.addEventListener("mousemove", this._onMouseMove, false);
  16427. };
  16428. FreeCameraMouseInput.prototype.detachControl = function (element) {
  16429. if (this._observer && element) {
  16430. this.camera.getScene().onPointerObservable.remove(this._observer);
  16431. element.removeEventListener("mousemove", this._onMouseMove);
  16432. this._observer = null;
  16433. this._onMouseMove = null;
  16434. this.previousPosition = null;
  16435. }
  16436. };
  16437. FreeCameraMouseInput.prototype.getTypeName = function () {
  16438. return "FreeCameraMouseInput";
  16439. };
  16440. FreeCameraMouseInput.prototype.getSimpleName = function () {
  16441. return "mouse";
  16442. };
  16443. return FreeCameraMouseInput;
  16444. }());
  16445. __decorate([
  16446. BABYLON.serialize()
  16447. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  16448. __decorate([
  16449. BABYLON.serialize()
  16450. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  16451. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  16452. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  16453. })(BABYLON || (BABYLON = {}));
  16454. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  16455. var BABYLON;
  16456. (function (BABYLON) {
  16457. var FreeCameraKeyboardMoveInput = (function () {
  16458. function FreeCameraKeyboardMoveInput() {
  16459. this._keys = [];
  16460. this.keysUp = [38];
  16461. this.keysDown = [40];
  16462. this.keysLeft = [37];
  16463. this.keysRight = [39];
  16464. }
  16465. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  16466. var _this = this;
  16467. if (!this._onKeyDown) {
  16468. element.tabIndex = 1;
  16469. this._onKeyDown = function (evt) {
  16470. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16471. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16472. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16473. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16474. var index = _this._keys.indexOf(evt.keyCode);
  16475. if (index === -1) {
  16476. _this._keys.push(evt.keyCode);
  16477. }
  16478. if (!noPreventDefault) {
  16479. evt.preventDefault();
  16480. }
  16481. }
  16482. };
  16483. this._onKeyUp = function (evt) {
  16484. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16485. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16486. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16487. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16488. var index = _this._keys.indexOf(evt.keyCode);
  16489. if (index >= 0) {
  16490. _this._keys.splice(index, 1);
  16491. }
  16492. if (!noPreventDefault) {
  16493. evt.preventDefault();
  16494. }
  16495. }
  16496. };
  16497. element.addEventListener("keydown", this._onKeyDown, false);
  16498. element.addEventListener("keyup", this._onKeyUp, false);
  16499. BABYLON.Tools.RegisterTopRootEvents([
  16500. { name: "blur", handler: this._onLostFocus }
  16501. ]);
  16502. }
  16503. };
  16504. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  16505. if (this._onKeyDown) {
  16506. element.removeEventListener("keydown", this._onKeyDown);
  16507. element.removeEventListener("keyup", this._onKeyUp);
  16508. BABYLON.Tools.UnregisterTopRootEvents([
  16509. { name: "blur", handler: this._onLostFocus }
  16510. ]);
  16511. this._keys = [];
  16512. this._onKeyDown = null;
  16513. this._onKeyUp = null;
  16514. }
  16515. };
  16516. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  16517. if (this._onKeyDown) {
  16518. var camera = this.camera;
  16519. // Keyboard
  16520. for (var index = 0; index < this._keys.length; index++) {
  16521. var keyCode = this._keys[index];
  16522. var speed = camera._computeLocalCameraSpeed();
  16523. if (this.keysLeft.indexOf(keyCode) !== -1) {
  16524. camera._localDirection.copyFromFloats(-speed, 0, 0);
  16525. }
  16526. else if (this.keysUp.indexOf(keyCode) !== -1) {
  16527. camera._localDirection.copyFromFloats(0, 0, speed);
  16528. }
  16529. else if (this.keysRight.indexOf(keyCode) !== -1) {
  16530. camera._localDirection.copyFromFloats(speed, 0, 0);
  16531. }
  16532. else if (this.keysDown.indexOf(keyCode) !== -1) {
  16533. camera._localDirection.copyFromFloats(0, 0, -speed);
  16534. }
  16535. if (camera.getScene().useRightHandedSystem) {
  16536. camera._localDirection.z *= -1;
  16537. }
  16538. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  16539. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  16540. camera.cameraDirection.addInPlace(camera._transformedDirection);
  16541. }
  16542. }
  16543. };
  16544. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  16545. return "FreeCameraKeyboardMoveInput";
  16546. };
  16547. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  16548. this._keys = [];
  16549. };
  16550. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  16551. return "keyboard";
  16552. };
  16553. return FreeCameraKeyboardMoveInput;
  16554. }());
  16555. __decorate([
  16556. BABYLON.serialize()
  16557. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  16558. __decorate([
  16559. BABYLON.serialize()
  16560. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  16561. __decorate([
  16562. BABYLON.serialize()
  16563. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  16564. __decorate([
  16565. BABYLON.serialize()
  16566. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  16567. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  16568. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  16569. })(BABYLON || (BABYLON = {}));
  16570. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  16571. var BABYLON;
  16572. (function (BABYLON) {
  16573. var FreeCameraTouchInput = (function () {
  16574. function FreeCameraTouchInput() {
  16575. this._offsetX = null;
  16576. this._offsetY = null;
  16577. this._pointerCount = 0;
  16578. this._pointerPressed = [];
  16579. this.touchAngularSensibility = 200000.0;
  16580. this.touchMoveSensibility = 250.0;
  16581. }
  16582. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  16583. var _this = this;
  16584. var previousPosition;
  16585. if (this._pointerInput === undefined) {
  16586. this._onLostFocus = function (evt) {
  16587. _this._offsetX = null;
  16588. _this._offsetY = null;
  16589. };
  16590. this._pointerInput = function (p, s) {
  16591. var evt = p.event;
  16592. if (evt.pointerType === "mouse") {
  16593. return;
  16594. }
  16595. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16596. if (!noPreventDefault) {
  16597. evt.preventDefault();
  16598. }
  16599. _this._pointerPressed.push(evt.pointerId);
  16600. if (_this._pointerPressed.length !== 1) {
  16601. return;
  16602. }
  16603. previousPosition = {
  16604. x: evt.clientX,
  16605. y: evt.clientY
  16606. };
  16607. }
  16608. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16609. if (!noPreventDefault) {
  16610. evt.preventDefault();
  16611. }
  16612. var index = _this._pointerPressed.indexOf(evt.pointerId);
  16613. if (index === -1) {
  16614. return;
  16615. }
  16616. _this._pointerPressed.splice(index, 1);
  16617. if (index != 0) {
  16618. return;
  16619. }
  16620. previousPosition = null;
  16621. _this._offsetX = null;
  16622. _this._offsetY = null;
  16623. }
  16624. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16625. if (!noPreventDefault) {
  16626. evt.preventDefault();
  16627. }
  16628. if (!previousPosition) {
  16629. return;
  16630. }
  16631. var index = _this._pointerPressed.indexOf(evt.pointerId);
  16632. if (index != 0) {
  16633. return;
  16634. }
  16635. _this._offsetX = evt.clientX - previousPosition.x;
  16636. _this._offsetY = -(evt.clientY - previousPosition.y);
  16637. }
  16638. };
  16639. }
  16640. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16641. element.addEventListener("blur", this._onLostFocus);
  16642. };
  16643. FreeCameraTouchInput.prototype.detachControl = function (element) {
  16644. if (this._pointerInput && element) {
  16645. this.camera.getScene().onPointerObservable.remove(this._observer);
  16646. this._observer = null;
  16647. element.removeEventListener("blur", this._onLostFocus);
  16648. this._onLostFocus = null;
  16649. this._pointerPressed = [];
  16650. this._offsetX = null;
  16651. this._offsetY = null;
  16652. this._pointerCount = 0;
  16653. }
  16654. };
  16655. FreeCameraTouchInput.prototype.checkInputs = function () {
  16656. if (this._offsetX) {
  16657. var camera = this.camera;
  16658. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  16659. if (this._pointerPressed.length > 1) {
  16660. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  16661. }
  16662. else {
  16663. var speed = camera._computeLocalCameraSpeed();
  16664. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  16665. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  16666. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  16667. }
  16668. }
  16669. };
  16670. FreeCameraTouchInput.prototype.getTypeName = function () {
  16671. return "FreeCameraTouchInput";
  16672. };
  16673. FreeCameraTouchInput.prototype.getSimpleName = function () {
  16674. return "touch";
  16675. };
  16676. return FreeCameraTouchInput;
  16677. }());
  16678. __decorate([
  16679. BABYLON.serialize()
  16680. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  16681. __decorate([
  16682. BABYLON.serialize()
  16683. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  16684. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  16685. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  16686. })(BABYLON || (BABYLON = {}));
  16687. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  16688. var BABYLON;
  16689. (function (BABYLON) {
  16690. var FreeCameraDeviceOrientationInput = (function () {
  16691. function FreeCameraDeviceOrientationInput() {
  16692. var _this = this;
  16693. this._screenOrientationAngle = 0;
  16694. this._screenQuaternion = new BABYLON.Quaternion();
  16695. this._alpha = 0;
  16696. this._beta = 0;
  16697. this._gamma = 0;
  16698. this._orientationChanged = function () {
  16699. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  16700. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  16701. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  16702. };
  16703. this._deviceOrientation = function (evt) {
  16704. _this._alpha = evt.alpha;
  16705. _this._beta = evt.beta;
  16706. _this._gamma = evt.gamma;
  16707. };
  16708. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  16709. this._orientationChanged();
  16710. }
  16711. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  16712. get: function () {
  16713. return this._camera;
  16714. },
  16715. set: function (camera) {
  16716. this._camera = camera;
  16717. if (!this._camera.rotationQuaternion)
  16718. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  16719. },
  16720. enumerable: true,
  16721. configurable: true
  16722. });
  16723. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  16724. window.addEventListener("orientationchange", this._orientationChanged);
  16725. window.addEventListener("deviceorientation", this._deviceOrientation);
  16726. //In certain cases, the attach control is called AFTER orientation was changed,
  16727. //So this is needed.
  16728. this._orientationChanged();
  16729. };
  16730. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  16731. window.removeEventListener("orientationchange", this._orientationChanged);
  16732. window.removeEventListener("deviceorientation", this._deviceOrientation);
  16733. };
  16734. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  16735. //if no device orientation provided, don't update the rotation.
  16736. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  16737. if (!this._alpha)
  16738. return;
  16739. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  16740. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  16741. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  16742. //Mirror on XY Plane
  16743. this._camera.rotationQuaternion.z *= -1;
  16744. this._camera.rotationQuaternion.w *= -1;
  16745. };
  16746. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  16747. return "FreeCameraDeviceOrientationInput";
  16748. };
  16749. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  16750. return "deviceOrientation";
  16751. };
  16752. return FreeCameraDeviceOrientationInput;
  16753. }());
  16754. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  16755. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  16756. })(BABYLON || (BABYLON = {}));
  16757. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  16758. var BABYLON;
  16759. (function (BABYLON) {
  16760. var FreeCameraGamepadInput = (function () {
  16761. function FreeCameraGamepadInput() {
  16762. this.gamepadAngularSensibility = 200;
  16763. this.gamepadMoveSensibility = 40;
  16764. }
  16765. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  16766. var _this = this;
  16767. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  16768. };
  16769. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  16770. if (this._gamepads) {
  16771. this._gamepads.dispose();
  16772. }
  16773. this.gamepad = null;
  16774. };
  16775. FreeCameraGamepadInput.prototype.checkInputs = function () {
  16776. if (this.gamepad) {
  16777. var camera = this.camera;
  16778. var LSValues = this.gamepad.leftStick;
  16779. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  16780. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  16781. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  16782. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  16783. var RSValues = this.gamepad.rightStick;
  16784. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  16785. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  16786. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  16787. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  16788. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  16789. var speed = camera._computeLocalCameraSpeed() * 50.0;
  16790. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  16791. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  16792. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  16793. }
  16794. };
  16795. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  16796. // Only the first gamepad can control the camera
  16797. if (gamepad.index === 0) {
  16798. this.gamepad = gamepad;
  16799. }
  16800. };
  16801. FreeCameraGamepadInput.prototype.getTypeName = function () {
  16802. return "FreeCameraGamepadInput";
  16803. };
  16804. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  16805. return "gamepad";
  16806. };
  16807. return FreeCameraGamepadInput;
  16808. }());
  16809. __decorate([
  16810. BABYLON.serialize()
  16811. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  16812. __decorate([
  16813. BABYLON.serialize()
  16814. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  16815. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  16816. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  16817. })(BABYLON || (BABYLON = {}));
  16818. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  16819. var BABYLON;
  16820. (function (BABYLON) {
  16821. var ArcRotateCameraKeyboardMoveInput = (function () {
  16822. function ArcRotateCameraKeyboardMoveInput() {
  16823. this._keys = [];
  16824. this.keysUp = [38];
  16825. this.keysDown = [40];
  16826. this.keysLeft = [37];
  16827. this.keysRight = [39];
  16828. }
  16829. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  16830. var _this = this;
  16831. element.tabIndex = 1;
  16832. this._onKeyDown = function (evt) {
  16833. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16834. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16835. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16836. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16837. var index = _this._keys.indexOf(evt.keyCode);
  16838. if (index === -1) {
  16839. _this._keys.push(evt.keyCode);
  16840. }
  16841. if (evt.preventDefault) {
  16842. if (!noPreventDefault) {
  16843. evt.preventDefault();
  16844. }
  16845. }
  16846. }
  16847. };
  16848. this._onKeyUp = function (evt) {
  16849. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16850. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16851. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16852. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16853. var index = _this._keys.indexOf(evt.keyCode);
  16854. if (index >= 0) {
  16855. _this._keys.splice(index, 1);
  16856. }
  16857. if (evt.preventDefault) {
  16858. if (!noPreventDefault) {
  16859. evt.preventDefault();
  16860. }
  16861. }
  16862. }
  16863. };
  16864. this._onLostFocus = function () {
  16865. _this._keys = [];
  16866. };
  16867. element.addEventListener("keydown", this._onKeyDown, false);
  16868. element.addEventListener("keyup", this._onKeyUp, false);
  16869. BABYLON.Tools.RegisterTopRootEvents([
  16870. { name: "blur", handler: this._onLostFocus }
  16871. ]);
  16872. };
  16873. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  16874. if (element) {
  16875. element.removeEventListener("keydown", this._onKeyDown);
  16876. element.removeEventListener("keyup", this._onKeyUp);
  16877. }
  16878. BABYLON.Tools.UnregisterTopRootEvents([
  16879. { name: "blur", handler: this._onLostFocus }
  16880. ]);
  16881. this._keys = [];
  16882. this._onKeyDown = null;
  16883. this._onKeyUp = null;
  16884. this._onLostFocus = null;
  16885. };
  16886. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  16887. if (this._onKeyDown) {
  16888. var camera = this.camera;
  16889. for (var index = 0; index < this._keys.length; index++) {
  16890. var keyCode = this._keys[index];
  16891. if (this.keysLeft.indexOf(keyCode) !== -1) {
  16892. camera.inertialAlphaOffset -= 0.01;
  16893. }
  16894. else if (this.keysUp.indexOf(keyCode) !== -1) {
  16895. camera.inertialBetaOffset -= 0.01;
  16896. }
  16897. else if (this.keysRight.indexOf(keyCode) !== -1) {
  16898. camera.inertialAlphaOffset += 0.01;
  16899. }
  16900. else if (this.keysDown.indexOf(keyCode) !== -1) {
  16901. camera.inertialBetaOffset += 0.01;
  16902. }
  16903. }
  16904. }
  16905. };
  16906. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  16907. return "ArcRotateCameraKeyboardMoveInput";
  16908. };
  16909. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  16910. return "keyboard";
  16911. };
  16912. return ArcRotateCameraKeyboardMoveInput;
  16913. }());
  16914. __decorate([
  16915. BABYLON.serialize()
  16916. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  16917. __decorate([
  16918. BABYLON.serialize()
  16919. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  16920. __decorate([
  16921. BABYLON.serialize()
  16922. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  16923. __decorate([
  16924. BABYLON.serialize()
  16925. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  16926. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  16927. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  16928. })(BABYLON || (BABYLON = {}));
  16929. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  16930. var BABYLON;
  16931. (function (BABYLON) {
  16932. var ArcRotateCameraMouseWheelInput = (function () {
  16933. function ArcRotateCameraMouseWheelInput() {
  16934. this.wheelPrecision = 3.0;
  16935. }
  16936. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  16937. var _this = this;
  16938. this._wheel = function (p, s) {
  16939. //sanity check - this should be a PointerWheel event.
  16940. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  16941. return;
  16942. var event = p.event;
  16943. var delta = 0;
  16944. if (event.wheelDelta) {
  16945. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  16946. }
  16947. else if (event.detail) {
  16948. delta = -event.detail / _this.wheelPrecision;
  16949. }
  16950. if (delta)
  16951. _this.camera.inertialRadiusOffset += delta;
  16952. if (event.preventDefault) {
  16953. if (!noPreventDefault) {
  16954. event.preventDefault();
  16955. }
  16956. }
  16957. };
  16958. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  16959. };
  16960. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  16961. if (this._observer && element) {
  16962. this.camera.getScene().onPointerObservable.remove(this._observer);
  16963. this._observer = null;
  16964. this._wheel = null;
  16965. }
  16966. };
  16967. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  16968. return "ArcRotateCameraMouseWheelInput";
  16969. };
  16970. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  16971. return "mousewheel";
  16972. };
  16973. return ArcRotateCameraMouseWheelInput;
  16974. }());
  16975. __decorate([
  16976. BABYLON.serialize()
  16977. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  16978. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  16979. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  16980. })(BABYLON || (BABYLON = {}));
  16981. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  16982. var BABYLON;
  16983. (function (BABYLON) {
  16984. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16985. var ArcRotateCameraPointersInput = (function () {
  16986. function ArcRotateCameraPointersInput() {
  16987. this.buttons = [0, 1, 2];
  16988. this.angularSensibilityX = 1000.0;
  16989. this.angularSensibilityY = 1000.0;
  16990. this.pinchPrecision = 6.0;
  16991. this.panningSensibility = 50.0;
  16992. this._isPanClick = false;
  16993. this.pinchInwards = true;
  16994. }
  16995. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  16996. var _this = this;
  16997. var engine = this.camera.getEngine();
  16998. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  16999. var pointA, pointB;
  17000. var previousPinchDistance = 0;
  17001. this._pointerInput = function (p, s) {
  17002. var evt = p.event;
  17003. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  17004. return;
  17005. }
  17006. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  17007. try {
  17008. evt.srcElement.setPointerCapture(evt.pointerId);
  17009. }
  17010. catch (e) {
  17011. }
  17012. // Manage panning with pan button click
  17013. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  17014. // manage pointers
  17015. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  17016. if (pointA === undefined) {
  17017. pointA = cacheSoloPointer;
  17018. }
  17019. else if (pointB === undefined) {
  17020. pointB = cacheSoloPointer;
  17021. }
  17022. if (!noPreventDefault) {
  17023. evt.preventDefault();
  17024. element.focus();
  17025. }
  17026. }
  17027. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  17028. try {
  17029. evt.srcElement.releasePointerCapture(evt.pointerId);
  17030. }
  17031. catch (e) {
  17032. }
  17033. cacheSoloPointer = null;
  17034. previousPinchDistance = 0;
  17035. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  17036. //but emptying completly pointers collection is required to fix a bug on iPhone :
  17037. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  17038. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  17039. pointA = pointB = undefined;
  17040. if (!noPreventDefault) {
  17041. evt.preventDefault();
  17042. }
  17043. }
  17044. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  17045. if (!noPreventDefault) {
  17046. evt.preventDefault();
  17047. }
  17048. // One button down
  17049. if (pointA && pointB === undefined) {
  17050. if (_this.panningSensibility !== 0 &&
  17051. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  17052. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  17053. _this.camera
  17054. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  17055. _this.camera
  17056. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  17057. }
  17058. else {
  17059. var offsetX = evt.clientX - cacheSoloPointer.x;
  17060. var offsetY = evt.clientY - cacheSoloPointer.y;
  17061. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17062. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17063. }
  17064. cacheSoloPointer.x = evt.clientX;
  17065. cacheSoloPointer.y = evt.clientY;
  17066. }
  17067. else if (pointA && pointB) {
  17068. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  17069. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  17070. ed.x = evt.clientX;
  17071. ed.y = evt.clientY;
  17072. var direction = _this.pinchInwards ? 1 : -1;
  17073. var distX = pointA.x - pointB.x;
  17074. var distY = pointA.y - pointB.y;
  17075. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  17076. if (previousPinchDistance === 0) {
  17077. previousPinchDistance = pinchSquaredDistance;
  17078. return;
  17079. }
  17080. if (pinchSquaredDistance !== previousPinchDistance) {
  17081. _this.camera
  17082. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  17083. (_this.pinchPrecision *
  17084. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  17085. direction);
  17086. previousPinchDistance = pinchSquaredDistance;
  17087. }
  17088. }
  17089. }
  17090. };
  17091. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  17092. this._onContextMenu = function (evt) {
  17093. evt.preventDefault();
  17094. };
  17095. if (!this.camera._useCtrlForPanning) {
  17096. element.addEventListener("contextmenu", this._onContextMenu, false);
  17097. }
  17098. this._onLostFocus = function () {
  17099. //this._keys = [];
  17100. pointA = pointB = undefined;
  17101. previousPinchDistance = 0;
  17102. cacheSoloPointer = null;
  17103. };
  17104. this._onMouseMove = function (evt) {
  17105. if (!engine.isPointerLock) {
  17106. return;
  17107. }
  17108. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  17109. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  17110. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17111. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17112. if (!noPreventDefault) {
  17113. evt.preventDefault();
  17114. }
  17115. };
  17116. this._onGestureStart = function (e) {
  17117. if (window.MSGesture === undefined) {
  17118. return;
  17119. }
  17120. if (!_this._MSGestureHandler) {
  17121. _this._MSGestureHandler = new MSGesture();
  17122. _this._MSGestureHandler.target = element;
  17123. }
  17124. _this._MSGestureHandler.addPointer(e.pointerId);
  17125. };
  17126. this._onGesture = function (e) {
  17127. _this.camera.radius *= e.scale;
  17128. if (e.preventDefault) {
  17129. if (!noPreventDefault) {
  17130. e.stopPropagation();
  17131. e.preventDefault();
  17132. }
  17133. }
  17134. };
  17135. element.addEventListener("mousemove", this._onMouseMove, false);
  17136. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  17137. element.addEventListener("MSGestureChange", this._onGesture, false);
  17138. element.addEventListener("keydown", this._onKeyDown, false);
  17139. element.addEventListener("keyup", this._onKeyUp, false);
  17140. BABYLON.Tools.RegisterTopRootEvents([
  17141. { name: "blur", handler: this._onLostFocus }
  17142. ]);
  17143. };
  17144. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  17145. if (element && this._observer) {
  17146. this.camera.getScene().onPointerObservable.remove(this._observer);
  17147. this._observer = null;
  17148. element.removeEventListener("contextmenu", this._onContextMenu);
  17149. element.removeEventListener("mousemove", this._onMouseMove);
  17150. element.removeEventListener("MSPointerDown", this._onGestureStart);
  17151. element.removeEventListener("MSGestureChange", this._onGesture);
  17152. element.removeEventListener("keydown", this._onKeyDown);
  17153. element.removeEventListener("keyup", this._onKeyUp);
  17154. this._isPanClick = false;
  17155. this.pinchInwards = true;
  17156. this._onKeyDown = null;
  17157. this._onKeyUp = null;
  17158. this._onMouseMove = null;
  17159. this._onGestureStart = null;
  17160. this._onGesture = null;
  17161. this._MSGestureHandler = null;
  17162. this._onLostFocus = null;
  17163. this._onContextMenu = null;
  17164. }
  17165. BABYLON.Tools.UnregisterTopRootEvents([
  17166. { name: "blur", handler: this._onLostFocus }
  17167. ]);
  17168. };
  17169. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  17170. return "ArcRotateCameraPointersInput";
  17171. };
  17172. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  17173. return "pointers";
  17174. };
  17175. return ArcRotateCameraPointersInput;
  17176. }());
  17177. __decorate([
  17178. BABYLON.serialize()
  17179. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  17180. __decorate([
  17181. BABYLON.serialize()
  17182. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  17183. __decorate([
  17184. BABYLON.serialize()
  17185. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  17186. __decorate([
  17187. BABYLON.serialize()
  17188. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  17189. __decorate([
  17190. BABYLON.serialize()
  17191. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  17192. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  17193. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  17194. })(BABYLON || (BABYLON = {}));
  17195. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  17196. var BABYLON;
  17197. (function (BABYLON) {
  17198. var ArcRotateCameraGamepadInput = (function () {
  17199. function ArcRotateCameraGamepadInput() {
  17200. this.gamepadRotationSensibility = 80;
  17201. this.gamepadMoveSensibility = 40;
  17202. }
  17203. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  17204. var _this = this;
  17205. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  17206. };
  17207. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  17208. if (this._gamepads) {
  17209. this._gamepads.dispose();
  17210. }
  17211. this.gamepad = null;
  17212. };
  17213. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  17214. if (this.gamepad) {
  17215. var camera = this.camera;
  17216. var RSValues = this.gamepad.rightStick;
  17217. if (RSValues.x != 0) {
  17218. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  17219. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  17220. camera.inertialAlphaOffset += normalizedRX;
  17221. }
  17222. }
  17223. if (RSValues.y != 0) {
  17224. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  17225. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  17226. camera.inertialBetaOffset += normalizedRY;
  17227. }
  17228. }
  17229. var LSValues = this.gamepad.leftStick;
  17230. if (LSValues.y != 0) {
  17231. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  17232. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  17233. this.camera.inertialRadiusOffset -= normalizedLY;
  17234. }
  17235. }
  17236. }
  17237. };
  17238. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  17239. // Only the first gamepad can control the camera
  17240. if (gamepad.index === 0) {
  17241. this.gamepad = gamepad;
  17242. }
  17243. };
  17244. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  17245. return "ArcRotateCameraGamepadInput";
  17246. };
  17247. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  17248. return "gamepad";
  17249. };
  17250. return ArcRotateCameraGamepadInput;
  17251. }());
  17252. __decorate([
  17253. BABYLON.serialize()
  17254. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  17255. __decorate([
  17256. BABYLON.serialize()
  17257. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17258. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  17259. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  17260. })(BABYLON || (BABYLON = {}));
  17261. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  17262. var BABYLON;
  17263. (function (BABYLON) {
  17264. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  17265. function ArcRotateCameraVRDeviceOrientationInput() {
  17266. this.alphaCorrection = 1;
  17267. this.betaCorrection = 1;
  17268. this.gammaCorrection = 1;
  17269. this._alpha = 0;
  17270. this._beta = 0;
  17271. this._gamma = 0;
  17272. this._dirty = false;
  17273. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17274. }
  17275. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  17276. this.camera.attachControl(element, noPreventDefault);
  17277. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17278. };
  17279. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  17280. var camera = this.camera;
  17281. this._alpha = +evt.alpha | 0;
  17282. this._beta = +evt.beta | 0;
  17283. this._gamma = +evt.gamma | 0;
  17284. this._dirty = true;
  17285. };
  17286. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  17287. if (this._dirty) {
  17288. this._dirty = false;
  17289. if (this._gamma < 0) {
  17290. this._gamma = 180 + this._gamma;
  17291. }
  17292. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  17293. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  17294. }
  17295. };
  17296. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  17297. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17298. };
  17299. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  17300. return "ArcRotateCameraVRDeviceOrientationInput";
  17301. };
  17302. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  17303. return "VRDeviceOrientation";
  17304. };
  17305. return ArcRotateCameraVRDeviceOrientationInput;
  17306. }());
  17307. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  17308. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  17309. })(BABYLON || (BABYLON = {}));
  17310. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  17311. /// <reference path="babylon.camera.ts" />
  17312. var BABYLON;
  17313. (function (BABYLON) {
  17314. var TargetCamera = (function (_super) {
  17315. __extends(TargetCamera, _super);
  17316. function TargetCamera(name, position, scene) {
  17317. var _this = _super.call(this, name, position, scene) || this;
  17318. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17319. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  17320. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  17321. _this.speed = 2.0;
  17322. _this.noRotationConstraint = false;
  17323. _this.lockedTarget = null;
  17324. _this._currentTarget = BABYLON.Vector3.Zero();
  17325. _this._viewMatrix = BABYLON.Matrix.Zero();
  17326. _this._camMatrix = BABYLON.Matrix.Zero();
  17327. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  17328. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  17329. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  17330. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  17331. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  17332. _this._lookAtTemp = BABYLON.Matrix.Zero();
  17333. _this._tempMatrix = BABYLON.Matrix.Zero();
  17334. return _this;
  17335. }
  17336. TargetCamera.prototype.getFrontPosition = function (distance) {
  17337. var direction = this.getTarget().subtract(this.position);
  17338. direction.normalize();
  17339. direction.scaleInPlace(distance);
  17340. return this.globalPosition.add(direction);
  17341. };
  17342. TargetCamera.prototype._getLockedTargetPosition = function () {
  17343. if (!this.lockedTarget) {
  17344. return null;
  17345. }
  17346. if (this.lockedTarget.absolutePosition) {
  17347. this.lockedTarget.computeWorldMatrix();
  17348. }
  17349. return this.lockedTarget.absolutePosition || this.lockedTarget;
  17350. };
  17351. // Cache
  17352. TargetCamera.prototype._initCache = function () {
  17353. _super.prototype._initCache.call(this);
  17354. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17355. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17356. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17357. };
  17358. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  17359. if (!ignoreParentClass) {
  17360. _super.prototype._updateCache.call(this);
  17361. }
  17362. var lockedTargetPosition = this._getLockedTargetPosition();
  17363. if (!lockedTargetPosition) {
  17364. this._cache.lockedTarget = null;
  17365. }
  17366. else {
  17367. if (!this._cache.lockedTarget) {
  17368. this._cache.lockedTarget = lockedTargetPosition.clone();
  17369. }
  17370. else {
  17371. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  17372. }
  17373. }
  17374. this._cache.rotation.copyFrom(this.rotation);
  17375. if (this.rotationQuaternion)
  17376. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17377. };
  17378. // Synchronized
  17379. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  17380. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  17381. return false;
  17382. }
  17383. var lockedTargetPosition = this._getLockedTargetPosition();
  17384. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  17385. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  17386. };
  17387. // Methods
  17388. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  17389. var engine = this.getEngine();
  17390. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  17391. };
  17392. // Target
  17393. TargetCamera.prototype.setTarget = function (target) {
  17394. this.upVector.normalize();
  17395. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  17396. this._camMatrix.invert();
  17397. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  17398. var vDir = target.subtract(this.position);
  17399. if (vDir.x >= 0.0) {
  17400. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  17401. }
  17402. else {
  17403. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  17404. }
  17405. this.rotation.z = 0;
  17406. if (isNaN(this.rotation.x)) {
  17407. this.rotation.x = 0;
  17408. }
  17409. if (isNaN(this.rotation.y)) {
  17410. this.rotation.y = 0;
  17411. }
  17412. if (isNaN(this.rotation.z)) {
  17413. this.rotation.z = 0;
  17414. }
  17415. if (this.rotationQuaternion) {
  17416. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  17417. }
  17418. };
  17419. TargetCamera.prototype.getTarget = function () {
  17420. return this._currentTarget;
  17421. };
  17422. TargetCamera.prototype._decideIfNeedsToMove = function () {
  17423. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  17424. };
  17425. TargetCamera.prototype._updatePosition = function () {
  17426. this.position.addInPlace(this.cameraDirection);
  17427. };
  17428. TargetCamera.prototype._checkInputs = function () {
  17429. var needToMove = this._decideIfNeedsToMove();
  17430. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  17431. // Move
  17432. if (needToMove) {
  17433. this._updatePosition();
  17434. }
  17435. // Rotate
  17436. if (needToRotate) {
  17437. this.rotation.x += this.cameraRotation.x;
  17438. this.rotation.y += this.cameraRotation.y;
  17439. if (!this.noRotationConstraint) {
  17440. var limit = (Math.PI / 2) * 0.95;
  17441. if (this.rotation.x > limit)
  17442. this.rotation.x = limit;
  17443. if (this.rotation.x < -limit)
  17444. this.rotation.x = -limit;
  17445. }
  17446. }
  17447. // Inertia
  17448. if (needToMove) {
  17449. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  17450. this.cameraDirection.x = 0;
  17451. }
  17452. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  17453. this.cameraDirection.y = 0;
  17454. }
  17455. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  17456. this.cameraDirection.z = 0;
  17457. }
  17458. this.cameraDirection.scaleInPlace(this.inertia);
  17459. }
  17460. if (needToRotate) {
  17461. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  17462. this.cameraRotation.x = 0;
  17463. }
  17464. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  17465. this.cameraRotation.y = 0;
  17466. }
  17467. this.cameraRotation.scaleInPlace(this.inertia);
  17468. }
  17469. _super.prototype._checkInputs.call(this);
  17470. };
  17471. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  17472. if (this.rotationQuaternion) {
  17473. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  17474. //update the up vector!
  17475. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  17476. }
  17477. else {
  17478. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  17479. }
  17480. };
  17481. TargetCamera.prototype._getViewMatrix = function () {
  17482. if (!this.lockedTarget) {
  17483. // Compute
  17484. this._updateCameraRotationMatrix();
  17485. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  17486. // Computing target and final matrix
  17487. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  17488. }
  17489. else {
  17490. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  17491. }
  17492. if (this.getScene().useRightHandedSystem) {
  17493. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  17494. }
  17495. else {
  17496. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  17497. }
  17498. return this._viewMatrix;
  17499. };
  17500. /**
  17501. * @override
  17502. * Override Camera.createRigCamera
  17503. */
  17504. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  17505. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  17506. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  17507. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  17508. if (!this.rotationQuaternion) {
  17509. this.rotationQuaternion = new BABYLON.Quaternion();
  17510. }
  17511. rigCamera._cameraRigParams = {};
  17512. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  17513. }
  17514. return rigCamera;
  17515. }
  17516. return null;
  17517. };
  17518. /**
  17519. * @override
  17520. * Override Camera._updateRigCameras
  17521. */
  17522. TargetCamera.prototype._updateRigCameras = function () {
  17523. var camLeft = this._rigCameras[0];
  17524. var camRight = this._rigCameras[1];
  17525. switch (this.cameraRigMode) {
  17526. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  17527. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  17528. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  17529. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  17530. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  17531. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  17532. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  17533. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  17534. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  17535. camLeft.setTarget(this.getTarget());
  17536. camRight.setTarget(this.getTarget());
  17537. break;
  17538. case BABYLON.Camera.RIG_MODE_VR:
  17539. case BABYLON.Camera.RIG_MODE_WEBVR:
  17540. if (camLeft.rotationQuaternion) {
  17541. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17542. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17543. }
  17544. else {
  17545. camLeft.rotation.copyFrom(this.rotation);
  17546. camRight.rotation.copyFrom(this.rotation);
  17547. }
  17548. camLeft.position.copyFrom(this.position);
  17549. camRight.position.copyFrom(this.position);
  17550. break;
  17551. }
  17552. _super.prototype._updateRigCameras.call(this);
  17553. };
  17554. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  17555. if (!this._rigCamTransformMatrix) {
  17556. this._rigCamTransformMatrix = new BABYLON.Matrix();
  17557. }
  17558. var target = this.getTarget();
  17559. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  17560. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  17561. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  17562. };
  17563. TargetCamera.prototype.getClassName = function () {
  17564. return "TargetCamera";
  17565. };
  17566. return TargetCamera;
  17567. }(BABYLON.Camera));
  17568. __decorate([
  17569. BABYLON.serializeAsVector3()
  17570. ], TargetCamera.prototype, "rotation", void 0);
  17571. __decorate([
  17572. BABYLON.serialize()
  17573. ], TargetCamera.prototype, "speed", void 0);
  17574. __decorate([
  17575. BABYLON.serializeAsMeshReference("lockedTargetId")
  17576. ], TargetCamera.prototype, "lockedTarget", void 0);
  17577. BABYLON.TargetCamera = TargetCamera;
  17578. })(BABYLON || (BABYLON = {}));
  17579. //# sourceMappingURL=babylon.targetCamera.js.map
  17580. var BABYLON;
  17581. (function (BABYLON) {
  17582. var FreeCamera = (function (_super) {
  17583. __extends(FreeCamera, _super);
  17584. function FreeCamera(name, position, scene) {
  17585. var _this = _super.call(this, name, position, scene) || this;
  17586. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17587. _this.checkCollisions = false;
  17588. _this.applyGravity = false;
  17589. _this._collider = new BABYLON.Collider();
  17590. _this._needMoveForGravity = false;
  17591. _this._oldPosition = BABYLON.Vector3.Zero();
  17592. _this._diffPosition = BABYLON.Vector3.Zero();
  17593. _this._newPosition = BABYLON.Vector3.Zero();
  17594. // Collisions
  17595. _this._collisionMask = -1;
  17596. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17597. if (collidedMesh === void 0) { collidedMesh = null; }
  17598. //TODO move this to the collision coordinator!
  17599. if (_this.getScene().workerCollisions)
  17600. newPosition.multiplyInPlace(_this._collider.radius);
  17601. var updatePosition = function (newPos) {
  17602. _this._newPosition.copyFrom(newPos);
  17603. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  17604. var oldPosition = _this.position.clone();
  17605. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  17606. _this.position.addInPlace(_this._diffPosition);
  17607. if (_this.onCollide && collidedMesh) {
  17608. _this.onCollide(collidedMesh);
  17609. }
  17610. }
  17611. };
  17612. updatePosition(newPosition);
  17613. };
  17614. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  17615. _this.inputs.addKeyboard().addMouse();
  17616. return _this;
  17617. }
  17618. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  17619. //-- begin properties for backward compatibility for inputs
  17620. get: function () {
  17621. var mouse = this.inputs.attached["mouse"];
  17622. if (mouse)
  17623. return mouse.angularSensibility;
  17624. },
  17625. set: function (value) {
  17626. var mouse = this.inputs.attached["mouse"];
  17627. if (mouse)
  17628. mouse.angularSensibility = value;
  17629. },
  17630. enumerable: true,
  17631. configurable: true
  17632. });
  17633. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  17634. get: function () {
  17635. var keyboard = this.inputs.attached["keyboard"];
  17636. if (keyboard)
  17637. return keyboard.keysUp;
  17638. },
  17639. set: function (value) {
  17640. var keyboard = this.inputs.attached["keyboard"];
  17641. if (keyboard)
  17642. keyboard.keysUp = value;
  17643. },
  17644. enumerable: true,
  17645. configurable: true
  17646. });
  17647. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  17648. get: function () {
  17649. var keyboard = this.inputs.attached["keyboard"];
  17650. if (keyboard)
  17651. return keyboard.keysDown;
  17652. },
  17653. set: function (value) {
  17654. var keyboard = this.inputs.attached["keyboard"];
  17655. if (keyboard)
  17656. keyboard.keysDown = value;
  17657. },
  17658. enumerable: true,
  17659. configurable: true
  17660. });
  17661. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  17662. get: function () {
  17663. var keyboard = this.inputs.attached["keyboard"];
  17664. if (keyboard)
  17665. return keyboard.keysLeft;
  17666. },
  17667. set: function (value) {
  17668. var keyboard = this.inputs.attached["keyboard"];
  17669. if (keyboard)
  17670. keyboard.keysLeft = value;
  17671. },
  17672. enumerable: true,
  17673. configurable: true
  17674. });
  17675. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  17676. get: function () {
  17677. var keyboard = this.inputs.attached["keyboard"];
  17678. if (keyboard)
  17679. return keyboard.keysRight;
  17680. },
  17681. set: function (value) {
  17682. var keyboard = this.inputs.attached["keyboard"];
  17683. if (keyboard)
  17684. keyboard.keysRight = value;
  17685. },
  17686. enumerable: true,
  17687. configurable: true
  17688. });
  17689. // Controls
  17690. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  17691. this.inputs.attachElement(element, noPreventDefault);
  17692. };
  17693. FreeCamera.prototype.detachControl = function (element) {
  17694. this.inputs.detachElement(element);
  17695. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17696. this.cameraRotation = new BABYLON.Vector2(0, 0);
  17697. };
  17698. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  17699. get: function () {
  17700. return this._collisionMask;
  17701. },
  17702. set: function (mask) {
  17703. this._collisionMask = !isNaN(mask) ? mask : -1;
  17704. },
  17705. enumerable: true,
  17706. configurable: true
  17707. });
  17708. FreeCamera.prototype._collideWithWorld = function (velocity) {
  17709. var globalPosition;
  17710. if (this.parent) {
  17711. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  17712. }
  17713. else {
  17714. globalPosition = this.position;
  17715. }
  17716. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  17717. this._collider.radius = this.ellipsoid;
  17718. this._collider.collisionMask = this._collisionMask;
  17719. //no need for clone, as long as gravity is not on.
  17720. var actualVelocity = velocity;
  17721. //add gravity to the velocity to prevent the dual-collision checking
  17722. if (this.applyGravity) {
  17723. //this prevents mending with cameraDirection, a global variable of the free camera class.
  17724. actualVelocity = velocity.add(this.getScene().gravity);
  17725. }
  17726. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  17727. };
  17728. FreeCamera.prototype._checkInputs = function () {
  17729. if (!this._localDirection) {
  17730. this._localDirection = BABYLON.Vector3.Zero();
  17731. this._transformedDirection = BABYLON.Vector3.Zero();
  17732. }
  17733. this.inputs.checkInputs();
  17734. _super.prototype._checkInputs.call(this);
  17735. };
  17736. FreeCamera.prototype._decideIfNeedsToMove = function () {
  17737. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  17738. };
  17739. FreeCamera.prototype._updatePosition = function () {
  17740. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  17741. this._collideWithWorld(this.cameraDirection);
  17742. }
  17743. else {
  17744. this.position.addInPlace(this.cameraDirection);
  17745. }
  17746. };
  17747. FreeCamera.prototype.dispose = function () {
  17748. this.inputs.clear();
  17749. _super.prototype.dispose.call(this);
  17750. };
  17751. FreeCamera.prototype.getClassName = function () {
  17752. return "FreeCamera";
  17753. };
  17754. return FreeCamera;
  17755. }(BABYLON.TargetCamera));
  17756. __decorate([
  17757. BABYLON.serializeAsVector3()
  17758. ], FreeCamera.prototype, "ellipsoid", void 0);
  17759. __decorate([
  17760. BABYLON.serialize()
  17761. ], FreeCamera.prototype, "checkCollisions", void 0);
  17762. __decorate([
  17763. BABYLON.serialize()
  17764. ], FreeCamera.prototype, "applyGravity", void 0);
  17765. BABYLON.FreeCamera = FreeCamera;
  17766. })(BABYLON || (BABYLON = {}));
  17767. //# sourceMappingURL=babylon.freeCamera.js.map
  17768. var BABYLON;
  17769. (function (BABYLON) {
  17770. var FreeCameraInputsManager = (function (_super) {
  17771. __extends(FreeCameraInputsManager, _super);
  17772. function FreeCameraInputsManager(camera) {
  17773. return _super.call(this, camera) || this;
  17774. }
  17775. FreeCameraInputsManager.prototype.addKeyboard = function () {
  17776. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  17777. return this;
  17778. };
  17779. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  17780. if (touchEnabled === void 0) { touchEnabled = true; }
  17781. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  17782. return this;
  17783. };
  17784. FreeCameraInputsManager.prototype.addGamepad = function () {
  17785. this.add(new BABYLON.FreeCameraGamepadInput());
  17786. return this;
  17787. };
  17788. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  17789. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  17790. return this;
  17791. };
  17792. FreeCameraInputsManager.prototype.addTouch = function () {
  17793. this.add(new BABYLON.FreeCameraTouchInput());
  17794. return this;
  17795. };
  17796. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  17797. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  17798. return this;
  17799. };
  17800. return FreeCameraInputsManager;
  17801. }(BABYLON.CameraInputsManager));
  17802. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  17803. })(BABYLON || (BABYLON = {}));
  17804. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  17805. /// <reference path="babylon.targetCamera.ts" />
  17806. var BABYLON;
  17807. (function (BABYLON) {
  17808. var FollowCamera = (function (_super) {
  17809. __extends(FollowCamera, _super);
  17810. function FollowCamera(name, position, scene, lockedTarget) {
  17811. var _this = _super.call(this, name, position, scene) || this;
  17812. _this.radius = 12;
  17813. _this.rotationOffset = 0;
  17814. _this.heightOffset = 4;
  17815. _this.cameraAcceleration = 0.05;
  17816. _this.maxCameraSpeed = 20;
  17817. _this.lockedTarget = lockedTarget;
  17818. return _this;
  17819. }
  17820. FollowCamera.prototype.getRadians = function (degrees) {
  17821. return degrees * Math.PI / 180;
  17822. };
  17823. FollowCamera.prototype.follow = function (cameraTarget) {
  17824. if (!cameraTarget)
  17825. return;
  17826. var yRotation;
  17827. if (cameraTarget.rotationQuaternion) {
  17828. var rotMatrix = new BABYLON.Matrix();
  17829. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  17830. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  17831. }
  17832. else {
  17833. yRotation = cameraTarget.rotation.y;
  17834. }
  17835. var radians = this.getRadians(this.rotationOffset) + yRotation;
  17836. var targetPosition = cameraTarget.getAbsolutePosition();
  17837. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  17838. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  17839. var dx = targetX - this.position.x;
  17840. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  17841. var dz = (targetZ) - this.position.z;
  17842. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  17843. var vy = dy * this.cameraAcceleration;
  17844. var vz = dz * this.cameraAcceleration * 2;
  17845. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  17846. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  17847. }
  17848. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  17849. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  17850. }
  17851. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  17852. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  17853. }
  17854. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  17855. this.setTarget(targetPosition);
  17856. };
  17857. FollowCamera.prototype._checkInputs = function () {
  17858. _super.prototype._checkInputs.call(this);
  17859. this.follow(this.lockedTarget);
  17860. };
  17861. FollowCamera.prototype.getClassName = function () {
  17862. return "FollowCamera";
  17863. };
  17864. return FollowCamera;
  17865. }(BABYLON.TargetCamera));
  17866. __decorate([
  17867. BABYLON.serialize()
  17868. ], FollowCamera.prototype, "radius", void 0);
  17869. __decorate([
  17870. BABYLON.serialize()
  17871. ], FollowCamera.prototype, "rotationOffset", void 0);
  17872. __decorate([
  17873. BABYLON.serialize()
  17874. ], FollowCamera.prototype, "heightOffset", void 0);
  17875. __decorate([
  17876. BABYLON.serialize()
  17877. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  17878. __decorate([
  17879. BABYLON.serialize()
  17880. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  17881. __decorate([
  17882. BABYLON.serializeAsMeshReference("lockedTargetId")
  17883. ], FollowCamera.prototype, "lockedTarget", void 0);
  17884. BABYLON.FollowCamera = FollowCamera;
  17885. var ArcFollowCamera = (function (_super) {
  17886. __extends(ArcFollowCamera, _super);
  17887. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  17888. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  17889. _this.alpha = alpha;
  17890. _this.beta = beta;
  17891. _this.radius = radius;
  17892. _this.target = target;
  17893. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  17894. _this.follow();
  17895. return _this;
  17896. }
  17897. ArcFollowCamera.prototype.follow = function () {
  17898. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  17899. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  17900. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  17901. var targetPosition = this.target.getAbsolutePosition();
  17902. this.position = targetPosition.add(this._cartesianCoordinates);
  17903. this.setTarget(targetPosition);
  17904. };
  17905. ArcFollowCamera.prototype._checkInputs = function () {
  17906. _super.prototype._checkInputs.call(this);
  17907. this.follow();
  17908. };
  17909. ArcFollowCamera.prototype.getClassName = function () {
  17910. return "ArcFollowCamera";
  17911. };
  17912. return ArcFollowCamera;
  17913. }(BABYLON.TargetCamera));
  17914. BABYLON.ArcFollowCamera = ArcFollowCamera;
  17915. })(BABYLON || (BABYLON = {}));
  17916. //# sourceMappingURL=babylon.followCamera.js.map
  17917. /// <reference path="babylon.freeCamera.ts" />
  17918. var BABYLON;
  17919. (function (BABYLON) {
  17920. // We're mainly based on the logic defined into the FreeCamera code
  17921. var TouchCamera = (function (_super) {
  17922. __extends(TouchCamera, _super);
  17923. //-- end properties for backward compatibility for inputs
  17924. function TouchCamera(name, position, scene) {
  17925. var _this = _super.call(this, name, position, scene) || this;
  17926. _this.inputs.addTouch();
  17927. _this._setupInputs();
  17928. return _this;
  17929. }
  17930. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  17931. //-- Begin properties for backward compatibility for inputs
  17932. get: function () {
  17933. var touch = this.inputs.attached["touch"];
  17934. if (touch)
  17935. return touch.touchAngularSensibility;
  17936. },
  17937. set: function (value) {
  17938. var touch = this.inputs.attached["touch"];
  17939. if (touch)
  17940. touch.touchAngularSensibility = value;
  17941. },
  17942. enumerable: true,
  17943. configurable: true
  17944. });
  17945. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  17946. get: function () {
  17947. var touch = this.inputs.attached["touch"];
  17948. if (touch)
  17949. return touch.touchMoveSensibility;
  17950. },
  17951. set: function (value) {
  17952. var touch = this.inputs.attached["touch"];
  17953. if (touch)
  17954. touch.touchMoveSensibility = value;
  17955. },
  17956. enumerable: true,
  17957. configurable: true
  17958. });
  17959. TouchCamera.prototype.getClassName = function () {
  17960. return "TouchCamera";
  17961. };
  17962. TouchCamera.prototype._setupInputs = function () {
  17963. var mouse = this.inputs.attached["mouse"];
  17964. if (mouse) {
  17965. mouse.touchEnabled = false;
  17966. }
  17967. };
  17968. return TouchCamera;
  17969. }(BABYLON.FreeCamera));
  17970. BABYLON.TouchCamera = TouchCamera;
  17971. })(BABYLON || (BABYLON = {}));
  17972. //# sourceMappingURL=babylon.touchCamera.js.map
  17973. /// <reference path="babylon.targetCamera.ts" />
  17974. /// <reference path="..\Tools\babylon.tools.ts" />
  17975. var BABYLON;
  17976. (function (BABYLON) {
  17977. var ArcRotateCamera = (function (_super) {
  17978. __extends(ArcRotateCamera, _super);
  17979. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  17980. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  17981. _this.inertialAlphaOffset = 0;
  17982. _this.inertialBetaOffset = 0;
  17983. _this.inertialRadiusOffset = 0;
  17984. _this.lowerAlphaLimit = null;
  17985. _this.upperAlphaLimit = null;
  17986. _this.lowerBetaLimit = 0.01;
  17987. _this.upperBetaLimit = Math.PI;
  17988. _this.lowerRadiusLimit = null;
  17989. _this.upperRadiusLimit = null;
  17990. _this.inertialPanningX = 0;
  17991. _this.inertialPanningY = 0;
  17992. //-- end properties for backward compatibility for inputs
  17993. _this.zoomOnFactor = 1;
  17994. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  17995. _this.allowUpsideDown = true;
  17996. _this._viewMatrix = new BABYLON.Matrix();
  17997. // Panning
  17998. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  17999. _this.checkCollisions = false;
  18000. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  18001. _this._collider = new BABYLON.Collider();
  18002. _this._previousPosition = BABYLON.Vector3.Zero();
  18003. _this._collisionVelocity = BABYLON.Vector3.Zero();
  18004. _this._newPosition = BABYLON.Vector3.Zero();
  18005. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  18006. if (collidedMesh === void 0) { collidedMesh = null; }
  18007. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  18008. newPosition.multiplyInPlace(_this._collider.radius);
  18009. }
  18010. if (!collidedMesh) {
  18011. _this._previousPosition.copyFrom(_this.position);
  18012. }
  18013. else {
  18014. _this.setPosition(newPosition);
  18015. if (_this.onCollide) {
  18016. _this.onCollide(collidedMesh);
  18017. }
  18018. }
  18019. // Recompute because of constraints
  18020. var cosa = Math.cos(_this.alpha);
  18021. var sina = Math.sin(_this.alpha);
  18022. var cosb = Math.cos(_this.beta);
  18023. var sinb = Math.sin(_this.beta);
  18024. if (sinb === 0) {
  18025. sinb = 0.0001;
  18026. }
  18027. var target = _this._getTargetPosition();
  18028. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  18029. _this.position.copyFrom(_this._newPosition);
  18030. var up = _this.upVector;
  18031. if (_this.allowUpsideDown && _this.beta < 0) {
  18032. up = up.clone();
  18033. up = up.negate();
  18034. }
  18035. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  18036. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  18037. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  18038. _this._collisionTriggered = false;
  18039. };
  18040. if (!target) {
  18041. _this.target = BABYLON.Vector3.Zero();
  18042. }
  18043. else {
  18044. _this.target = target;
  18045. }
  18046. _this.alpha = alpha;
  18047. _this.beta = beta;
  18048. _this.radius = radius;
  18049. _this.getViewMatrix();
  18050. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  18051. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  18052. return _this;
  18053. }
  18054. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  18055. //-- begin properties for backward compatibility for inputs
  18056. get: function () {
  18057. var pointers = this.inputs.attached["pointers"];
  18058. if (pointers)
  18059. return pointers.angularSensibilityX;
  18060. },
  18061. set: function (value) {
  18062. var pointers = this.inputs.attached["pointers"];
  18063. if (pointers) {
  18064. pointers.angularSensibilityX = value;
  18065. }
  18066. },
  18067. enumerable: true,
  18068. configurable: true
  18069. });
  18070. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  18071. get: function () {
  18072. var pointers = this.inputs.attached["pointers"];
  18073. if (pointers)
  18074. return pointers.angularSensibilityY;
  18075. },
  18076. set: function (value) {
  18077. var pointers = this.inputs.attached["pointers"];
  18078. if (pointers) {
  18079. pointers.angularSensibilityY = value;
  18080. }
  18081. },
  18082. enumerable: true,
  18083. configurable: true
  18084. });
  18085. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  18086. get: function () {
  18087. var pointers = this.inputs.attached["pointers"];
  18088. if (pointers)
  18089. return pointers.pinchPrecision;
  18090. },
  18091. set: function (value) {
  18092. var pointers = this.inputs.attached["pointers"];
  18093. if (pointers) {
  18094. pointers.pinchPrecision = value;
  18095. }
  18096. },
  18097. enumerable: true,
  18098. configurable: true
  18099. });
  18100. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  18101. get: function () {
  18102. var pointers = this.inputs.attached["pointers"];
  18103. if (pointers)
  18104. return pointers.panningSensibility;
  18105. },
  18106. set: function (value) {
  18107. var pointers = this.inputs.attached["pointers"];
  18108. if (pointers) {
  18109. pointers.panningSensibility = value;
  18110. }
  18111. },
  18112. enumerable: true,
  18113. configurable: true
  18114. });
  18115. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  18116. get: function () {
  18117. var keyboard = this.inputs.attached["keyboard"];
  18118. if (keyboard)
  18119. return keyboard.keysUp;
  18120. },
  18121. set: function (value) {
  18122. var keyboard = this.inputs.attached["keyboard"];
  18123. if (keyboard)
  18124. keyboard.keysUp = value;
  18125. },
  18126. enumerable: true,
  18127. configurable: true
  18128. });
  18129. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  18130. get: function () {
  18131. var keyboard = this.inputs.attached["keyboard"];
  18132. if (keyboard)
  18133. return keyboard.keysDown;
  18134. },
  18135. set: function (value) {
  18136. var keyboard = this.inputs.attached["keyboard"];
  18137. if (keyboard)
  18138. keyboard.keysDown = value;
  18139. },
  18140. enumerable: true,
  18141. configurable: true
  18142. });
  18143. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  18144. get: function () {
  18145. var keyboard = this.inputs.attached["keyboard"];
  18146. if (keyboard)
  18147. return keyboard.keysLeft;
  18148. },
  18149. set: function (value) {
  18150. var keyboard = this.inputs.attached["keyboard"];
  18151. if (keyboard)
  18152. keyboard.keysLeft = value;
  18153. },
  18154. enumerable: true,
  18155. configurable: true
  18156. });
  18157. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  18158. get: function () {
  18159. var keyboard = this.inputs.attached["keyboard"];
  18160. if (keyboard)
  18161. return keyboard.keysRight;
  18162. },
  18163. set: function (value) {
  18164. var keyboard = this.inputs.attached["keyboard"];
  18165. if (keyboard)
  18166. keyboard.keysRight = value;
  18167. },
  18168. enumerable: true,
  18169. configurable: true
  18170. });
  18171. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  18172. get: function () {
  18173. var mousewheel = this.inputs.attached["mousewheel"];
  18174. if (mousewheel)
  18175. return mousewheel.wheelPrecision;
  18176. },
  18177. set: function (value) {
  18178. var mousewheel = this.inputs.attached["mousewheel"];
  18179. if (mousewheel)
  18180. mousewheel.wheelPrecision = value;
  18181. },
  18182. enumerable: true,
  18183. configurable: true
  18184. });
  18185. // Cache
  18186. ArcRotateCamera.prototype._initCache = function () {
  18187. _super.prototype._initCache.call(this);
  18188. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18189. this._cache.alpha = undefined;
  18190. this._cache.beta = undefined;
  18191. this._cache.radius = undefined;
  18192. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  18193. };
  18194. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  18195. if (!ignoreParentClass) {
  18196. _super.prototype._updateCache.call(this);
  18197. }
  18198. this._cache.target.copyFrom(this._getTargetPosition());
  18199. this._cache.alpha = this.alpha;
  18200. this._cache.beta = this.beta;
  18201. this._cache.radius = this.radius;
  18202. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  18203. };
  18204. ArcRotateCamera.prototype._getTargetPosition = function () {
  18205. if (this.target.getAbsolutePosition) {
  18206. var pos = this.target.getAbsolutePosition();
  18207. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  18208. }
  18209. return this.target;
  18210. };
  18211. // Synchronized
  18212. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  18213. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  18214. return false;
  18215. return this._cache.target.equals(this.target)
  18216. && this._cache.alpha === this.alpha
  18217. && this._cache.beta === this.beta
  18218. && this._cache.radius === this.radius
  18219. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  18220. };
  18221. // Methods
  18222. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  18223. var _this = this;
  18224. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  18225. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  18226. this._useCtrlForPanning = useCtrlForPanning;
  18227. this._panningMouseButton = panningMouseButton;
  18228. this.inputs.attachElement(element, noPreventDefault);
  18229. this._reset = function () {
  18230. _this.inertialAlphaOffset = 0;
  18231. _this.inertialBetaOffset = 0;
  18232. _this.inertialRadiusOffset = 0;
  18233. };
  18234. };
  18235. ArcRotateCamera.prototype.detachControl = function (element) {
  18236. this.inputs.detachElement(element);
  18237. if (this._reset) {
  18238. this._reset();
  18239. }
  18240. };
  18241. ArcRotateCamera.prototype._checkInputs = function () {
  18242. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  18243. if (this._collisionTriggered) {
  18244. return;
  18245. }
  18246. this.inputs.checkInputs();
  18247. // Inertia
  18248. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  18249. if (this.getScene().useRightHandedSystem) {
  18250. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18251. }
  18252. else {
  18253. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18254. }
  18255. this.beta += this.inertialBetaOffset;
  18256. this.radius -= this.inertialRadiusOffset;
  18257. this.inertialAlphaOffset *= this.inertia;
  18258. this.inertialBetaOffset *= this.inertia;
  18259. this.inertialRadiusOffset *= this.inertia;
  18260. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  18261. this.inertialAlphaOffset = 0;
  18262. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  18263. this.inertialBetaOffset = 0;
  18264. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  18265. this.inertialRadiusOffset = 0;
  18266. }
  18267. // Panning inertia
  18268. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  18269. if (!this._localDirection) {
  18270. this._localDirection = BABYLON.Vector3.Zero();
  18271. this._transformedDirection = BABYLON.Vector3.Zero();
  18272. }
  18273. this.inertialPanningX *= this.inertia;
  18274. this.inertialPanningY *= this.inertia;
  18275. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  18276. this.inertialPanningX = 0;
  18277. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  18278. this.inertialPanningY = 0;
  18279. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  18280. this._localDirection.multiplyInPlace(this.panningAxis);
  18281. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  18282. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  18283. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  18284. if (!this.panningAxis.y) {
  18285. this._transformedDirection.y = 0;
  18286. }
  18287. if (!this.target.getAbsolutePosition) {
  18288. this.target.addInPlace(this._transformedDirection);
  18289. }
  18290. }
  18291. // Limits
  18292. this._checkLimits();
  18293. _super.prototype._checkInputs.call(this);
  18294. };
  18295. ArcRotateCamera.prototype._checkLimits = function () {
  18296. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  18297. if (this.allowUpsideDown && this.beta > Math.PI) {
  18298. this.beta = this.beta - (2 * Math.PI);
  18299. }
  18300. }
  18301. else {
  18302. if (this.beta < this.lowerBetaLimit) {
  18303. this.beta = this.lowerBetaLimit;
  18304. }
  18305. }
  18306. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  18307. if (this.allowUpsideDown && this.beta < -Math.PI) {
  18308. this.beta = this.beta + (2 * Math.PI);
  18309. }
  18310. }
  18311. else {
  18312. if (this.beta > this.upperBetaLimit) {
  18313. this.beta = this.upperBetaLimit;
  18314. }
  18315. }
  18316. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  18317. this.alpha = this.lowerAlphaLimit;
  18318. }
  18319. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  18320. this.alpha = this.upperAlphaLimit;
  18321. }
  18322. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  18323. this.radius = this.lowerRadiusLimit;
  18324. }
  18325. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  18326. this.radius = this.upperRadiusLimit;
  18327. }
  18328. };
  18329. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  18330. var radiusv3 = this.position.subtract(this._getTargetPosition());
  18331. this.radius = radiusv3.length();
  18332. // Alpha
  18333. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  18334. if (radiusv3.z < 0) {
  18335. this.alpha = 2 * Math.PI - this.alpha;
  18336. }
  18337. // Beta
  18338. this.beta = Math.acos(radiusv3.y / this.radius);
  18339. this._checkLimits();
  18340. };
  18341. ArcRotateCamera.prototype.setPosition = function (position) {
  18342. if (this.position.equals(position)) {
  18343. return;
  18344. }
  18345. this.position.copyFrom(position);
  18346. this.rebuildAnglesAndRadius();
  18347. };
  18348. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  18349. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  18350. if (allowSamePosition === void 0) { allowSamePosition = false; }
  18351. if (!allowSamePosition && this._getTargetPosition().equals(target)) {
  18352. return;
  18353. }
  18354. if (toBoundingCenter && target.getBoundingInfo) {
  18355. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  18356. }
  18357. else {
  18358. this._targetBoundingCenter = null;
  18359. }
  18360. this.target = target;
  18361. this.rebuildAnglesAndRadius();
  18362. };
  18363. ArcRotateCamera.prototype._getViewMatrix = function () {
  18364. // Compute
  18365. var cosa = Math.cos(this.alpha);
  18366. var sina = Math.sin(this.alpha);
  18367. var cosb = Math.cos(this.beta);
  18368. var sinb = Math.sin(this.beta);
  18369. if (sinb === 0) {
  18370. sinb = 0.0001;
  18371. }
  18372. var target = this._getTargetPosition();
  18373. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  18374. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  18375. this._collider.radius = this.collisionRadius;
  18376. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  18377. this._collisionTriggered = true;
  18378. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  18379. }
  18380. else {
  18381. this.position.copyFrom(this._newPosition);
  18382. var up = this.upVector;
  18383. if (this.allowUpsideDown && this.beta < 0) {
  18384. up = up.clone();
  18385. up = up.negate();
  18386. }
  18387. if (this.getScene().useRightHandedSystem) {
  18388. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  18389. }
  18390. else {
  18391. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  18392. }
  18393. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  18394. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  18395. }
  18396. this._currentTarget = target;
  18397. return this._viewMatrix;
  18398. };
  18399. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  18400. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18401. meshes = meshes || this.getScene().meshes;
  18402. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  18403. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  18404. this.radius = distance * this.zoomOnFactor;
  18405. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  18406. };
  18407. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  18408. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18409. var meshesOrMinMaxVector;
  18410. var distance;
  18411. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  18412. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  18413. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  18414. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  18415. }
  18416. else {
  18417. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  18418. distance = meshesOrMinMaxVectorAndDistance.distance;
  18419. }
  18420. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  18421. if (!doNotUpdateMaxZ) {
  18422. this.maxZ = distance * 2;
  18423. }
  18424. };
  18425. /**
  18426. * @override
  18427. * Override Camera.createRigCamera
  18428. */
  18429. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  18430. var alphaShift;
  18431. switch (this.cameraRigMode) {
  18432. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18433. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18434. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18435. case BABYLON.Camera.RIG_MODE_VR:
  18436. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  18437. break;
  18438. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18439. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  18440. break;
  18441. }
  18442. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  18443. rigCam._cameraRigParams = {};
  18444. return rigCam;
  18445. };
  18446. /**
  18447. * @override
  18448. * Override Camera._updateRigCameras
  18449. */
  18450. ArcRotateCamera.prototype._updateRigCameras = function () {
  18451. var camLeft = this._rigCameras[0];
  18452. var camRight = this._rigCameras[1];
  18453. camLeft.beta = camRight.beta = this.beta;
  18454. camLeft.radius = camRight.radius = this.radius;
  18455. switch (this.cameraRigMode) {
  18456. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18457. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18458. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18459. case BABYLON.Camera.RIG_MODE_VR:
  18460. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  18461. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  18462. break;
  18463. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18464. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  18465. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  18466. break;
  18467. }
  18468. _super.prototype._updateRigCameras.call(this);
  18469. };
  18470. ArcRotateCamera.prototype.dispose = function () {
  18471. this.inputs.clear();
  18472. _super.prototype.dispose.call(this);
  18473. };
  18474. ArcRotateCamera.prototype.getClassName = function () {
  18475. return "ArcRotateCamera";
  18476. };
  18477. return ArcRotateCamera;
  18478. }(BABYLON.TargetCamera));
  18479. __decorate([
  18480. BABYLON.serialize()
  18481. ], ArcRotateCamera.prototype, "alpha", void 0);
  18482. __decorate([
  18483. BABYLON.serialize()
  18484. ], ArcRotateCamera.prototype, "beta", void 0);
  18485. __decorate([
  18486. BABYLON.serialize()
  18487. ], ArcRotateCamera.prototype, "radius", void 0);
  18488. __decorate([
  18489. BABYLON.serializeAsVector3()
  18490. ], ArcRotateCamera.prototype, "target", void 0);
  18491. __decorate([
  18492. BABYLON.serialize()
  18493. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  18494. __decorate([
  18495. BABYLON.serialize()
  18496. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  18497. __decorate([
  18498. BABYLON.serialize()
  18499. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  18500. __decorate([
  18501. BABYLON.serialize()
  18502. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  18503. __decorate([
  18504. BABYLON.serialize()
  18505. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  18506. __decorate([
  18507. BABYLON.serialize()
  18508. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  18509. __decorate([
  18510. BABYLON.serialize()
  18511. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  18512. __decorate([
  18513. BABYLON.serialize()
  18514. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  18515. __decorate([
  18516. BABYLON.serialize()
  18517. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  18518. __decorate([
  18519. BABYLON.serialize()
  18520. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  18521. __decorate([
  18522. BABYLON.serialize()
  18523. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  18524. __decorate([
  18525. BABYLON.serialize()
  18526. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  18527. __decorate([
  18528. BABYLON.serialize()
  18529. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  18530. BABYLON.ArcRotateCamera = ArcRotateCamera;
  18531. })(BABYLON || (BABYLON = {}));
  18532. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  18533. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  18534. var BABYLON;
  18535. (function (BABYLON) {
  18536. var ArcRotateCameraInputsManager = (function (_super) {
  18537. __extends(ArcRotateCameraInputsManager, _super);
  18538. function ArcRotateCameraInputsManager(camera) {
  18539. return _super.call(this, camera) || this;
  18540. }
  18541. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  18542. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  18543. return this;
  18544. };
  18545. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  18546. this.add(new BABYLON.ArcRotateCameraPointersInput());
  18547. return this;
  18548. };
  18549. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  18550. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  18551. return this;
  18552. };
  18553. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  18554. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  18555. return this;
  18556. };
  18557. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  18558. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  18559. return this;
  18560. };
  18561. return ArcRotateCameraInputsManager;
  18562. }(BABYLON.CameraInputsManager));
  18563. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  18564. })(BABYLON || (BABYLON = {}));
  18565. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  18566. var BABYLON;
  18567. (function (BABYLON) {
  18568. var RenderingManager = (function () {
  18569. function RenderingManager(scene) {
  18570. this._renderingGroups = new Array();
  18571. this._autoClearDepthStencil = {};
  18572. this._customOpaqueSortCompareFn = {};
  18573. this._customAlphaTestSortCompareFn = {};
  18574. this._customTransparentSortCompareFn = {};
  18575. this._renderinGroupInfo = null;
  18576. this._scene = scene;
  18577. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18578. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18579. }
  18580. }
  18581. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18582. if (depth === void 0) { depth = true; }
  18583. if (stencil === void 0) { stencil = true; }
  18584. if (this._depthStencilBufferAlreadyCleaned) {
  18585. return;
  18586. }
  18587. this._scene.getEngine().clear(null, false, depth, stencil);
  18588. this._depthStencilBufferAlreadyCleaned = true;
  18589. };
  18590. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18591. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18592. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18593. var info = null;
  18594. if (observable) {
  18595. if (!this._renderinGroupInfo) {
  18596. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18597. }
  18598. info = this._renderinGroupInfo;
  18599. info.scene = this._scene;
  18600. info.camera = this._scene.activeCamera;
  18601. }
  18602. // Dispatch sprites
  18603. if (renderSprites) {
  18604. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18605. var manager = this._scene.spriteManagers[index];
  18606. this.dispatchSprites(manager);
  18607. }
  18608. }
  18609. // Render
  18610. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18611. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18612. var renderingGroup = this._renderingGroups[index];
  18613. if (!renderingGroup && !observable)
  18614. continue;
  18615. this._currentIndex = index;
  18616. var renderingGroupMask = 0;
  18617. // Fire PRECLEAR stage
  18618. if (observable) {
  18619. renderingGroupMask = Math.pow(2, index);
  18620. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18621. info.renderingGroupId = index;
  18622. observable.notifyObservers(info, renderingGroupMask);
  18623. }
  18624. // Clear depth/stencil if needed
  18625. var autoClear = this._autoClearDepthStencil[index];
  18626. if (autoClear && autoClear.autoClear) {
  18627. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18628. }
  18629. if (observable) {
  18630. // Fire PREOPAQUE stage
  18631. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18632. observable.notifyObservers(info, renderingGroupMask);
  18633. // Fire PRETRANSPARENT stage
  18634. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18635. observable.notifyObservers(info, renderingGroupMask);
  18636. }
  18637. if (renderingGroup)
  18638. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18639. // Fire POSTTRANSPARENT stage
  18640. if (observable) {
  18641. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18642. observable.notifyObservers(info, renderingGroupMask);
  18643. }
  18644. }
  18645. };
  18646. RenderingManager.prototype.reset = function () {
  18647. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18648. var renderingGroup = this._renderingGroups[index];
  18649. if (renderingGroup) {
  18650. renderingGroup.prepare();
  18651. }
  18652. }
  18653. };
  18654. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18655. if (!this._renderingGroups[renderingGroupId]) {
  18656. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18657. }
  18658. };
  18659. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18660. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18661. this._prepareRenderingGroup(renderingGroupId);
  18662. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18663. };
  18664. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18665. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18666. this._prepareRenderingGroup(renderingGroupId);
  18667. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18668. };
  18669. RenderingManager.prototype.dispatch = function (subMesh) {
  18670. var mesh = subMesh.getMesh();
  18671. var renderingGroupId = mesh.renderingGroupId || 0;
  18672. this._prepareRenderingGroup(renderingGroupId);
  18673. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  18674. };
  18675. /**
  18676. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18677. * This allowed control for front to back rendering or reversly depending of the special needs.
  18678. *
  18679. * @param renderingGroupId The rendering group id corresponding to its index
  18680. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18681. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18682. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18683. */
  18684. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18685. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18686. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18687. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18688. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18689. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18690. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18691. if (this._renderingGroups[renderingGroupId]) {
  18692. var group = this._renderingGroups[renderingGroupId];
  18693. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18694. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18695. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18696. }
  18697. };
  18698. /**
  18699. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18700. *
  18701. * @param renderingGroupId The rendering group id corresponding to its index
  18702. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18703. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18704. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18705. */
  18706. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18707. if (depth === void 0) { depth = true; }
  18708. if (stencil === void 0) { stencil = true; }
  18709. this._autoClearDepthStencil[renderingGroupId] = {
  18710. autoClear: autoClearDepthStencil,
  18711. depth: depth,
  18712. stencil: stencil
  18713. };
  18714. };
  18715. return RenderingManager;
  18716. }());
  18717. /**
  18718. * The max id used for rendering groups (not included)
  18719. */
  18720. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18721. /**
  18722. * The min id used for rendering groups (included)
  18723. */
  18724. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18725. BABYLON.RenderingManager = RenderingManager;
  18726. })(BABYLON || (BABYLON = {}));
  18727. //# sourceMappingURL=babylon.renderingManager.js.map
  18728. var BABYLON;
  18729. (function (BABYLON) {
  18730. var RenderingGroup = (function () {
  18731. /**
  18732. * Creates a new rendering group.
  18733. * @param index The rendering group index
  18734. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18735. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18736. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18737. */
  18738. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18739. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18740. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18741. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18742. this.index = index;
  18743. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18744. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18745. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18746. this._particleSystems = new BABYLON.SmartArray(256);
  18747. this._spriteManagers = new BABYLON.SmartArray(256);
  18748. this._scene = scene;
  18749. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18750. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18751. this.transparentSortCompareFn = transparentSortCompareFn;
  18752. }
  18753. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18754. /**
  18755. * Set the opaque sort comparison function.
  18756. * If null the sub meshes will be render in the order they were created
  18757. */
  18758. set: function (value) {
  18759. this._opaqueSortCompareFn = value;
  18760. if (value) {
  18761. this._renderOpaque = this.renderOpaqueSorted;
  18762. }
  18763. else {
  18764. this._renderOpaque = RenderingGroup.renderUnsorted;
  18765. }
  18766. },
  18767. enumerable: true,
  18768. configurable: true
  18769. });
  18770. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18771. /**
  18772. * Set the alpha test sort comparison function.
  18773. * If null the sub meshes will be render in the order they were created
  18774. */
  18775. set: function (value) {
  18776. this._alphaTestSortCompareFn = value;
  18777. if (value) {
  18778. this._renderAlphaTest = this.renderAlphaTestSorted;
  18779. }
  18780. else {
  18781. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  18782. }
  18783. },
  18784. enumerable: true,
  18785. configurable: true
  18786. });
  18787. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  18788. /**
  18789. * Set the transparent sort comparison function.
  18790. * If null the sub meshes will be render in the order they were created
  18791. */
  18792. set: function (value) {
  18793. if (value) {
  18794. this._transparentSortCompareFn = value;
  18795. }
  18796. else {
  18797. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  18798. }
  18799. this._renderTransparent = this.renderTransparentSorted;
  18800. },
  18801. enumerable: true,
  18802. configurable: true
  18803. });
  18804. /**
  18805. * Render all the sub meshes contained in the group.
  18806. * @param customRenderFunction Used to override the default render behaviour of the group.
  18807. * @returns true if rendered some submeshes.
  18808. */
  18809. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  18810. if (customRenderFunction) {
  18811. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  18812. return;
  18813. }
  18814. var engine = this._scene.getEngine();
  18815. // Opaque
  18816. if (this._opaqueSubMeshes.length !== 0) {
  18817. this._renderOpaque(this._opaqueSubMeshes);
  18818. }
  18819. // Alpha test
  18820. if (this._alphaTestSubMeshes.length !== 0) {
  18821. engine.setAlphaTesting(true);
  18822. this._renderAlphaTest(this._alphaTestSubMeshes);
  18823. engine.setAlphaTesting(false);
  18824. }
  18825. // Sprites
  18826. if (renderSprites) {
  18827. this._renderSprites();
  18828. }
  18829. // Particles
  18830. if (renderParticles) {
  18831. this._renderParticles(activeMeshes);
  18832. }
  18833. if (this.onBeforeTransparentRendering) {
  18834. this.onBeforeTransparentRendering();
  18835. }
  18836. // Transparent
  18837. if (this._transparentSubMeshes.length !== 0) {
  18838. this._renderTransparent(this._transparentSubMeshes);
  18839. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18840. }
  18841. };
  18842. /**
  18843. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  18844. * @param subMeshes The submeshes to render
  18845. */
  18846. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  18847. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  18848. };
  18849. /**
  18850. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  18851. * @param subMeshes The submeshes to render
  18852. */
  18853. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  18854. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  18855. };
  18856. /**
  18857. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  18858. * @param subMeshes The submeshes to render
  18859. */
  18860. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18861. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  18862. };
  18863. /**
  18864. * Renders the submeshes in a specified order.
  18865. * @param subMeshes The submeshes to sort before render
  18866. * @param sortCompareFn The comparison function use to sort
  18867. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18868. * @param transparent Specifies to activate blending if true
  18869. */
  18870. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  18871. var subIndex = 0;
  18872. var subMesh;
  18873. for (; subIndex < subMeshes.length; subIndex++) {
  18874. subMesh = subMeshes.data[subIndex];
  18875. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18876. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18877. }
  18878. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18879. sortedArray.sort(sortCompareFn);
  18880. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18881. subMesh = sortedArray[subIndex];
  18882. subMesh.render(transparent);
  18883. }
  18884. };
  18885. /**
  18886. * Renders the submeshes in the order they were dispatched (no sort applied).
  18887. * @param subMeshes The submeshes to render
  18888. */
  18889. RenderingGroup.renderUnsorted = function (subMeshes) {
  18890. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18891. var submesh = subMeshes.data[subIndex];
  18892. submesh.render(false);
  18893. }
  18894. };
  18895. /**
  18896. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18897. * are rendered back to front if in the same alpha index.
  18898. *
  18899. * @param a The first submesh
  18900. * @param b The second submesh
  18901. * @returns The result of the comparison
  18902. */
  18903. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  18904. // Alpha index first
  18905. if (a._alphaIndex > b._alphaIndex) {
  18906. return 1;
  18907. }
  18908. if (a._alphaIndex < b._alphaIndex) {
  18909. return -1;
  18910. }
  18911. // Then distance to camera
  18912. return RenderingGroup.backToFrontSortCompare(a, b);
  18913. };
  18914. /**
  18915. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18916. * are rendered back to front.
  18917. *
  18918. * @param a The first submesh
  18919. * @param b The second submesh
  18920. * @returns The result of the comparison
  18921. */
  18922. RenderingGroup.backToFrontSortCompare = function (a, b) {
  18923. // Then distance to camera
  18924. if (a._distanceToCamera < b._distanceToCamera) {
  18925. return 1;
  18926. }
  18927. if (a._distanceToCamera > b._distanceToCamera) {
  18928. return -1;
  18929. }
  18930. return 0;
  18931. };
  18932. /**
  18933. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18934. * are rendered front to back (prevent overdraw).
  18935. *
  18936. * @param a The first submesh
  18937. * @param b The second submesh
  18938. * @returns The result of the comparison
  18939. */
  18940. RenderingGroup.frontToBackSortCompare = function (a, b) {
  18941. // Then distance to camera
  18942. if (a._distanceToCamera < b._distanceToCamera) {
  18943. return -1;
  18944. }
  18945. if (a._distanceToCamera > b._distanceToCamera) {
  18946. return 1;
  18947. }
  18948. return 0;
  18949. };
  18950. /**
  18951. * Resets the different lists of submeshes to prepare a new frame.
  18952. */
  18953. RenderingGroup.prototype.prepare = function () {
  18954. this._opaqueSubMeshes.reset();
  18955. this._transparentSubMeshes.reset();
  18956. this._alphaTestSubMeshes.reset();
  18957. this._particleSystems.reset();
  18958. this._spriteManagers.reset();
  18959. };
  18960. /**
  18961. * Inserts the submesh in its correct queue depending on its material.
  18962. * @param subMesh The submesh to dispatch
  18963. */
  18964. RenderingGroup.prototype.dispatch = function (subMesh) {
  18965. var material = subMesh.getMaterial();
  18966. var mesh = subMesh.getMesh();
  18967. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  18968. this._transparentSubMeshes.push(subMesh);
  18969. }
  18970. else if (material.needAlphaTesting()) {
  18971. this._alphaTestSubMeshes.push(subMesh);
  18972. }
  18973. else {
  18974. this._opaqueSubMeshes.push(subMesh); // Opaque
  18975. }
  18976. };
  18977. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  18978. this._spriteManagers.push(spriteManager);
  18979. };
  18980. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  18981. this._particleSystems.push(particleSystem);
  18982. };
  18983. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  18984. if (this._particleSystems.length === 0) {
  18985. return;
  18986. }
  18987. // Particles
  18988. var activeCamera = this._scene.activeCamera;
  18989. this._scene._particlesDuration.beginMonitoring();
  18990. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  18991. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  18992. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  18993. continue;
  18994. }
  18995. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  18996. this._scene._activeParticles.addCount(particleSystem.render(), false);
  18997. }
  18998. }
  18999. this._scene._particlesDuration.endMonitoring(false);
  19000. };
  19001. RenderingGroup.prototype._renderSprites = function () {
  19002. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19003. return;
  19004. }
  19005. // Sprites
  19006. var activeCamera = this._scene.activeCamera;
  19007. this._scene._spritesDuration.beginMonitoring();
  19008. for (var id = 0; id < this._spriteManagers.length; id++) {
  19009. var spriteManager = this._spriteManagers.data[id];
  19010. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19011. spriteManager.render();
  19012. }
  19013. }
  19014. this._scene._spritesDuration.endMonitoring(false);
  19015. };
  19016. return RenderingGroup;
  19017. }());
  19018. BABYLON.RenderingGroup = RenderingGroup;
  19019. })(BABYLON || (BABYLON = {}));
  19020. //# sourceMappingURL=babylon.renderingGroup.js.map
  19021. var BABYLON;
  19022. (function (BABYLON) {
  19023. var PointerEventTypes = (function () {
  19024. function PointerEventTypes() {
  19025. }
  19026. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  19027. get: function () {
  19028. return PointerEventTypes._POINTERDOWN;
  19029. },
  19030. enumerable: true,
  19031. configurable: true
  19032. });
  19033. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  19034. get: function () {
  19035. return PointerEventTypes._POINTERUP;
  19036. },
  19037. enumerable: true,
  19038. configurable: true
  19039. });
  19040. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  19041. get: function () {
  19042. return PointerEventTypes._POINTERMOVE;
  19043. },
  19044. enumerable: true,
  19045. configurable: true
  19046. });
  19047. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  19048. get: function () {
  19049. return PointerEventTypes._POINTERWHEEL;
  19050. },
  19051. enumerable: true,
  19052. configurable: true
  19053. });
  19054. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  19055. get: function () {
  19056. return PointerEventTypes._POINTERPICK;
  19057. },
  19058. enumerable: true,
  19059. configurable: true
  19060. });
  19061. return PointerEventTypes;
  19062. }());
  19063. PointerEventTypes._POINTERDOWN = 0x01;
  19064. PointerEventTypes._POINTERUP = 0x02;
  19065. PointerEventTypes._POINTERMOVE = 0x04;
  19066. PointerEventTypes._POINTERWHEEL = 0x08;
  19067. PointerEventTypes._POINTERPICK = 0x10;
  19068. BABYLON.PointerEventTypes = PointerEventTypes;
  19069. var PointerInfoBase = (function () {
  19070. function PointerInfoBase(type, event) {
  19071. this.type = type;
  19072. this.event = event;
  19073. }
  19074. return PointerInfoBase;
  19075. }());
  19076. BABYLON.PointerInfoBase = PointerInfoBase;
  19077. /**
  19078. * This class is used to store pointer related info for the onPrePointerObservable event.
  19079. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  19080. */
  19081. var PointerInfoPre = (function (_super) {
  19082. __extends(PointerInfoPre, _super);
  19083. function PointerInfoPre(type, event, localX, localY) {
  19084. var _this = _super.call(this, type, event) || this;
  19085. _this.skipOnPointerObservable = false;
  19086. _this.localPosition = new BABYLON.Vector2(localX, localY);
  19087. return _this;
  19088. }
  19089. return PointerInfoPre;
  19090. }(PointerInfoBase));
  19091. BABYLON.PointerInfoPre = PointerInfoPre;
  19092. /**
  19093. * This type contains all the data related to a pointer event in Babylon.js.
  19094. * 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.
  19095. */
  19096. var PointerInfo = (function (_super) {
  19097. __extends(PointerInfo, _super);
  19098. function PointerInfo(type, event, pickInfo) {
  19099. var _this = _super.call(this, type, event) || this;
  19100. _this.pickInfo = pickInfo;
  19101. return _this;
  19102. }
  19103. return PointerInfo;
  19104. }(PointerInfoBase));
  19105. BABYLON.PointerInfo = PointerInfo;
  19106. /**
  19107. * This class is used by the onRenderingGroupObservable
  19108. */
  19109. var RenderingGroupInfo = (function () {
  19110. function RenderingGroupInfo() {
  19111. }
  19112. return RenderingGroupInfo;
  19113. }());
  19114. /**
  19115. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19116. * This stage will be fired no matter what
  19117. */
  19118. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19119. /**
  19120. * Called before opaque object are rendered.
  19121. * This stage will be fired only if there's 3D Opaque content to render
  19122. */
  19123. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19124. /**
  19125. * Called after the opaque objects are rendered and before the transparent ones
  19126. * This stage will be fired only if there's 3D transparent content to render
  19127. */
  19128. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19129. /**
  19130. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19131. * This stage will be fired no matter what
  19132. */
  19133. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19134. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19135. /**
  19136. * Represents a scene to be rendered by the engine.
  19137. * @see http://doc.babylonjs.com/page.php?p=21911
  19138. */
  19139. var Scene = (function () {
  19140. /**
  19141. * @constructor
  19142. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19143. */
  19144. function Scene(engine) {
  19145. // Members
  19146. this.autoClear = true;
  19147. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19148. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19149. this.forceWireframe = false;
  19150. this.forcePointsCloud = false;
  19151. this.forceShowBoundingBoxes = false;
  19152. this.animationsEnabled = true;
  19153. this.constantlyUpdateMeshUnderPointer = false;
  19154. this.useRightHandedSystem = false;
  19155. this.hoverCursor = "pointer";
  19156. // Metadata
  19157. this.metadata = null;
  19158. // Events
  19159. /**
  19160. * An event triggered when the scene is disposed.
  19161. * @type {BABYLON.Observable}
  19162. */
  19163. this.onDisposeObservable = new BABYLON.Observable();
  19164. /**
  19165. * An event triggered before rendering the scene
  19166. * @type {BABYLON.Observable}
  19167. */
  19168. this.onBeforeRenderObservable = new BABYLON.Observable();
  19169. /**
  19170. * An event triggered after rendering the scene
  19171. * @type {BABYLON.Observable}
  19172. */
  19173. this.onAfterRenderObservable = new BABYLON.Observable();
  19174. /**
  19175. * An event triggered when the scene is ready
  19176. * @type {BABYLON.Observable}
  19177. */
  19178. this.onReadyObservable = new BABYLON.Observable();
  19179. /**
  19180. * An event triggered before rendering a camera
  19181. * @type {BABYLON.Observable}
  19182. */
  19183. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19184. /**
  19185. * An event triggered after rendering a camera
  19186. * @type {BABYLON.Observable}
  19187. */
  19188. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19189. /**
  19190. * An event triggered when a camera is created
  19191. * @type {BABYLON.Observable}
  19192. */
  19193. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19194. /**
  19195. * An event triggered when a camera is removed
  19196. * @type {BABYLON.Observable}
  19197. */
  19198. this.onCameraRemovedObservable = new BABYLON.Observable();
  19199. /**
  19200. * An event triggered when a light is created
  19201. * @type {BABYLON.Observable}
  19202. */
  19203. this.onNewLightAddedObservable = new BABYLON.Observable();
  19204. /**
  19205. * An event triggered when a light is removed
  19206. * @type {BABYLON.Observable}
  19207. */
  19208. this.onLightRemovedObservable = new BABYLON.Observable();
  19209. /**
  19210. * An event triggered when a geometry is created
  19211. * @type {BABYLON.Observable}
  19212. */
  19213. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19214. /**
  19215. * An event triggered when a geometry is removed
  19216. * @type {BABYLON.Observable}
  19217. */
  19218. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19219. /**
  19220. * An event triggered when a mesh is created
  19221. * @type {BABYLON.Observable}
  19222. */
  19223. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19224. /**
  19225. * An event triggered when a mesh is removed
  19226. * @type {BABYLON.Observable}
  19227. */
  19228. this.onMeshRemovedObservable = new BABYLON.Observable();
  19229. /**
  19230. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19231. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19232. * 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)
  19233. */
  19234. this.onRenderingGroupObservable = new BABYLON.Observable();
  19235. // Animations
  19236. this.animations = [];
  19237. /**
  19238. * 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).
  19239. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  19240. */
  19241. this.onPrePointerObservable = new BABYLON.Observable();
  19242. /**
  19243. * Observable event triggered each time an input event is received from the rendering canvas
  19244. */
  19245. this.onPointerObservable = new BABYLON.Observable();
  19246. 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
  19247. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19248. this._startingPointerTime = 0;
  19249. // Fog
  19250. /**
  19251. * is fog enabled on this scene.
  19252. * @type {boolean}
  19253. */
  19254. this.fogEnabled = true;
  19255. this.fogMode = Scene.FOGMODE_NONE;
  19256. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19257. this.fogDensity = 0.1;
  19258. this.fogStart = 0;
  19259. this.fogEnd = 1000.0;
  19260. // Lights
  19261. /**
  19262. * is shadow enabled on this scene.
  19263. * @type {boolean}
  19264. */
  19265. this.shadowsEnabled = true;
  19266. /**
  19267. * is light enabled on this scene.
  19268. * @type {boolean}
  19269. */
  19270. this.lightsEnabled = true;
  19271. /**
  19272. * All of the lights added to this scene.
  19273. * @see BABYLON.Light
  19274. * @type {BABYLON.Light[]}
  19275. */
  19276. this.lights = new Array();
  19277. // Cameras
  19278. /**
  19279. * All of the cameras added to this scene.
  19280. * @see BABYLON.Camera
  19281. * @type {BABYLON.Camera[]}
  19282. */
  19283. this.cameras = new Array();
  19284. this.activeCameras = new Array();
  19285. // Meshes
  19286. /**
  19287. * All of the (abstract) meshes added to this scene.
  19288. * @see BABYLON.AbstractMesh
  19289. * @type {BABYLON.AbstractMesh[]}
  19290. */
  19291. this.meshes = new Array();
  19292. // Geometries
  19293. this._geometries = new Array();
  19294. this.materials = new Array();
  19295. this.multiMaterials = new Array();
  19296. // Textures
  19297. this.texturesEnabled = true;
  19298. this.textures = new Array();
  19299. // Particles
  19300. this.particlesEnabled = true;
  19301. this.particleSystems = new Array();
  19302. // Sprites
  19303. this.spritesEnabled = true;
  19304. this.spriteManagers = new Array();
  19305. // Layers
  19306. this.layers = new Array();
  19307. this.highlightLayers = new Array();
  19308. // Skeletons
  19309. this.skeletonsEnabled = true;
  19310. this.skeletons = new Array();
  19311. // Lens flares
  19312. this.lensFlaresEnabled = true;
  19313. this.lensFlareSystems = new Array();
  19314. // Collisions
  19315. this.collisionsEnabled = true;
  19316. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19317. // Postprocesses
  19318. this.postProcessesEnabled = true;
  19319. // Customs render targets
  19320. this.renderTargetsEnabled = true;
  19321. this.dumpNextRenderTargets = false;
  19322. this.customRenderTargets = new Array();
  19323. // Imported meshes
  19324. this.importedMeshesFiles = new Array();
  19325. // Probes
  19326. this.probesEnabled = true;
  19327. this.reflectionProbes = new Array();
  19328. this._actionManagers = new Array();
  19329. this._meshesForIntersections = new BABYLON.SmartArray(256);
  19330. // Procedural textures
  19331. this.proceduralTexturesEnabled = true;
  19332. this._proceduralTextures = new Array();
  19333. this.soundTracks = new Array();
  19334. this._audioEnabled = true;
  19335. this._headphone = false;
  19336. // Performance counters
  19337. this._totalMeshesCounter = new BABYLON.PerfCounter();
  19338. this._totalLightsCounter = new BABYLON.PerfCounter();
  19339. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  19340. this._totalTexturesCounter = new BABYLON.PerfCounter();
  19341. this._totalVertices = new BABYLON.PerfCounter();
  19342. this._activeIndices = new BABYLON.PerfCounter();
  19343. this._activeParticles = new BABYLON.PerfCounter();
  19344. this._lastFrameDuration = new BABYLON.PerfCounter();
  19345. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  19346. this._renderTargetsDuration = new BABYLON.PerfCounter();
  19347. this._particlesDuration = new BABYLON.PerfCounter();
  19348. this._renderDuration = new BABYLON.PerfCounter();
  19349. this._spritesDuration = new BABYLON.PerfCounter();
  19350. this._activeBones = new BABYLON.PerfCounter();
  19351. this._animationTime = 0;
  19352. this.animationTimeScale = 1;
  19353. this._renderId = 0;
  19354. this._executeWhenReadyTimeoutId = -1;
  19355. this._intermediateRendering = false;
  19356. this._toBeDisposed = new BABYLON.SmartArray(256);
  19357. this._pendingData = []; //ANY
  19358. this._activeMeshes = new BABYLON.SmartArray(256);
  19359. this._processedMaterials = new BABYLON.SmartArray(256);
  19360. this._renderTargets = new BABYLON.SmartArray(256);
  19361. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19362. this._activeSkeletons = new BABYLON.SmartArray(32);
  19363. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  19364. this._activeAnimatables = new Array();
  19365. this._transformMatrix = BABYLON.Matrix.Zero();
  19366. this._edgesRenderers = new BABYLON.SmartArray(16);
  19367. this._uniqueIdCounter = 0;
  19368. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19369. this._engine.scenes.push(this);
  19370. this._externalData = new BABYLON.StringDictionary();
  19371. this._uid = null;
  19372. this._renderingManager = new BABYLON.RenderingManager(this);
  19373. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19374. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19375. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19376. if (BABYLON.OutlineRenderer) {
  19377. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19378. }
  19379. this.attachControl();
  19380. if (BABYLON.SoundTrack) {
  19381. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19382. }
  19383. //simplification queue
  19384. if (BABYLON.SimplificationQueue) {
  19385. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19386. }
  19387. //collision coordinator initialization. For now legacy per default.
  19388. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19389. }
  19390. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19391. get: function () {
  19392. return Scene._FOGMODE_NONE;
  19393. },
  19394. enumerable: true,
  19395. configurable: true
  19396. });
  19397. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19398. get: function () {
  19399. return Scene._FOGMODE_EXP;
  19400. },
  19401. enumerable: true,
  19402. configurable: true
  19403. });
  19404. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19405. get: function () {
  19406. return Scene._FOGMODE_EXP2;
  19407. },
  19408. enumerable: true,
  19409. configurable: true
  19410. });
  19411. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19412. get: function () {
  19413. return Scene._FOGMODE_LINEAR;
  19414. },
  19415. enumerable: true,
  19416. configurable: true
  19417. });
  19418. Object.defineProperty(Scene.prototype, "onDispose", {
  19419. set: function (callback) {
  19420. if (this._onDisposeObserver) {
  19421. this.onDisposeObservable.remove(this._onDisposeObserver);
  19422. }
  19423. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19424. },
  19425. enumerable: true,
  19426. configurable: true
  19427. });
  19428. Object.defineProperty(Scene.prototype, "beforeRender", {
  19429. set: function (callback) {
  19430. if (this._onBeforeRenderObserver) {
  19431. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19432. }
  19433. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19434. },
  19435. enumerable: true,
  19436. configurable: true
  19437. });
  19438. Object.defineProperty(Scene.prototype, "afterRender", {
  19439. set: function (callback) {
  19440. if (this._onAfterRenderObserver) {
  19441. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19442. }
  19443. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19444. },
  19445. enumerable: true,
  19446. configurable: true
  19447. });
  19448. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19449. set: function (callback) {
  19450. if (this._onBeforeCameraRenderObserver) {
  19451. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19452. }
  19453. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19454. },
  19455. enumerable: true,
  19456. configurable: true
  19457. });
  19458. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19459. set: function (callback) {
  19460. if (this._onAfterCameraRenderObserver) {
  19461. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19462. }
  19463. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19464. },
  19465. enumerable: true,
  19466. configurable: true
  19467. });
  19468. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19469. get: function () {
  19470. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19471. },
  19472. enumerable: true,
  19473. configurable: true
  19474. });
  19475. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19476. get: function () {
  19477. if (!this._defaultMaterial) {
  19478. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19479. }
  19480. return this._defaultMaterial;
  19481. },
  19482. enumerable: true,
  19483. configurable: true
  19484. });
  19485. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19486. get: function () {
  19487. return this._frustumPlanes;
  19488. },
  19489. enumerable: true,
  19490. configurable: true
  19491. });
  19492. Object.defineProperty(Scene.prototype, "debugLayer", {
  19493. // Properties
  19494. get: function () {
  19495. if (!this._debugLayer) {
  19496. this._debugLayer = new BABYLON.DebugLayer(this);
  19497. }
  19498. return this._debugLayer;
  19499. },
  19500. enumerable: true,
  19501. configurable: true
  19502. });
  19503. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19504. get: function () {
  19505. return this._workerCollisions;
  19506. },
  19507. set: function (enabled) {
  19508. enabled = (enabled && !!Worker);
  19509. this._workerCollisions = enabled;
  19510. if (this.collisionCoordinator) {
  19511. this.collisionCoordinator.destroy();
  19512. }
  19513. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19514. this.collisionCoordinator.init(this);
  19515. },
  19516. enumerable: true,
  19517. configurable: true
  19518. });
  19519. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  19520. get: function () {
  19521. return this._selectionOctree;
  19522. },
  19523. enumerable: true,
  19524. configurable: true
  19525. });
  19526. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19527. /**
  19528. * The mesh that is currently under the pointer.
  19529. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19530. */
  19531. get: function () {
  19532. return this._pointerOverMesh;
  19533. },
  19534. enumerable: true,
  19535. configurable: true
  19536. });
  19537. Object.defineProperty(Scene.prototype, "pointerX", {
  19538. /**
  19539. * Current on-screen X position of the pointer
  19540. * @return {number} X position of the pointer
  19541. */
  19542. get: function () {
  19543. return this._pointerX;
  19544. },
  19545. enumerable: true,
  19546. configurable: true
  19547. });
  19548. Object.defineProperty(Scene.prototype, "pointerY", {
  19549. /**
  19550. * Current on-screen Y position of the pointer
  19551. * @return {number} Y position of the pointer
  19552. */
  19553. get: function () {
  19554. return this._pointerY;
  19555. },
  19556. enumerable: true,
  19557. configurable: true
  19558. });
  19559. Scene.prototype.getCachedMaterial = function () {
  19560. return this._cachedMaterial;
  19561. };
  19562. Scene.prototype.getBoundingBoxRenderer = function () {
  19563. return this._boundingBoxRenderer;
  19564. };
  19565. Scene.prototype.getOutlineRenderer = function () {
  19566. return this._outlineRenderer;
  19567. };
  19568. Scene.prototype.getEngine = function () {
  19569. return this._engine;
  19570. };
  19571. Scene.prototype.getTotalVertices = function () {
  19572. return this._totalVertices.current;
  19573. };
  19574. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19575. get: function () {
  19576. return this._totalVertices;
  19577. },
  19578. enumerable: true,
  19579. configurable: true
  19580. });
  19581. Scene.prototype.getActiveIndices = function () {
  19582. return this._activeIndices.current;
  19583. };
  19584. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19585. get: function () {
  19586. return this._activeIndices;
  19587. },
  19588. enumerable: true,
  19589. configurable: true
  19590. });
  19591. Scene.prototype.getActiveParticles = function () {
  19592. return this._activeParticles.current;
  19593. };
  19594. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  19595. get: function () {
  19596. return this._activeParticles;
  19597. },
  19598. enumerable: true,
  19599. configurable: true
  19600. });
  19601. Scene.prototype.getActiveBones = function () {
  19602. return this._activeBones.current;
  19603. };
  19604. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  19605. get: function () {
  19606. return this._activeBones;
  19607. },
  19608. enumerable: true,
  19609. configurable: true
  19610. });
  19611. // Stats
  19612. Scene.prototype.getLastFrameDuration = function () {
  19613. return this._lastFrameDuration.current;
  19614. };
  19615. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  19616. get: function () {
  19617. return this._lastFrameDuration;
  19618. },
  19619. enumerable: true,
  19620. configurable: true
  19621. });
  19622. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  19623. return this._evaluateActiveMeshesDuration.current;
  19624. };
  19625. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  19626. get: function () {
  19627. return this._evaluateActiveMeshesDuration;
  19628. },
  19629. enumerable: true,
  19630. configurable: true
  19631. });
  19632. Scene.prototype.getActiveMeshes = function () {
  19633. return this._activeMeshes;
  19634. };
  19635. Scene.prototype.getRenderTargetsDuration = function () {
  19636. return this._renderTargetsDuration.current;
  19637. };
  19638. Scene.prototype.getRenderDuration = function () {
  19639. return this._renderDuration.current;
  19640. };
  19641. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  19642. get: function () {
  19643. return this._renderDuration;
  19644. },
  19645. enumerable: true,
  19646. configurable: true
  19647. });
  19648. Scene.prototype.getParticlesDuration = function () {
  19649. return this._particlesDuration.current;
  19650. };
  19651. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  19652. get: function () {
  19653. return this._particlesDuration;
  19654. },
  19655. enumerable: true,
  19656. configurable: true
  19657. });
  19658. Scene.prototype.getSpritesDuration = function () {
  19659. return this._spritesDuration.current;
  19660. };
  19661. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  19662. get: function () {
  19663. return this._spritesDuration;
  19664. },
  19665. enumerable: true,
  19666. configurable: true
  19667. });
  19668. Scene.prototype.getAnimationRatio = function () {
  19669. return this._animationRatio;
  19670. };
  19671. Scene.prototype.getRenderId = function () {
  19672. return this._renderId;
  19673. };
  19674. Scene.prototype.incrementRenderId = function () {
  19675. this._renderId++;
  19676. };
  19677. Scene.prototype._updatePointerPosition = function (evt) {
  19678. var canvasRect = this._engine.getRenderingCanvasClientRect();
  19679. this._pointerX = evt.clientX - canvasRect.left;
  19680. this._pointerY = evt.clientY - canvasRect.top;
  19681. this._unTranslatedPointerX = this._pointerX;
  19682. this._unTranslatedPointerY = this._pointerY;
  19683. if (this.cameraToUseForPointers) {
  19684. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  19685. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  19686. }
  19687. };
  19688. // Pointers handling
  19689. /**
  19690. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  19691. * @param attachUp defines if you want to attach events to pointerup
  19692. * @param attachDown defines if you want to attach events to pointerdown
  19693. * @param attachMove defines if you want to attach events to pointermove
  19694. */
  19695. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  19696. var _this = this;
  19697. if (attachUp === void 0) { attachUp = true; }
  19698. if (attachDown === void 0) { attachDown = true; }
  19699. if (attachMove === void 0) { attachMove = true; }
  19700. var spritePredicate = function (sprite) {
  19701. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  19702. };
  19703. this._onPointerMove = function (evt) {
  19704. _this._updatePointerPosition(evt);
  19705. // PreObservable support
  19706. if (_this.onPrePointerObservable.hasObservers()) {
  19707. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  19708. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19709. _this.onPrePointerObservable.notifyObservers(pi, type);
  19710. if (pi.skipOnPointerObservable) {
  19711. return;
  19712. }
  19713. }
  19714. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19715. return;
  19716. }
  19717. var canvas = _this._engine.getRenderingCanvas();
  19718. if (!_this.pointerMovePredicate) {
  19719. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  19720. }
  19721. // Meshes
  19722. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  19723. if (pickResult.hit && pickResult.pickedMesh) {
  19724. _this.setPointerOverSprite(null);
  19725. _this.setPointerOverMesh(pickResult.pickedMesh);
  19726. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  19727. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  19728. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  19729. }
  19730. else {
  19731. canvas.style.cursor = _this.hoverCursor;
  19732. }
  19733. }
  19734. else {
  19735. canvas.style.cursor = "";
  19736. }
  19737. }
  19738. else {
  19739. _this.setPointerOverMesh(null);
  19740. // Sprites
  19741. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  19742. if (pickResult.hit && pickResult.pickedSprite) {
  19743. _this.setPointerOverSprite(pickResult.pickedSprite);
  19744. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  19745. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  19746. }
  19747. else {
  19748. canvas.style.cursor = _this.hoverCursor;
  19749. }
  19750. }
  19751. else {
  19752. _this.setPointerOverSprite(null);
  19753. // Restore pointer
  19754. canvas.style.cursor = "";
  19755. }
  19756. }
  19757. if (_this.onPointerMove) {
  19758. _this.onPointerMove(evt, pickResult);
  19759. }
  19760. if (_this.onPointerObservable.hasObservers()) {
  19761. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  19762. var pi = new PointerInfo(type, evt, pickResult);
  19763. _this.onPointerObservable.notifyObservers(pi, type);
  19764. }
  19765. };
  19766. this._onPointerDown = function (evt) {
  19767. _this._updatePointerPosition(evt);
  19768. // PreObservable support
  19769. if (_this.onPrePointerObservable.hasObservers()) {
  19770. var type = PointerEventTypes.POINTERDOWN;
  19771. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19772. _this.onPrePointerObservable.notifyObservers(pi, type);
  19773. if (pi.skipOnPointerObservable) {
  19774. return;
  19775. }
  19776. }
  19777. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19778. return;
  19779. }
  19780. _this._startingPointerPosition.x = _this._pointerX;
  19781. _this._startingPointerPosition.y = _this._pointerY;
  19782. _this._startingPointerTime = new Date().getTime();
  19783. if (!_this.pointerDownPredicate) {
  19784. _this.pointerDownPredicate = function (mesh) {
  19785. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  19786. };
  19787. }
  19788. // Meshes
  19789. _this._pickedDownMesh = null;
  19790. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19791. if (pickResult.hit && pickResult.pickedMesh) {
  19792. _this._pickedDownMesh = pickResult.pickedMesh;
  19793. if (pickResult.pickedMesh.actionManager) {
  19794. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  19795. switch (evt.button) {
  19796. case 0:
  19797. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19798. break;
  19799. case 1:
  19800. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19801. break;
  19802. case 2:
  19803. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19804. break;
  19805. }
  19806. if (pickResult.pickedMesh.actionManager) {
  19807. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19808. }
  19809. }
  19810. if (pickResult.pickedMesh.actionManager && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  19811. var that = _this;
  19812. window.setTimeout(function () {
  19813. var pickResult = that.pick(that._unTranslatedPointerX, that._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  19814. if (pickResult.hit && pickResult.pickedMesh) {
  19815. if (pickResult.pickedMesh.actionManager) {
  19816. if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < BABYLON.ActionManager.DragMovementThreshold)) {
  19817. that._startingPointerTime = 0;
  19818. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19819. }
  19820. }
  19821. }
  19822. }, BABYLON.ActionManager.LongPressDelay);
  19823. }
  19824. }
  19825. }
  19826. if (_this.onPointerDown) {
  19827. _this.onPointerDown(evt, pickResult);
  19828. }
  19829. if (_this.onPointerObservable.hasObservers()) {
  19830. var type = PointerEventTypes.POINTERDOWN;
  19831. var pi = new PointerInfo(type, evt, pickResult);
  19832. _this.onPointerObservable.notifyObservers(pi, type);
  19833. }
  19834. // Sprites
  19835. _this._pickedDownSprite = null;
  19836. if (_this.spriteManagers.length > 0) {
  19837. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  19838. if (pickResult.hit && pickResult.pickedSprite) {
  19839. if (pickResult.pickedSprite.actionManager) {
  19840. _this._pickedDownSprite = pickResult.pickedSprite;
  19841. switch (evt.button) {
  19842. case 0:
  19843. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19844. break;
  19845. case 1:
  19846. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19847. break;
  19848. case 2:
  19849. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19850. break;
  19851. }
  19852. if (pickResult.pickedSprite.actionManager) {
  19853. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19854. }
  19855. }
  19856. }
  19857. }
  19858. };
  19859. this._onPointerUp = function (evt) {
  19860. _this._updatePointerPosition(evt);
  19861. // PreObservable support
  19862. if (_this.onPrePointerObservable.hasObservers()) {
  19863. var type = PointerEventTypes.POINTERUP;
  19864. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19865. _this.onPrePointerObservable.notifyObservers(pi, type);
  19866. if (pi.skipOnPointerObservable) {
  19867. return;
  19868. }
  19869. }
  19870. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19871. return;
  19872. }
  19873. if (!_this.pointerUpPredicate) {
  19874. _this.pointerUpPredicate = function (mesh) {
  19875. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  19876. };
  19877. }
  19878. // Meshes
  19879. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  19880. if (pickResult.hit && pickResult.pickedMesh) {
  19881. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  19882. if (_this.onPointerPick) {
  19883. _this.onPointerPick(evt, pickResult);
  19884. }
  19885. if (_this.onPointerObservable.hasObservers()) {
  19886. var type = PointerEventTypes.POINTERPICK;
  19887. var pi = new PointerInfo(type, evt, pickResult);
  19888. _this.onPointerObservable.notifyObservers(pi, type);
  19889. }
  19890. }
  19891. if (pickResult.pickedMesh.actionManager) {
  19892. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19893. if (pickResult.pickedMesh.actionManager) {
  19894. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  19895. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19896. }
  19897. }
  19898. }
  19899. }
  19900. if (_this._pickedDownMesh && _this._pickedDownMesh.actionManager && _this._pickedDownMesh !== pickResult.pickedMesh) {
  19901. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  19902. }
  19903. if (_this.onPointerUp) {
  19904. _this.onPointerUp(evt, pickResult);
  19905. }
  19906. if (_this.onPointerObservable.hasObservers()) {
  19907. var type = PointerEventTypes.POINTERUP;
  19908. var pi = new PointerInfo(type, evt, pickResult);
  19909. _this.onPointerObservable.notifyObservers(pi, type);
  19910. }
  19911. _this._startingPointerTime = 0;
  19912. // Sprites
  19913. if (_this.spriteManagers.length > 0) {
  19914. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  19915. if (pickResult.hit && pickResult.pickedSprite) {
  19916. if (pickResult.pickedSprite.actionManager) {
  19917. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19918. if (pickResult.pickedSprite.actionManager) {
  19919. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  19920. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19921. }
  19922. }
  19923. }
  19924. }
  19925. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
  19926. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  19927. }
  19928. }
  19929. };
  19930. this._onKeyDown = function (evt) {
  19931. if (_this.actionManager) {
  19932. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19933. }
  19934. };
  19935. this._onKeyUp = function (evt) {
  19936. if (_this.actionManager) {
  19937. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19938. }
  19939. };
  19940. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19941. var canvas = this._engine.getRenderingCanvas();
  19942. if (attachMove) {
  19943. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  19944. // Wheel
  19945. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  19946. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  19947. }
  19948. if (attachDown) {
  19949. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  19950. }
  19951. if (attachUp) {
  19952. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  19953. }
  19954. canvas.tabIndex = 1;
  19955. canvas.addEventListener("keydown", this._onKeyDown, false);
  19956. canvas.addEventListener("keyup", this._onKeyUp, false);
  19957. };
  19958. Scene.prototype.detachControl = function () {
  19959. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19960. var canvas = this._engine.getRenderingCanvas();
  19961. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  19962. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  19963. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  19964. // Wheel
  19965. canvas.removeEventListener('mousewheel', this._onPointerMove);
  19966. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  19967. canvas.removeEventListener("keydown", this._onKeyDown);
  19968. canvas.removeEventListener("keyup", this._onKeyUp);
  19969. };
  19970. // Ready
  19971. Scene.prototype.isReady = function () {
  19972. if (this._pendingData.length > 0) {
  19973. return false;
  19974. }
  19975. var index;
  19976. for (index = 0; index < this._geometries.length; index++) {
  19977. var geometry = this._geometries[index];
  19978. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19979. return false;
  19980. }
  19981. }
  19982. for (index = 0; index < this.meshes.length; index++) {
  19983. var mesh = this.meshes[index];
  19984. if (!mesh.isReady()) {
  19985. return false;
  19986. }
  19987. var mat = mesh.material;
  19988. if (mat) {
  19989. if (!mat.isReady(mesh)) {
  19990. return false;
  19991. }
  19992. }
  19993. }
  19994. return true;
  19995. };
  19996. Scene.prototype.resetCachedMaterial = function () {
  19997. this._cachedMaterial = null;
  19998. };
  19999. Scene.prototype.registerBeforeRender = function (func) {
  20000. this.onBeforeRenderObservable.add(func);
  20001. };
  20002. Scene.prototype.unregisterBeforeRender = function (func) {
  20003. this.onBeforeRenderObservable.removeCallback(func);
  20004. };
  20005. Scene.prototype.registerAfterRender = function (func) {
  20006. this.onAfterRenderObservable.add(func);
  20007. };
  20008. Scene.prototype.unregisterAfterRender = function (func) {
  20009. this.onAfterRenderObservable.removeCallback(func);
  20010. };
  20011. Scene.prototype._addPendingData = function (data) {
  20012. this._pendingData.push(data);
  20013. };
  20014. Scene.prototype._removePendingData = function (data) {
  20015. var index = this._pendingData.indexOf(data);
  20016. if (index !== -1) {
  20017. this._pendingData.splice(index, 1);
  20018. }
  20019. };
  20020. Scene.prototype.getWaitingItemsCount = function () {
  20021. return this._pendingData.length;
  20022. };
  20023. /**
  20024. * Registers a function to be executed when the scene is ready.
  20025. * @param {Function} func - the function to be executed.
  20026. */
  20027. Scene.prototype.executeWhenReady = function (func) {
  20028. var _this = this;
  20029. this.onReadyObservable.add(func);
  20030. if (this._executeWhenReadyTimeoutId !== -1) {
  20031. return;
  20032. }
  20033. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20034. _this._checkIsReady();
  20035. }, 150);
  20036. };
  20037. Scene.prototype._checkIsReady = function () {
  20038. var _this = this;
  20039. if (this.isReady()) {
  20040. this.onReadyObservable.notifyObservers(this);
  20041. this.onReadyObservable.clear();
  20042. this._executeWhenReadyTimeoutId = -1;
  20043. return;
  20044. }
  20045. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20046. _this._checkIsReady();
  20047. }, 150);
  20048. };
  20049. // Animations
  20050. /**
  20051. * Will start the animation sequence of a given target
  20052. * @param target - the target
  20053. * @param {number} from - from which frame should animation start
  20054. * @param {number} to - till which frame should animation run.
  20055. * @param {boolean} [loop] - should the animation loop
  20056. * @param {number} [speedRatio] - the speed in which to run the animation
  20057. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20058. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20059. * @return {BABYLON.Animatable} the animatable object created for this animation
  20060. * @see BABYLON.Animatable
  20061. * @see http://doc.babylonjs.com/page.php?p=22081
  20062. */
  20063. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20064. if (speedRatio === void 0) { speedRatio = 1.0; }
  20065. this.stopAnimation(target);
  20066. if (!animatable) {
  20067. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20068. }
  20069. // Local animations
  20070. if (target.animations) {
  20071. animatable.appendAnimations(target, target.animations);
  20072. }
  20073. // Children animations
  20074. if (target.getAnimatables) {
  20075. var animatables = target.getAnimatables();
  20076. for (var index = 0; index < animatables.length; index++) {
  20077. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20078. }
  20079. }
  20080. animatable.reset();
  20081. return animatable;
  20082. };
  20083. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20084. if (speedRatio === undefined) {
  20085. speedRatio = 1.0;
  20086. }
  20087. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20088. return animatable;
  20089. };
  20090. Scene.prototype.getAnimatableByTarget = function (target) {
  20091. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20092. if (this._activeAnimatables[index].target === target) {
  20093. return this._activeAnimatables[index];
  20094. }
  20095. }
  20096. return null;
  20097. };
  20098. Object.defineProperty(Scene.prototype, "Animatables", {
  20099. get: function () {
  20100. return this._activeAnimatables;
  20101. },
  20102. enumerable: true,
  20103. configurable: true
  20104. });
  20105. /**
  20106. * Will stop the animation of the given target
  20107. * @param target - the target
  20108. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20109. * @see beginAnimation
  20110. */
  20111. Scene.prototype.stopAnimation = function (target, animationName) {
  20112. var animatable = this.getAnimatableByTarget(target);
  20113. if (animatable) {
  20114. animatable.stop(animationName);
  20115. }
  20116. };
  20117. Scene.prototype._animate = function () {
  20118. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20119. return;
  20120. }
  20121. // Getting time
  20122. var now = BABYLON.Tools.Now;
  20123. if (!this._animationTimeLast) {
  20124. if (this._pendingData.length > 0) {
  20125. return;
  20126. }
  20127. this._animationTimeLast = now;
  20128. }
  20129. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  20130. this._animationTime += deltaTime;
  20131. this._animationTimeLast = now;
  20132. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20133. this._activeAnimatables[index]._animate(this._animationTime);
  20134. }
  20135. };
  20136. // Matrix
  20137. Scene.prototype.getViewMatrix = function () {
  20138. return this._viewMatrix;
  20139. };
  20140. Scene.prototype.getProjectionMatrix = function () {
  20141. return this._projectionMatrix;
  20142. };
  20143. Scene.prototype.getTransformMatrix = function () {
  20144. return this._transformMatrix;
  20145. };
  20146. Scene.prototype.setTransformMatrix = function (view, projection) {
  20147. this._viewMatrix = view;
  20148. this._projectionMatrix = projection;
  20149. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20150. // Update frustum
  20151. if (!this._frustumPlanes) {
  20152. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20153. }
  20154. else {
  20155. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20156. }
  20157. };
  20158. // Methods
  20159. Scene.prototype.addMesh = function (newMesh) {
  20160. newMesh.uniqueId = this._uniqueIdCounter++;
  20161. var position = this.meshes.push(newMesh);
  20162. //notify the collision coordinator
  20163. this.collisionCoordinator.onMeshAdded(newMesh);
  20164. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  20165. };
  20166. Scene.prototype.removeMesh = function (toRemove) {
  20167. var index = this.meshes.indexOf(toRemove);
  20168. if (index !== -1) {
  20169. // Remove from the scene if mesh found
  20170. this.meshes.splice(index, 1);
  20171. }
  20172. //notify the collision coordinator
  20173. this.collisionCoordinator.onMeshRemoved(toRemove);
  20174. this.onMeshRemovedObservable.notifyObservers(toRemove);
  20175. return index;
  20176. };
  20177. Scene.prototype.removeSkeleton = function (toRemove) {
  20178. var index = this.skeletons.indexOf(toRemove);
  20179. if (index !== -1) {
  20180. // Remove from the scene if mesh found
  20181. this.skeletons.splice(index, 1);
  20182. }
  20183. return index;
  20184. };
  20185. Scene.prototype.removeLight = function (toRemove) {
  20186. var index = this.lights.indexOf(toRemove);
  20187. if (index !== -1) {
  20188. // Remove from the scene if mesh found
  20189. this.lights.splice(index, 1);
  20190. }
  20191. this.onLightRemovedObservable.notifyObservers(toRemove);
  20192. return index;
  20193. };
  20194. Scene.prototype.removeCamera = function (toRemove) {
  20195. var index = this.cameras.indexOf(toRemove);
  20196. if (index !== -1) {
  20197. // Remove from the scene if mesh found
  20198. this.cameras.splice(index, 1);
  20199. }
  20200. // Remove from activeCameras
  20201. var index2 = this.activeCameras.indexOf(toRemove);
  20202. if (index2 !== -1) {
  20203. // Remove from the scene if mesh found
  20204. this.activeCameras.splice(index2, 1);
  20205. }
  20206. // Reset the activeCamera
  20207. if (this.activeCamera === toRemove) {
  20208. if (this.cameras.length > 0) {
  20209. this.activeCamera = this.cameras[0];
  20210. }
  20211. else {
  20212. this.activeCamera = null;
  20213. }
  20214. }
  20215. this.onCameraRemovedObservable.notifyObservers(toRemove);
  20216. return index;
  20217. };
  20218. Scene.prototype.addLight = function (newLight) {
  20219. newLight.uniqueId = this._uniqueIdCounter++;
  20220. var position = this.lights.push(newLight);
  20221. this.onNewLightAddedObservable.notifyObservers(newLight);
  20222. };
  20223. Scene.prototype.addCamera = function (newCamera) {
  20224. newCamera.uniqueId = this._uniqueIdCounter++;
  20225. var position = this.cameras.push(newCamera);
  20226. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  20227. };
  20228. /**
  20229. * Switch active camera
  20230. * @param {Camera} newCamera - new active camera
  20231. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  20232. */
  20233. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  20234. if (attachControl === void 0) { attachControl = true; }
  20235. var canvas = this._engine.getRenderingCanvas();
  20236. this.activeCamera.detachControl(canvas);
  20237. this.activeCamera = newCamera;
  20238. if (attachControl) {
  20239. newCamera.attachControl(canvas);
  20240. }
  20241. };
  20242. /**
  20243. * sets the active camera of the scene using its ID
  20244. * @param {string} id - the camera's ID
  20245. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20246. * @see activeCamera
  20247. */
  20248. Scene.prototype.setActiveCameraByID = function (id) {
  20249. var camera = this.getCameraByID(id);
  20250. if (camera) {
  20251. this.activeCamera = camera;
  20252. return camera;
  20253. }
  20254. return null;
  20255. };
  20256. /**
  20257. * sets the active camera of the scene using its name
  20258. * @param {string} name - the camera's name
  20259. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20260. * @see activeCamera
  20261. */
  20262. Scene.prototype.setActiveCameraByName = function (name) {
  20263. var camera = this.getCameraByName(name);
  20264. if (camera) {
  20265. this.activeCamera = camera;
  20266. return camera;
  20267. }
  20268. return null;
  20269. };
  20270. /**
  20271. * get a material using its id
  20272. * @param {string} the material's ID
  20273. * @return {BABYLON.Material|null} the material or null if none found.
  20274. */
  20275. Scene.prototype.getMaterialByID = function (id) {
  20276. for (var index = 0; index < this.materials.length; index++) {
  20277. if (this.materials[index].id === id) {
  20278. return this.materials[index];
  20279. }
  20280. }
  20281. return null;
  20282. };
  20283. /**
  20284. * get a material using its name
  20285. * @param {string} the material's name
  20286. * @return {BABYLON.Material|null} the material or null if none found.
  20287. */
  20288. Scene.prototype.getMaterialByName = function (name) {
  20289. for (var index = 0; index < this.materials.length; index++) {
  20290. if (this.materials[index].name === name) {
  20291. return this.materials[index];
  20292. }
  20293. }
  20294. return null;
  20295. };
  20296. Scene.prototype.getLensFlareSystemByName = function (name) {
  20297. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20298. if (this.lensFlareSystems[index].name === name) {
  20299. return this.lensFlareSystems[index];
  20300. }
  20301. }
  20302. return null;
  20303. };
  20304. Scene.prototype.getLensFlareSystemByID = function (id) {
  20305. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20306. if (this.lensFlareSystems[index].id === id) {
  20307. return this.lensFlareSystems[index];
  20308. }
  20309. }
  20310. return null;
  20311. };
  20312. Scene.prototype.getCameraByID = function (id) {
  20313. for (var index = 0; index < this.cameras.length; index++) {
  20314. if (this.cameras[index].id === id) {
  20315. return this.cameras[index];
  20316. }
  20317. }
  20318. return null;
  20319. };
  20320. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  20321. for (var index = 0; index < this.cameras.length; index++) {
  20322. if (this.cameras[index].uniqueId === uniqueId) {
  20323. return this.cameras[index];
  20324. }
  20325. }
  20326. return null;
  20327. };
  20328. /**
  20329. * get a camera using its name
  20330. * @param {string} the camera's name
  20331. * @return {BABYLON.Camera|null} the camera or null if none found.
  20332. */
  20333. Scene.prototype.getCameraByName = function (name) {
  20334. for (var index = 0; index < this.cameras.length; index++) {
  20335. if (this.cameras[index].name === name) {
  20336. return this.cameras[index];
  20337. }
  20338. }
  20339. return null;
  20340. };
  20341. /**
  20342. * get a bone using its id
  20343. * @param {string} the bone's id
  20344. * @return {BABYLON.Bone|null} the bone or null if not found
  20345. */
  20346. Scene.prototype.getBoneByID = function (id) {
  20347. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20348. var skeleton = this.skeletons[skeletonIndex];
  20349. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20350. if (skeleton.bones[boneIndex].id === id) {
  20351. return skeleton.bones[boneIndex];
  20352. }
  20353. }
  20354. }
  20355. return null;
  20356. };
  20357. /**
  20358. * get a bone using its id
  20359. * @param {string} the bone's name
  20360. * @return {BABYLON.Bone|null} the bone or null if not found
  20361. */
  20362. Scene.prototype.getBoneByName = function (name) {
  20363. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20364. var skeleton = this.skeletons[skeletonIndex];
  20365. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20366. if (skeleton.bones[boneIndex].name === name) {
  20367. return skeleton.bones[boneIndex];
  20368. }
  20369. }
  20370. }
  20371. return null;
  20372. };
  20373. /**
  20374. * get a light node using its name
  20375. * @param {string} the light's name
  20376. * @return {BABYLON.Light|null} the light or null if none found.
  20377. */
  20378. Scene.prototype.getLightByName = function (name) {
  20379. for (var index = 0; index < this.lights.length; index++) {
  20380. if (this.lights[index].name === name) {
  20381. return this.lights[index];
  20382. }
  20383. }
  20384. return null;
  20385. };
  20386. /**
  20387. * get a light node using its ID
  20388. * @param {string} the light's id
  20389. * @return {BABYLON.Light|null} the light or null if none found.
  20390. */
  20391. Scene.prototype.getLightByID = function (id) {
  20392. for (var index = 0; index < this.lights.length; index++) {
  20393. if (this.lights[index].id === id) {
  20394. return this.lights[index];
  20395. }
  20396. }
  20397. return null;
  20398. };
  20399. /**
  20400. * get a light node using its scene-generated unique ID
  20401. * @param {number} the light's unique id
  20402. * @return {BABYLON.Light|null} the light or null if none found.
  20403. */
  20404. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  20405. for (var index = 0; index < this.lights.length; index++) {
  20406. if (this.lights[index].uniqueId === uniqueId) {
  20407. return this.lights[index];
  20408. }
  20409. }
  20410. return null;
  20411. };
  20412. /**
  20413. * get a particle system by id
  20414. * @param id {number} the particle system id
  20415. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  20416. */
  20417. Scene.prototype.getParticleSystemByID = function (id) {
  20418. for (var index = 0; index < this.particleSystems.length; index++) {
  20419. if (this.particleSystems[index].id === id) {
  20420. return this.particleSystems[index];
  20421. }
  20422. }
  20423. return null;
  20424. };
  20425. /**
  20426. * get a geometry using its ID
  20427. * @param {string} the geometry's id
  20428. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  20429. */
  20430. Scene.prototype.getGeometryByID = function (id) {
  20431. for (var index = 0; index < this._geometries.length; index++) {
  20432. if (this._geometries[index].id === id) {
  20433. return this._geometries[index];
  20434. }
  20435. }
  20436. return null;
  20437. };
  20438. /**
  20439. * add a new geometry to this scene.
  20440. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  20441. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  20442. * @return {boolean} was the geometry added or not
  20443. */
  20444. Scene.prototype.pushGeometry = function (geometry, force) {
  20445. if (!force && this.getGeometryByID(geometry.id)) {
  20446. return false;
  20447. }
  20448. this._geometries.push(geometry);
  20449. //notify the collision coordinator
  20450. this.collisionCoordinator.onGeometryAdded(geometry);
  20451. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  20452. return true;
  20453. };
  20454. /**
  20455. * Removes an existing geometry
  20456. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  20457. * @return {boolean} was the geometry removed or not
  20458. */
  20459. Scene.prototype.removeGeometry = function (geometry) {
  20460. var index = this._geometries.indexOf(geometry);
  20461. if (index > -1) {
  20462. this._geometries.splice(index, 1);
  20463. //notify the collision coordinator
  20464. this.collisionCoordinator.onGeometryDeleted(geometry);
  20465. this.onGeometryRemovedObservable.notifyObservers(geometry);
  20466. return true;
  20467. }
  20468. return false;
  20469. };
  20470. Scene.prototype.getGeometries = function () {
  20471. return this._geometries;
  20472. };
  20473. /**
  20474. * Get the first added mesh found of a given ID
  20475. * @param {string} id - the id to search for
  20476. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20477. */
  20478. Scene.prototype.getMeshByID = function (id) {
  20479. for (var index = 0; index < this.meshes.length; index++) {
  20480. if (this.meshes[index].id === id) {
  20481. return this.meshes[index];
  20482. }
  20483. }
  20484. return null;
  20485. };
  20486. Scene.prototype.getMeshesByID = function (id) {
  20487. return this.meshes.filter(function (m) {
  20488. return m.id === id;
  20489. });
  20490. };
  20491. /**
  20492. * Get a mesh with its auto-generated unique id
  20493. * @param {number} uniqueId - the unique id to search for
  20494. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20495. */
  20496. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  20497. for (var index = 0; index < this.meshes.length; index++) {
  20498. if (this.meshes[index].uniqueId === uniqueId) {
  20499. return this.meshes[index];
  20500. }
  20501. }
  20502. return null;
  20503. };
  20504. /**
  20505. * Get a the last added mesh found of a given ID
  20506. * @param {string} id - the id to search for
  20507. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20508. */
  20509. Scene.prototype.getLastMeshByID = function (id) {
  20510. for (var index = this.meshes.length - 1; index >= 0; index--) {
  20511. if (this.meshes[index].id === id) {
  20512. return this.meshes[index];
  20513. }
  20514. }
  20515. return null;
  20516. };
  20517. /**
  20518. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  20519. * @param {string} id - the id to search for
  20520. * @return {BABYLON.Node|null} the node found or null if not found at all.
  20521. */
  20522. Scene.prototype.getLastEntryByID = function (id) {
  20523. var index;
  20524. for (index = this.meshes.length - 1; index >= 0; index--) {
  20525. if (this.meshes[index].id === id) {
  20526. return this.meshes[index];
  20527. }
  20528. }
  20529. for (index = this.cameras.length - 1; index >= 0; index--) {
  20530. if (this.cameras[index].id === id) {
  20531. return this.cameras[index];
  20532. }
  20533. }
  20534. for (index = this.lights.length - 1; index >= 0; index--) {
  20535. if (this.lights[index].id === id) {
  20536. return this.lights[index];
  20537. }
  20538. }
  20539. return null;
  20540. };
  20541. Scene.prototype.getNodeByID = function (id) {
  20542. var mesh = this.getMeshByID(id);
  20543. if (mesh) {
  20544. return mesh;
  20545. }
  20546. var light = this.getLightByID(id);
  20547. if (light) {
  20548. return light;
  20549. }
  20550. var camera = this.getCameraByID(id);
  20551. if (camera) {
  20552. return camera;
  20553. }
  20554. var bone = this.getBoneByID(id);
  20555. return bone;
  20556. };
  20557. Scene.prototype.getNodeByName = function (name) {
  20558. var mesh = this.getMeshByName(name);
  20559. if (mesh) {
  20560. return mesh;
  20561. }
  20562. var light = this.getLightByName(name);
  20563. if (light) {
  20564. return light;
  20565. }
  20566. var camera = this.getCameraByName(name);
  20567. if (camera) {
  20568. return camera;
  20569. }
  20570. var bone = this.getBoneByName(name);
  20571. return bone;
  20572. };
  20573. Scene.prototype.getMeshByName = function (name) {
  20574. for (var index = 0; index < this.meshes.length; index++) {
  20575. if (this.meshes[index].name === name) {
  20576. return this.meshes[index];
  20577. }
  20578. }
  20579. return null;
  20580. };
  20581. Scene.prototype.getSoundByName = function (name) {
  20582. var index;
  20583. if (BABYLON.AudioEngine) {
  20584. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  20585. if (this.mainSoundTrack.soundCollection[index].name === name) {
  20586. return this.mainSoundTrack.soundCollection[index];
  20587. }
  20588. }
  20589. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  20590. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  20591. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  20592. return this.soundTracks[sdIndex].soundCollection[index];
  20593. }
  20594. }
  20595. }
  20596. }
  20597. return null;
  20598. };
  20599. Scene.prototype.getLastSkeletonByID = function (id) {
  20600. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  20601. if (this.skeletons[index].id === id) {
  20602. return this.skeletons[index];
  20603. }
  20604. }
  20605. return null;
  20606. };
  20607. Scene.prototype.getSkeletonById = function (id) {
  20608. for (var index = 0; index < this.skeletons.length; index++) {
  20609. if (this.skeletons[index].id === id) {
  20610. return this.skeletons[index];
  20611. }
  20612. }
  20613. return null;
  20614. };
  20615. Scene.prototype.getSkeletonByName = function (name) {
  20616. for (var index = 0; index < this.skeletons.length; index++) {
  20617. if (this.skeletons[index].name === name) {
  20618. return this.skeletons[index];
  20619. }
  20620. }
  20621. return null;
  20622. };
  20623. Scene.prototype.isActiveMesh = function (mesh) {
  20624. return (this._activeMeshes.indexOf(mesh) !== -1);
  20625. };
  20626. Object.defineProperty(Scene.prototype, "uid", {
  20627. /**
  20628. * Return a unique id as a string which can serve as an identifier for the scene
  20629. */
  20630. get: function () {
  20631. if (!this._uid) {
  20632. this._uid = BABYLON.Tools.RandomId();
  20633. }
  20634. return this._uid;
  20635. },
  20636. enumerable: true,
  20637. configurable: true
  20638. });
  20639. /**
  20640. * Add an externaly attached data from its key.
  20641. * This method call will fail and return false, if such key already exists.
  20642. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  20643. * @param key the unique key that identifies the data
  20644. * @param data the data object to associate to the key for this Engine instance
  20645. * @return true if no such key were already present and the data was added successfully, false otherwise
  20646. */
  20647. Scene.prototype.addExternalData = function (key, data) {
  20648. return this._externalData.add(key, data);
  20649. };
  20650. /**
  20651. * Get an externaly attached data from its key
  20652. * @param key the unique key that identifies the data
  20653. * @return the associated data, if present (can be null), or undefined if not present
  20654. */
  20655. Scene.prototype.getExternalData = function (key) {
  20656. return this._externalData.get(key);
  20657. };
  20658. /**
  20659. * Get an externaly attached data from its key, create it using a factory if it's not already present
  20660. * @param key the unique key that identifies the data
  20661. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  20662. * @return the associated data, can be null if the factory returned null.
  20663. */
  20664. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  20665. return this._externalData.getOrAddWithFactory(key, factory);
  20666. };
  20667. /**
  20668. * Remove an externaly attached data from the Engine instance
  20669. * @param key the unique key that identifies the data
  20670. * @return true if the data was successfully removed, false if it doesn't exist
  20671. */
  20672. Scene.prototype.removeExternalData = function (key) {
  20673. return this._externalData.remove(key);
  20674. };
  20675. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  20676. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  20677. var material = subMesh.getMaterial();
  20678. if (mesh.showSubMeshesBoundingBox) {
  20679. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  20680. }
  20681. if (material) {
  20682. // Render targets
  20683. if (material.getRenderTargetTextures) {
  20684. if (this._processedMaterials.indexOf(material) === -1) {
  20685. this._processedMaterials.push(material);
  20686. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  20687. }
  20688. }
  20689. // Dispatch
  20690. this._activeIndices.addCount(subMesh.indexCount, false);
  20691. this._renderingManager.dispatch(subMesh);
  20692. }
  20693. }
  20694. };
  20695. Scene.prototype._isInIntermediateRendering = function () {
  20696. return this._intermediateRendering;
  20697. };
  20698. Scene.prototype._evaluateActiveMeshes = function () {
  20699. this.activeCamera._activeMeshes.reset();
  20700. this._activeMeshes.reset();
  20701. this._renderingManager.reset();
  20702. this._processedMaterials.reset();
  20703. this._activeParticleSystems.reset();
  20704. this._activeSkeletons.reset();
  20705. this._softwareSkinnedMeshes.reset();
  20706. this._boundingBoxRenderer.reset();
  20707. this._edgesRenderers.reset();
  20708. // Meshes
  20709. var meshes;
  20710. var len;
  20711. if (this._selectionOctree) {
  20712. var selection = this._selectionOctree.select(this._frustumPlanes);
  20713. meshes = selection.data;
  20714. len = selection.length;
  20715. }
  20716. else {
  20717. len = this.meshes.length;
  20718. meshes = this.meshes;
  20719. }
  20720. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  20721. var mesh = meshes[meshIndex];
  20722. if (mesh.isBlocked) {
  20723. continue;
  20724. }
  20725. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  20726. if (!mesh.isReady() || !mesh.isEnabled()) {
  20727. continue;
  20728. }
  20729. mesh.computeWorldMatrix();
  20730. // Intersections
  20731. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  20732. this._meshesForIntersections.pushNoDuplicate(mesh);
  20733. }
  20734. // Switch to current LOD
  20735. var meshLOD = mesh.getLOD(this.activeCamera);
  20736. if (!meshLOD) {
  20737. continue;
  20738. }
  20739. mesh._preActivate();
  20740. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  20741. this._activeMeshes.push(mesh);
  20742. this.activeCamera._activeMeshes.push(mesh);
  20743. mesh._activate(this._renderId);
  20744. this._activeMesh(mesh, meshLOD);
  20745. }
  20746. }
  20747. // Particle systems
  20748. this._particlesDuration.beginMonitoring();
  20749. var beforeParticlesDate = BABYLON.Tools.Now;
  20750. if (this.particlesEnabled) {
  20751. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  20752. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  20753. var particleSystem = this.particleSystems[particleIndex];
  20754. if (!particleSystem.isStarted()) {
  20755. continue;
  20756. }
  20757. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  20758. this._activeParticleSystems.push(particleSystem);
  20759. particleSystem.animate();
  20760. this._renderingManager.dispatchParticles(particleSystem);
  20761. }
  20762. }
  20763. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  20764. }
  20765. this._particlesDuration.endMonitoring(false);
  20766. };
  20767. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  20768. if (mesh.skeleton && this.skeletonsEnabled) {
  20769. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  20770. mesh.skeleton.prepare();
  20771. }
  20772. if (!mesh.computeBonesUsingShaders) {
  20773. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  20774. }
  20775. }
  20776. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  20777. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  20778. }
  20779. if (sourceMesh._edgesRenderer) {
  20780. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  20781. }
  20782. if (mesh && mesh.subMeshes) {
  20783. // Submeshes Octrees
  20784. var len;
  20785. var subMeshes;
  20786. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  20787. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  20788. len = intersections.length;
  20789. subMeshes = intersections.data;
  20790. }
  20791. else {
  20792. subMeshes = mesh.subMeshes;
  20793. len = subMeshes.length;
  20794. }
  20795. for (var subIndex = 0; subIndex < len; subIndex++) {
  20796. var subMesh = subMeshes[subIndex];
  20797. this._evaluateSubMesh(subMesh, mesh);
  20798. }
  20799. }
  20800. };
  20801. Scene.prototype.updateTransformMatrix = function (force) {
  20802. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  20803. };
  20804. Scene.prototype._renderForCamera = function (camera) {
  20805. var engine = this._engine;
  20806. var startTime = BABYLON.Tools.Now;
  20807. this.activeCamera = camera;
  20808. if (!this.activeCamera)
  20809. throw new Error("Active camera not set");
  20810. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20811. // Viewport
  20812. engine.setViewport(this.activeCamera.viewport);
  20813. // Camera
  20814. this.resetCachedMaterial();
  20815. this._renderId++;
  20816. this.updateTransformMatrix();
  20817. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  20818. // Meshes
  20819. this._evaluateActiveMeshesDuration.beginMonitoring();
  20820. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  20821. this._evaluateActiveMeshes();
  20822. this._evaluateActiveMeshesDuration.endMonitoring(false);
  20823. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  20824. // Software skinning
  20825. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  20826. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  20827. mesh.applySkeleton(mesh.skeleton);
  20828. }
  20829. // Render targets
  20830. this._renderTargetsDuration.beginMonitoring();
  20831. var needsRestoreFrameBuffer = false;
  20832. var beforeRenderTargetDate = BABYLON.Tools.Now;
  20833. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  20834. this._intermediateRendering = true;
  20835. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20836. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  20837. var renderTarget = this._renderTargets.data[renderIndex];
  20838. if (renderTarget._shouldRender()) {
  20839. this._renderId++;
  20840. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  20841. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  20842. }
  20843. }
  20844. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20845. this._intermediateRendering = false;
  20846. this._renderId++;
  20847. needsRestoreFrameBuffer = true; // Restore back buffer
  20848. }
  20849. // Render HighlightLayer Texture
  20850. var stencilState = this._engine.getStencilBuffer();
  20851. var renderhighlights = false;
  20852. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  20853. this._intermediateRendering = true;
  20854. for (var i = 0; i < this.highlightLayers.length; i++) {
  20855. var highlightLayer = this.highlightLayers[i];
  20856. if (highlightLayer.shouldRender() &&
  20857. (!highlightLayer.camera ||
  20858. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  20859. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  20860. renderhighlights = true;
  20861. var renderTarget = highlightLayer._mainTexture;
  20862. if (renderTarget._shouldRender()) {
  20863. this._renderId++;
  20864. renderTarget.render(false, false);
  20865. needsRestoreFrameBuffer = true;
  20866. }
  20867. }
  20868. }
  20869. this._intermediateRendering = false;
  20870. this._renderId++;
  20871. }
  20872. if (needsRestoreFrameBuffer) {
  20873. engine.restoreDefaultFramebuffer();
  20874. }
  20875. this._renderTargetsDuration.endMonitoring(false);
  20876. // Prepare Frame
  20877. this.postProcessManager._prepareFrame();
  20878. this._renderDuration.beginMonitoring();
  20879. // Backgrounds
  20880. var layerIndex;
  20881. var layer;
  20882. if (this.layers.length) {
  20883. engine.setDepthBuffer(false);
  20884. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20885. layer = this.layers[layerIndex];
  20886. if (layer.isBackground) {
  20887. layer.render();
  20888. }
  20889. }
  20890. engine.setDepthBuffer(true);
  20891. }
  20892. // Render
  20893. BABYLON.Tools.StartPerformanceCounter("Main render");
  20894. // Activate HighlightLayer stencil
  20895. if (renderhighlights) {
  20896. this._engine.setStencilBuffer(true);
  20897. }
  20898. this._renderingManager.render(null, null, true, true);
  20899. // Restore HighlightLayer stencil
  20900. if (renderhighlights) {
  20901. this._engine.setStencilBuffer(stencilState);
  20902. }
  20903. BABYLON.Tools.EndPerformanceCounter("Main render");
  20904. // Bounding boxes
  20905. this._boundingBoxRenderer.render();
  20906. // Edges
  20907. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20908. this._edgesRenderers.data[edgesRendererIndex].render();
  20909. }
  20910. // Lens flares
  20911. if (this.lensFlaresEnabled) {
  20912. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20913. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  20914. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  20915. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  20916. lensFlareSystem.render();
  20917. }
  20918. }
  20919. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20920. }
  20921. // Foregrounds
  20922. if (this.layers.length) {
  20923. engine.setDepthBuffer(false);
  20924. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20925. layer = this.layers[layerIndex];
  20926. if (!layer.isBackground) {
  20927. layer.render();
  20928. }
  20929. }
  20930. engine.setDepthBuffer(true);
  20931. }
  20932. // Highlight Layer
  20933. if (renderhighlights) {
  20934. engine.setDepthBuffer(false);
  20935. for (var i = 0; i < this.highlightLayers.length; i++) {
  20936. if (this.highlightLayers[i].shouldRender()) {
  20937. this.highlightLayers[i].render();
  20938. }
  20939. }
  20940. engine.setDepthBuffer(true);
  20941. }
  20942. this._renderDuration.endMonitoring(false);
  20943. // Finalize frame
  20944. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  20945. // Update camera
  20946. this.activeCamera._updateFromScene();
  20947. // Reset some special arrays
  20948. this._renderTargets.reset();
  20949. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  20950. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20951. };
  20952. Scene.prototype._processSubCameras = function (camera) {
  20953. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  20954. this._renderForCamera(camera);
  20955. return;
  20956. }
  20957. // rig cameras
  20958. for (var index = 0; index < camera._rigCameras.length; index++) {
  20959. this._renderForCamera(camera._rigCameras[index]);
  20960. }
  20961. this.activeCamera = camera;
  20962. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  20963. // Update camera
  20964. this.activeCamera._updateFromScene();
  20965. };
  20966. Scene.prototype._checkIntersections = function () {
  20967. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  20968. var sourceMesh = this._meshesForIntersections.data[index];
  20969. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  20970. var action = sourceMesh.actionManager.actions[actionIndex];
  20971. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20972. var parameters = action.getTriggerParameter();
  20973. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  20974. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  20975. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  20976. if (areIntersecting && currentIntersectionInProgress === -1) {
  20977. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  20978. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  20979. sourceMesh._intersectionsInProgress.push(otherMesh);
  20980. }
  20981. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20982. sourceMesh._intersectionsInProgress.push(otherMesh);
  20983. }
  20984. }
  20985. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  20986. //They intersected, and now they don't.
  20987. //is this trigger an exit trigger? execute an event.
  20988. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20989. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  20990. }
  20991. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  20992. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20993. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  20994. }
  20995. }
  20996. }
  20997. }
  20998. }
  20999. };
  21000. Scene.prototype.render = function () {
  21001. this._lastFrameDuration.beginMonitoring();
  21002. this._particlesDuration.fetchNewFrame();
  21003. this._spritesDuration.fetchNewFrame();
  21004. this._activeParticles.fetchNewFrame();
  21005. this._renderDuration.fetchNewFrame();
  21006. this._renderTargetsDuration.fetchNewFrame();
  21007. this._evaluateActiveMeshesDuration.fetchNewFrame();
  21008. this._totalVertices.fetchNewFrame();
  21009. this._activeIndices.fetchNewFrame();
  21010. this._activeBones.fetchNewFrame();
  21011. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  21012. this._meshesForIntersections.reset();
  21013. this.resetCachedMaterial();
  21014. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  21015. // Actions
  21016. if (this.actionManager) {
  21017. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  21018. }
  21019. //Simplification Queue
  21020. if (this.simplificationQueue && !this.simplificationQueue.running) {
  21021. this.simplificationQueue.executeNext();
  21022. }
  21023. // Animations
  21024. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  21025. this._animationRatio = deltaTime * (60.0 / 1000.0);
  21026. this._animate();
  21027. // Physics
  21028. if (this._physicsEngine) {
  21029. BABYLON.Tools.StartPerformanceCounter("Physics");
  21030. this._physicsEngine._step(deltaTime / 1000.0);
  21031. BABYLON.Tools.EndPerformanceCounter("Physics");
  21032. }
  21033. // Before render
  21034. this.onBeforeRenderObservable.notifyObservers(this);
  21035. // Customs render targets
  21036. this._renderTargetsDuration.beginMonitoring();
  21037. var beforeRenderTargetDate = BABYLON.Tools.Now;
  21038. var engine = this.getEngine();
  21039. var currentActiveCamera = this.activeCamera;
  21040. if (this.renderTargetsEnabled) {
  21041. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21042. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  21043. var renderTarget = this.customRenderTargets[customIndex];
  21044. if (renderTarget._shouldRender()) {
  21045. this._renderId++;
  21046. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  21047. if (!this.activeCamera)
  21048. throw new Error("Active camera not set");
  21049. // Viewport
  21050. engine.setViewport(this.activeCamera.viewport);
  21051. // Camera
  21052. this.updateTransformMatrix();
  21053. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  21054. }
  21055. }
  21056. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21057. this._renderId++;
  21058. }
  21059. if (this.customRenderTargets.length > 0) {
  21060. engine.restoreDefaultFramebuffer();
  21061. }
  21062. this._renderTargetsDuration.endMonitoring();
  21063. this.activeCamera = currentActiveCamera;
  21064. // Procedural textures
  21065. if (this.proceduralTexturesEnabled) {
  21066. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21067. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  21068. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  21069. if (proceduralTexture._shouldRender()) {
  21070. proceduralTexture.render();
  21071. }
  21072. }
  21073. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21074. }
  21075. // Clear
  21076. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  21077. // Shadows
  21078. if (this.shadowsEnabled) {
  21079. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  21080. var light = this.lights[lightIndex];
  21081. var shadowGenerator = light.getShadowGenerator();
  21082. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  21083. this._renderTargets.push(shadowGenerator.getShadowMap());
  21084. }
  21085. }
  21086. }
  21087. // Depth renderer
  21088. if (this._depthRenderer) {
  21089. this._renderTargets.push(this._depthRenderer.getDepthMap());
  21090. }
  21091. // RenderPipeline
  21092. this.postProcessRenderPipelineManager.update();
  21093. // Multi-cameras?
  21094. if (this.activeCameras.length > 0) {
  21095. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  21096. if (cameraIndex > 0) {
  21097. this._engine.clear(null, false, true, true);
  21098. }
  21099. this._processSubCameras(this.activeCameras[cameraIndex]);
  21100. }
  21101. }
  21102. else {
  21103. if (!this.activeCamera) {
  21104. throw new Error("No camera defined");
  21105. }
  21106. this._processSubCameras(this.activeCamera);
  21107. }
  21108. // Intersection checks
  21109. this._checkIntersections();
  21110. // Update the audio listener attached to the camera
  21111. if (BABYLON.AudioEngine) {
  21112. this._updateAudioParameters();
  21113. }
  21114. // After render
  21115. if (this.afterRender) {
  21116. this.afterRender();
  21117. }
  21118. this.onAfterRenderObservable.notifyObservers(this);
  21119. // Cleaning
  21120. for (var index = 0; index < this._toBeDisposed.length; index++) {
  21121. this._toBeDisposed.data[index].dispose();
  21122. this._toBeDisposed[index] = null;
  21123. }
  21124. this._toBeDisposed.reset();
  21125. if (this.dumpNextRenderTargets) {
  21126. this.dumpNextRenderTargets = false;
  21127. }
  21128. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  21129. this._lastFrameDuration.endMonitoring();
  21130. this._totalMeshesCounter.addCount(this.meshes.length, true);
  21131. this._totalLightsCounter.addCount(this.lights.length, true);
  21132. this._totalMaterialsCounter.addCount(this.materials.length, true);
  21133. this._totalTexturesCounter.addCount(this.textures.length, true);
  21134. this._activeBones.addCount(0, true);
  21135. this._activeIndices.addCount(0, true);
  21136. this._activeParticles.addCount(0, true);
  21137. };
  21138. Scene.prototype._updateAudioParameters = function () {
  21139. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  21140. return;
  21141. }
  21142. var listeningCamera;
  21143. var audioEngine = BABYLON.Engine.audioEngine;
  21144. if (this.activeCameras.length > 0) {
  21145. listeningCamera = this.activeCameras[0];
  21146. }
  21147. else {
  21148. listeningCamera = this.activeCamera;
  21149. }
  21150. if (listeningCamera && audioEngine.canUseWebAudio) {
  21151. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  21152. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  21153. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  21154. cameraDirection.normalize();
  21155. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  21156. var i;
  21157. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21158. var sound = this.mainSoundTrack.soundCollection[i];
  21159. if (sound.useCustomAttenuation) {
  21160. sound.updateDistanceFromListener();
  21161. }
  21162. }
  21163. for (i = 0; i < this.soundTracks.length; i++) {
  21164. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21165. sound = this.soundTracks[i].soundCollection[j];
  21166. if (sound.useCustomAttenuation) {
  21167. sound.updateDistanceFromListener();
  21168. }
  21169. }
  21170. }
  21171. }
  21172. };
  21173. Object.defineProperty(Scene.prototype, "audioEnabled", {
  21174. // Audio
  21175. get: function () {
  21176. return this._audioEnabled;
  21177. },
  21178. set: function (value) {
  21179. this._audioEnabled = value;
  21180. if (BABYLON.AudioEngine) {
  21181. if (this._audioEnabled) {
  21182. this._enableAudio();
  21183. }
  21184. else {
  21185. this._disableAudio();
  21186. }
  21187. }
  21188. },
  21189. enumerable: true,
  21190. configurable: true
  21191. });
  21192. Scene.prototype._disableAudio = function () {
  21193. var i;
  21194. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21195. this.mainSoundTrack.soundCollection[i].pause();
  21196. }
  21197. for (i = 0; i < this.soundTracks.length; i++) {
  21198. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21199. this.soundTracks[i].soundCollection[j].pause();
  21200. }
  21201. }
  21202. };
  21203. Scene.prototype._enableAudio = function () {
  21204. var i;
  21205. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21206. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  21207. this.mainSoundTrack.soundCollection[i].play();
  21208. }
  21209. }
  21210. for (i = 0; i < this.soundTracks.length; i++) {
  21211. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21212. if (this.soundTracks[i].soundCollection[j].isPaused) {
  21213. this.soundTracks[i].soundCollection[j].play();
  21214. }
  21215. }
  21216. }
  21217. };
  21218. Object.defineProperty(Scene.prototype, "headphone", {
  21219. get: function () {
  21220. return this._headphone;
  21221. },
  21222. set: function (value) {
  21223. this._headphone = value;
  21224. if (BABYLON.AudioEngine) {
  21225. if (this._headphone) {
  21226. this._switchAudioModeForHeadphones();
  21227. }
  21228. else {
  21229. this._switchAudioModeForNormalSpeakers();
  21230. }
  21231. }
  21232. },
  21233. enumerable: true,
  21234. configurable: true
  21235. });
  21236. Scene.prototype._switchAudioModeForHeadphones = function () {
  21237. this.mainSoundTrack.switchPanningModelToHRTF();
  21238. for (var i = 0; i < this.soundTracks.length; i++) {
  21239. this.soundTracks[i].switchPanningModelToHRTF();
  21240. }
  21241. };
  21242. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  21243. this.mainSoundTrack.switchPanningModelToEqualPower();
  21244. for (var i = 0; i < this.soundTracks.length; i++) {
  21245. this.soundTracks[i].switchPanningModelToEqualPower();
  21246. }
  21247. };
  21248. Scene.prototype.enableDepthRenderer = function () {
  21249. if (this._depthRenderer) {
  21250. return this._depthRenderer;
  21251. }
  21252. this._depthRenderer = new BABYLON.DepthRenderer(this);
  21253. return this._depthRenderer;
  21254. };
  21255. Scene.prototype.disableDepthRenderer = function () {
  21256. if (!this._depthRenderer) {
  21257. return;
  21258. }
  21259. this._depthRenderer.dispose();
  21260. this._depthRenderer = null;
  21261. };
  21262. Scene.prototype.freezeMaterials = function () {
  21263. for (var i = 0; i < this.materials.length; i++) {
  21264. this.materials[i].freeze();
  21265. }
  21266. };
  21267. Scene.prototype.unfreezeMaterials = function () {
  21268. for (var i = 0; i < this.materials.length; i++) {
  21269. this.materials[i].unfreeze();
  21270. }
  21271. };
  21272. Scene.prototype.dispose = function () {
  21273. this.beforeRender = null;
  21274. this.afterRender = null;
  21275. this.skeletons = [];
  21276. this._boundingBoxRenderer.dispose();
  21277. if (this._depthRenderer) {
  21278. this._depthRenderer.dispose();
  21279. }
  21280. // Debug layer
  21281. if (this._debugLayer) {
  21282. this._debugLayer.hide();
  21283. }
  21284. // Events
  21285. this.onDisposeObservable.notifyObservers(this);
  21286. this.onDisposeObservable.clear();
  21287. this.onBeforeRenderObservable.clear();
  21288. this.onAfterRenderObservable.clear();
  21289. this.detachControl();
  21290. // Release sounds & sounds tracks
  21291. if (BABYLON.AudioEngine) {
  21292. this.disposeSounds();
  21293. }
  21294. // Detach cameras
  21295. var canvas = this._engine.getRenderingCanvas();
  21296. var index;
  21297. for (index = 0; index < this.cameras.length; index++) {
  21298. this.cameras[index].detachControl(canvas);
  21299. }
  21300. // Release lights
  21301. while (this.lights.length) {
  21302. this.lights[0].dispose();
  21303. }
  21304. // Release meshes
  21305. while (this.meshes.length) {
  21306. this.meshes[0].dispose(true);
  21307. }
  21308. // Release cameras
  21309. while (this.cameras.length) {
  21310. this.cameras[0].dispose();
  21311. }
  21312. // Release materials
  21313. while (this.materials.length) {
  21314. this.materials[0].dispose();
  21315. }
  21316. // Release particles
  21317. while (this.particleSystems.length) {
  21318. this.particleSystems[0].dispose();
  21319. }
  21320. // Release sprites
  21321. while (this.spriteManagers.length) {
  21322. this.spriteManagers[0].dispose();
  21323. }
  21324. // Release layers
  21325. while (this.layers.length) {
  21326. this.layers[0].dispose();
  21327. }
  21328. while (this.highlightLayers.length) {
  21329. this.highlightLayers[0].dispose();
  21330. }
  21331. // Release textures
  21332. while (this.textures.length) {
  21333. this.textures[0].dispose();
  21334. }
  21335. // Post-processes
  21336. this.postProcessManager.dispose();
  21337. // Physics
  21338. if (this._physicsEngine) {
  21339. this.disablePhysicsEngine();
  21340. }
  21341. // Remove from engine
  21342. index = this._engine.scenes.indexOf(this);
  21343. if (index > -1) {
  21344. this._engine.scenes.splice(index, 1);
  21345. }
  21346. this._engine.wipeCaches();
  21347. };
  21348. // Release sounds & sounds tracks
  21349. Scene.prototype.disposeSounds = function () {
  21350. this.mainSoundTrack.dispose();
  21351. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21352. this.soundTracks[scIndex].dispose();
  21353. }
  21354. };
  21355. // Octrees
  21356. Scene.prototype.getWorldExtends = function () {
  21357. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21358. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21359. for (var index = 0; index < this.meshes.length; index++) {
  21360. var mesh = this.meshes[index];
  21361. mesh.computeWorldMatrix(true);
  21362. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  21363. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  21364. BABYLON.Tools.CheckExtends(minBox, min, max);
  21365. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21366. }
  21367. return {
  21368. min: min,
  21369. max: max
  21370. };
  21371. };
  21372. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21373. if (maxCapacity === void 0) { maxCapacity = 64; }
  21374. if (maxDepth === void 0) { maxDepth = 2; }
  21375. if (!this._selectionOctree) {
  21376. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21377. }
  21378. var worldExtends = this.getWorldExtends();
  21379. // Update octree
  21380. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21381. return this._selectionOctree;
  21382. };
  21383. // Picking
  21384. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21385. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21386. var engine = this._engine;
  21387. if (!camera) {
  21388. if (!this.activeCamera)
  21389. throw new Error("Active camera not set");
  21390. camera = this.activeCamera;
  21391. }
  21392. var cameraViewport = camera.viewport;
  21393. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21394. // Moving coordinates to local viewport world
  21395. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21396. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21397. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21398. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  21399. };
  21400. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21401. var engine = this._engine;
  21402. if (!camera) {
  21403. if (!this.activeCamera)
  21404. throw new Error("Active camera not set");
  21405. camera = this.activeCamera;
  21406. }
  21407. var cameraViewport = camera.viewport;
  21408. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21409. var identity = BABYLON.Matrix.Identity();
  21410. // Moving coordinates to local viewport world
  21411. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21412. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21413. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21414. };
  21415. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21416. var pickingInfo = null;
  21417. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21418. var mesh = this.meshes[meshIndex];
  21419. if (predicate) {
  21420. if (!predicate(mesh)) {
  21421. continue;
  21422. }
  21423. }
  21424. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21425. continue;
  21426. }
  21427. var world = mesh.getWorldMatrix();
  21428. var ray = rayFunction(world);
  21429. var result = mesh.intersects(ray, fastCheck);
  21430. if (!result || !result.hit)
  21431. continue;
  21432. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21433. continue;
  21434. pickingInfo = result;
  21435. if (fastCheck) {
  21436. break;
  21437. }
  21438. }
  21439. return pickingInfo || new BABYLON.PickingInfo();
  21440. };
  21441. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  21442. var pickingInfos = new Array();
  21443. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21444. var mesh = this.meshes[meshIndex];
  21445. if (predicate) {
  21446. if (!predicate(mesh)) {
  21447. continue;
  21448. }
  21449. }
  21450. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21451. continue;
  21452. }
  21453. var world = mesh.getWorldMatrix();
  21454. var ray = rayFunction(world);
  21455. var result = mesh.intersects(ray, false);
  21456. if (!result || !result.hit)
  21457. continue;
  21458. pickingInfos.push(result);
  21459. }
  21460. return pickingInfos;
  21461. };
  21462. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  21463. var pickingInfo = null;
  21464. camera = camera || this.activeCamera;
  21465. if (this.spriteManagers.length > 0) {
  21466. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  21467. var spriteManager = this.spriteManagers[spriteIndex];
  21468. if (!spriteManager.isPickable) {
  21469. continue;
  21470. }
  21471. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  21472. if (!result || !result.hit)
  21473. continue;
  21474. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21475. continue;
  21476. pickingInfo = result;
  21477. if (fastCheck) {
  21478. break;
  21479. }
  21480. }
  21481. }
  21482. return pickingInfo || new BABYLON.PickingInfo();
  21483. };
  21484. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  21485. /// <param name="x">X position on screen</param>
  21486. /// <param name="y">Y position on screen</param>
  21487. /// <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>
  21488. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  21489. /// <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>
  21490. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  21491. var _this = this;
  21492. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  21493. };
  21494. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  21495. /// <param name="x">X position on screen</param>
  21496. /// <param name="y">Y position on screen</param>
  21497. /// <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>
  21498. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  21499. /// <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>
  21500. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  21501. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  21502. };
  21503. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  21504. var _this = this;
  21505. return this._internalPick(function (world) {
  21506. if (!_this._pickWithRayInverseMatrix) {
  21507. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21508. }
  21509. world.invertToRef(_this._pickWithRayInverseMatrix);
  21510. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  21511. }, predicate, fastCheck);
  21512. };
  21513. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  21514. /// <param name="x">X position on screen</param>
  21515. /// <param name="y">Y position on screen</param>
  21516. /// <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>
  21517. /// <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>
  21518. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  21519. var _this = this;
  21520. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  21521. };
  21522. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  21523. /// <param name="ray">Ray to use</param>
  21524. /// <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>
  21525. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  21526. var _this = this;
  21527. return this._internalMultiPick(function (world) {
  21528. if (!_this._pickWithRayInverseMatrix) {
  21529. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21530. }
  21531. world.invertToRef(_this._pickWithRayInverseMatrix);
  21532. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  21533. }, predicate);
  21534. };
  21535. Scene.prototype.setPointerOverMesh = function (mesh) {
  21536. if (this._pointerOverMesh === mesh) {
  21537. return;
  21538. }
  21539. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21540. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21541. }
  21542. this._pointerOverMesh = mesh;
  21543. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21544. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21545. }
  21546. };
  21547. Scene.prototype.getPointerOverMesh = function () {
  21548. return this._pointerOverMesh;
  21549. };
  21550. Scene.prototype.setPointerOverSprite = function (sprite) {
  21551. if (this._pointerOverSprite === sprite) {
  21552. return;
  21553. }
  21554. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21555. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21556. }
  21557. this._pointerOverSprite = sprite;
  21558. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21559. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21560. }
  21561. };
  21562. Scene.prototype.getPointerOverSprite = function () {
  21563. return this._pointerOverSprite;
  21564. };
  21565. // Physics
  21566. Scene.prototype.getPhysicsEngine = function () {
  21567. return this._physicsEngine;
  21568. };
  21569. /**
  21570. * Enables physics to the current scene
  21571. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  21572. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  21573. * @return {boolean} was the physics engine initialized
  21574. */
  21575. Scene.prototype.enablePhysics = function (gravity, plugin) {
  21576. if (this._physicsEngine) {
  21577. return true;
  21578. }
  21579. try {
  21580. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  21581. return true;
  21582. }
  21583. catch (e) {
  21584. BABYLON.Tools.Error(e.message);
  21585. return false;
  21586. }
  21587. };
  21588. Scene.prototype.disablePhysicsEngine = function () {
  21589. if (!this._physicsEngine) {
  21590. return;
  21591. }
  21592. this._physicsEngine.dispose();
  21593. this._physicsEngine = undefined;
  21594. };
  21595. Scene.prototype.isPhysicsEnabled = function () {
  21596. return this._physicsEngine !== undefined;
  21597. };
  21598. /**
  21599. *
  21600. * Sets the gravity of the physics engine (and NOT of the scene)
  21601. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  21602. */
  21603. Scene.prototype.setGravity = function (gravity) {
  21604. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  21605. if (!this._physicsEngine) {
  21606. return;
  21607. }
  21608. this._physicsEngine.setGravity(gravity);
  21609. };
  21610. /**
  21611. * Legacy support, using the new API
  21612. * @Deprecated
  21613. */
  21614. Scene.prototype.createCompoundImpostor = function (parts, options) {
  21615. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  21616. if (parts.parts) {
  21617. options = parts;
  21618. parts = parts.parts;
  21619. }
  21620. var mainMesh = parts[0].mesh;
  21621. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  21622. for (var index = 1; index < parts.length; index++) {
  21623. var mesh = parts[index].mesh;
  21624. if (mesh.parent !== mainMesh) {
  21625. mesh.position = mesh.position.subtract(mainMesh.position);
  21626. mesh.parent = mainMesh;
  21627. }
  21628. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  21629. }
  21630. mainMesh.physicsImpostor.forceUpdate();
  21631. };
  21632. Scene.prototype.deleteCompoundImpostor = function (compound) {
  21633. var mesh = compound.parts[0].mesh;
  21634. mesh.physicsImpostor.dispose();
  21635. mesh.physicsImpostor = null;
  21636. };
  21637. // Misc.
  21638. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  21639. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  21640. // Light
  21641. if (this.lights.length === 0) {
  21642. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  21643. }
  21644. // Camera
  21645. if (!this.activeCamera) {
  21646. // Compute position
  21647. var worldExtends = this.getWorldExtends();
  21648. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  21649. var camera;
  21650. if (createArcRotateCamera) {
  21651. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  21652. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  21653. camera.setTarget(worldCenter);
  21654. }
  21655. else {
  21656. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  21657. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  21658. camera.setTarget(worldCenter);
  21659. }
  21660. this.activeCamera = camera;
  21661. }
  21662. };
  21663. // Tags
  21664. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  21665. if (tagsQuery === undefined) {
  21666. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  21667. return list;
  21668. }
  21669. var listByTags = [];
  21670. forEach = forEach || (function (item) { return; });
  21671. for (var i in list) {
  21672. var item = list[i];
  21673. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  21674. listByTags.push(item);
  21675. forEach(item);
  21676. }
  21677. }
  21678. return listByTags;
  21679. };
  21680. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  21681. return this._getByTags(this.meshes, tagsQuery, forEach);
  21682. };
  21683. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  21684. return this._getByTags(this.cameras, tagsQuery, forEach);
  21685. };
  21686. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  21687. return this._getByTags(this.lights, tagsQuery, forEach);
  21688. };
  21689. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  21690. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  21691. };
  21692. /**
  21693. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21694. * This allowed control for front to back rendering or reversly depending of the special needs.
  21695. *
  21696. * @param renderingGroupId The rendering group id corresponding to its index
  21697. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21698. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21699. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21700. */
  21701. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21702. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21703. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21704. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21705. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  21706. };
  21707. /**
  21708. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21709. *
  21710. * @param renderingGroupId The rendering group id corresponding to its index
  21711. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21712. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21713. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21714. */
  21715. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21716. if (depth === void 0) { depth = true; }
  21717. if (stencil === void 0) { stencil = true; }
  21718. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  21719. };
  21720. return Scene;
  21721. }());
  21722. // Statics
  21723. Scene._FOGMODE_NONE = 0;
  21724. Scene._FOGMODE_EXP = 1;
  21725. Scene._FOGMODE_EXP2 = 2;
  21726. Scene._FOGMODE_LINEAR = 3;
  21727. Scene.MinDeltaTime = 1.0;
  21728. Scene.MaxDeltaTime = 1000.0;
  21729. BABYLON.Scene = Scene;
  21730. })(BABYLON || (BABYLON = {}));
  21731. //# sourceMappingURL=babylon.scene.js.map
  21732. var BABYLON;
  21733. (function (BABYLON) {
  21734. var Buffer = (function () {
  21735. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  21736. if (engine instanceof BABYLON.Mesh) {
  21737. this._engine = engine.getScene().getEngine();
  21738. }
  21739. else {
  21740. this._engine = engine;
  21741. }
  21742. this._updatable = updatable;
  21743. this._data = data;
  21744. this._strideSize = stride;
  21745. if (!postponeInternalCreation) {
  21746. this.create();
  21747. }
  21748. this._instanced = instanced;
  21749. }
  21750. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21751. // a lot of these parameters are ignored as they are overriden by the buffer
  21752. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21753. };
  21754. // Properties
  21755. Buffer.prototype.isUpdatable = function () {
  21756. return this._updatable;
  21757. };
  21758. Buffer.prototype.getData = function () {
  21759. return this._data;
  21760. };
  21761. Buffer.prototype.getBuffer = function () {
  21762. return this._buffer;
  21763. };
  21764. Buffer.prototype.getStrideSize = function () {
  21765. return this._strideSize;
  21766. };
  21767. Buffer.prototype.getIsInstanced = function () {
  21768. return this._instanced;
  21769. };
  21770. // Methods
  21771. Buffer.prototype.create = function (data) {
  21772. if (!data && this._buffer) {
  21773. return; // nothing to do
  21774. }
  21775. data = data || this._data;
  21776. if (!this._buffer) {
  21777. if (this._updatable) {
  21778. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21779. this._data = data;
  21780. }
  21781. else {
  21782. this._buffer = this._engine.createVertexBuffer(data);
  21783. }
  21784. }
  21785. else if (this._updatable) {
  21786. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21787. this._data = data;
  21788. }
  21789. };
  21790. Buffer.prototype.update = function (data) {
  21791. this.create(data);
  21792. };
  21793. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21794. if (!this._buffer) {
  21795. return;
  21796. }
  21797. if (this._updatable) {
  21798. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21799. this._data = null;
  21800. }
  21801. };
  21802. Buffer.prototype.dispose = function () {
  21803. if (!this._buffer) {
  21804. return;
  21805. }
  21806. if (this._engine._releaseBuffer(this._buffer)) {
  21807. this._buffer = null;
  21808. }
  21809. };
  21810. return Buffer;
  21811. }());
  21812. BABYLON.Buffer = Buffer;
  21813. })(BABYLON || (BABYLON = {}));
  21814. //# sourceMappingURL=babylon.buffer.js.map
  21815. var BABYLON;
  21816. (function (BABYLON) {
  21817. var VertexBuffer = (function () {
  21818. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21819. if (!stride) {
  21820. // Deduce stride from kind
  21821. switch (kind) {
  21822. case VertexBuffer.PositionKind:
  21823. stride = 3;
  21824. break;
  21825. case VertexBuffer.NormalKind:
  21826. stride = 3;
  21827. break;
  21828. case VertexBuffer.UVKind:
  21829. case VertexBuffer.UV2Kind:
  21830. case VertexBuffer.UV3Kind:
  21831. case VertexBuffer.UV4Kind:
  21832. case VertexBuffer.UV5Kind:
  21833. case VertexBuffer.UV6Kind:
  21834. stride = 2;
  21835. break;
  21836. case VertexBuffer.ColorKind:
  21837. stride = 4;
  21838. break;
  21839. case VertexBuffer.MatricesIndicesKind:
  21840. case VertexBuffer.MatricesIndicesExtraKind:
  21841. stride = 4;
  21842. break;
  21843. case VertexBuffer.MatricesWeightsKind:
  21844. case VertexBuffer.MatricesWeightsExtraKind:
  21845. stride = 4;
  21846. break;
  21847. }
  21848. }
  21849. if (data instanceof BABYLON.Buffer) {
  21850. if (!stride) {
  21851. stride = data.getStrideSize();
  21852. }
  21853. this._buffer = data;
  21854. this._ownsBuffer = false;
  21855. }
  21856. else {
  21857. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21858. this._ownsBuffer = true;
  21859. }
  21860. this._stride = stride;
  21861. this._offset = offset ? offset : 0;
  21862. this._size = size ? size : stride;
  21863. this._kind = kind;
  21864. }
  21865. /**
  21866. * Returns the kind of the VertexBuffer (string).
  21867. */
  21868. VertexBuffer.prototype.getKind = function () {
  21869. return this._kind;
  21870. };
  21871. // Properties
  21872. /**
  21873. * Boolean : is the VertexBuffer updatable ?
  21874. */
  21875. VertexBuffer.prototype.isUpdatable = function () {
  21876. return this._buffer.isUpdatable();
  21877. };
  21878. /**
  21879. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21880. */
  21881. VertexBuffer.prototype.getData = function () {
  21882. return this._buffer.getData();
  21883. };
  21884. /**
  21885. * Returns the WebGLBuffer associated to the VertexBuffer.
  21886. */
  21887. VertexBuffer.prototype.getBuffer = function () {
  21888. return this._buffer.getBuffer();
  21889. };
  21890. /**
  21891. * Returns the stride of the VertexBuffer (integer).
  21892. */
  21893. VertexBuffer.prototype.getStrideSize = function () {
  21894. return this._stride;
  21895. };
  21896. /**
  21897. * Returns the offset (integer).
  21898. */
  21899. VertexBuffer.prototype.getOffset = function () {
  21900. return this._offset;
  21901. };
  21902. /**
  21903. * Returns the VertexBuffer total size (integer).
  21904. */
  21905. VertexBuffer.prototype.getSize = function () {
  21906. return this._size;
  21907. };
  21908. /**
  21909. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21910. */
  21911. VertexBuffer.prototype.getIsInstanced = function () {
  21912. return this._buffer.getIsInstanced();
  21913. };
  21914. // Methods
  21915. /**
  21916. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21917. * Returns the created WebGLBuffer.
  21918. */
  21919. VertexBuffer.prototype.create = function (data) {
  21920. return this._buffer.create(data);
  21921. };
  21922. /**
  21923. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21924. * Returns the updated WebGLBuffer.
  21925. */
  21926. VertexBuffer.prototype.update = function (data) {
  21927. return this._buffer.update(data);
  21928. };
  21929. /**
  21930. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21931. * Returns the directly updated WebGLBuffer.
  21932. */
  21933. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21934. return this._buffer.updateDirectly(data, offset);
  21935. };
  21936. /**
  21937. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21938. */
  21939. VertexBuffer.prototype.dispose = function () {
  21940. if (this._ownsBuffer) {
  21941. this._buffer.dispose();
  21942. }
  21943. };
  21944. Object.defineProperty(VertexBuffer, "PositionKind", {
  21945. get: function () {
  21946. return VertexBuffer._PositionKind;
  21947. },
  21948. enumerable: true,
  21949. configurable: true
  21950. });
  21951. Object.defineProperty(VertexBuffer, "NormalKind", {
  21952. get: function () {
  21953. return VertexBuffer._NormalKind;
  21954. },
  21955. enumerable: true,
  21956. configurable: true
  21957. });
  21958. Object.defineProperty(VertexBuffer, "UVKind", {
  21959. get: function () {
  21960. return VertexBuffer._UVKind;
  21961. },
  21962. enumerable: true,
  21963. configurable: true
  21964. });
  21965. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21966. get: function () {
  21967. return VertexBuffer._UV2Kind;
  21968. },
  21969. enumerable: true,
  21970. configurable: true
  21971. });
  21972. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21973. get: function () {
  21974. return VertexBuffer._UV3Kind;
  21975. },
  21976. enumerable: true,
  21977. configurable: true
  21978. });
  21979. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21980. get: function () {
  21981. return VertexBuffer._UV4Kind;
  21982. },
  21983. enumerable: true,
  21984. configurable: true
  21985. });
  21986. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21987. get: function () {
  21988. return VertexBuffer._UV5Kind;
  21989. },
  21990. enumerable: true,
  21991. configurable: true
  21992. });
  21993. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21994. get: function () {
  21995. return VertexBuffer._UV6Kind;
  21996. },
  21997. enumerable: true,
  21998. configurable: true
  21999. });
  22000. Object.defineProperty(VertexBuffer, "ColorKind", {
  22001. get: function () {
  22002. return VertexBuffer._ColorKind;
  22003. },
  22004. enumerable: true,
  22005. configurable: true
  22006. });
  22007. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  22008. get: function () {
  22009. return VertexBuffer._MatricesIndicesKind;
  22010. },
  22011. enumerable: true,
  22012. configurable: true
  22013. });
  22014. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  22015. get: function () {
  22016. return VertexBuffer._MatricesWeightsKind;
  22017. },
  22018. enumerable: true,
  22019. configurable: true
  22020. });
  22021. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  22022. get: function () {
  22023. return VertexBuffer._MatricesIndicesExtraKind;
  22024. },
  22025. enumerable: true,
  22026. configurable: true
  22027. });
  22028. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  22029. get: function () {
  22030. return VertexBuffer._MatricesWeightsExtraKind;
  22031. },
  22032. enumerable: true,
  22033. configurable: true
  22034. });
  22035. return VertexBuffer;
  22036. }());
  22037. // Enums
  22038. VertexBuffer._PositionKind = "position";
  22039. VertexBuffer._NormalKind = "normal";
  22040. VertexBuffer._UVKind = "uv";
  22041. VertexBuffer._UV2Kind = "uv2";
  22042. VertexBuffer._UV3Kind = "uv3";
  22043. VertexBuffer._UV4Kind = "uv4";
  22044. VertexBuffer._UV5Kind = "uv5";
  22045. VertexBuffer._UV6Kind = "uv6";
  22046. VertexBuffer._ColorKind = "color";
  22047. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  22048. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  22049. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  22050. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  22051. BABYLON.VertexBuffer = VertexBuffer;
  22052. })(BABYLON || (BABYLON = {}));
  22053. //# sourceMappingURL=babylon.vertexBuffer.js.map
  22054. var BABYLON;
  22055. (function (BABYLON) {
  22056. /**
  22057. * Creates an instance based on a source mesh.
  22058. */
  22059. var InstancedMesh = (function (_super) {
  22060. __extends(InstancedMesh, _super);
  22061. function InstancedMesh(name, source) {
  22062. var _this = _super.call(this, name, source.getScene()) || this;
  22063. source.instances.push(_this);
  22064. _this._sourceMesh = source;
  22065. _this.position.copyFrom(source.position);
  22066. _this.rotation.copyFrom(source.rotation);
  22067. _this.scaling.copyFrom(source.scaling);
  22068. if (source.rotationQuaternion) {
  22069. _this.rotationQuaternion = source.rotationQuaternion.clone();
  22070. }
  22071. _this.infiniteDistance = source.infiniteDistance;
  22072. _this.setPivotMatrix(source.getPivotMatrix());
  22073. _this.refreshBoundingInfo();
  22074. _this._syncSubMeshes();
  22075. return _this;
  22076. }
  22077. /**
  22078. * Returns the string "InstancedMesh".
  22079. */
  22080. InstancedMesh.prototype.getClassName = function () {
  22081. return "InstancedMesh";
  22082. };
  22083. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  22084. // Methods
  22085. get: function () {
  22086. return this._sourceMesh.receiveShadows;
  22087. },
  22088. enumerable: true,
  22089. configurable: true
  22090. });
  22091. Object.defineProperty(InstancedMesh.prototype, "material", {
  22092. get: function () {
  22093. return this._sourceMesh.material;
  22094. },
  22095. enumerable: true,
  22096. configurable: true
  22097. });
  22098. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  22099. get: function () {
  22100. return this._sourceMesh.visibility;
  22101. },
  22102. enumerable: true,
  22103. configurable: true
  22104. });
  22105. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  22106. get: function () {
  22107. return this._sourceMesh.skeleton;
  22108. },
  22109. enumerable: true,
  22110. configurable: true
  22111. });
  22112. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  22113. get: function () {
  22114. return this._sourceMesh.renderingGroupId;
  22115. },
  22116. enumerable: true,
  22117. configurable: true
  22118. });
  22119. /**
  22120. * Returns the total number of vertices (integer).
  22121. */
  22122. InstancedMesh.prototype.getTotalVertices = function () {
  22123. return this._sourceMesh.getTotalVertices();
  22124. };
  22125. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  22126. get: function () {
  22127. return this._sourceMesh;
  22128. },
  22129. enumerable: true,
  22130. configurable: true
  22131. });
  22132. /**
  22133. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  22134. */
  22135. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  22136. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  22137. };
  22138. /**
  22139. * Boolean : True if the mesh owns the requested kind of data.
  22140. */
  22141. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  22142. return this._sourceMesh.isVerticesDataPresent(kind);
  22143. };
  22144. /**
  22145. * Returns an array of indices (IndicesArray).
  22146. */
  22147. InstancedMesh.prototype.getIndices = function () {
  22148. return this._sourceMesh.getIndices();
  22149. };
  22150. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  22151. get: function () {
  22152. return this._sourceMesh._positions;
  22153. },
  22154. enumerable: true,
  22155. configurable: true
  22156. });
  22157. /**
  22158. * Sets a new updated BoundingInfo to the mesh.
  22159. * Returns the mesh.
  22160. */
  22161. InstancedMesh.prototype.refreshBoundingInfo = function () {
  22162. var meshBB = this._sourceMesh.getBoundingInfo();
  22163. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  22164. this._updateBoundingInfo();
  22165. return this;
  22166. };
  22167. InstancedMesh.prototype._preActivate = function () {
  22168. if (this._currentLOD) {
  22169. this._currentLOD._preActivate();
  22170. }
  22171. return this;
  22172. };
  22173. InstancedMesh.prototype._activate = function (renderId) {
  22174. if (this._currentLOD) {
  22175. this._currentLOD._registerInstanceForRenderId(this, renderId);
  22176. }
  22177. return this;
  22178. };
  22179. /**
  22180. * Returns the current associated LOD AbstractMesh.
  22181. */
  22182. InstancedMesh.prototype.getLOD = function (camera) {
  22183. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  22184. if (this._currentLOD === this.sourceMesh) {
  22185. return this;
  22186. }
  22187. return this._currentLOD;
  22188. };
  22189. InstancedMesh.prototype._syncSubMeshes = function () {
  22190. this.releaseSubMeshes();
  22191. if (this._sourceMesh.subMeshes) {
  22192. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  22193. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  22194. }
  22195. }
  22196. return this;
  22197. };
  22198. InstancedMesh.prototype._generatePointsArray = function () {
  22199. return this._sourceMesh._generatePointsArray();
  22200. };
  22201. /**
  22202. * Creates a new InstancedMesh from the current mesh.
  22203. * - name (string) : the cloned mesh name
  22204. * - newParent (optional Node) : the optional Node to parent the clone to.
  22205. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  22206. *
  22207. * Returns the clone.
  22208. */
  22209. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  22210. var result = this._sourceMesh.createInstance(name);
  22211. // Deep copy
  22212. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  22213. // Bounding info
  22214. this.refreshBoundingInfo();
  22215. // Parent
  22216. if (newParent) {
  22217. result.parent = newParent;
  22218. }
  22219. if (!doNotCloneChildren) {
  22220. // Children
  22221. for (var index = 0; index < this.getScene().meshes.length; index++) {
  22222. var mesh = this.getScene().meshes[index];
  22223. if (mesh.parent === this) {
  22224. mesh.clone(mesh.name, result);
  22225. }
  22226. }
  22227. }
  22228. result.computeWorldMatrix(true);
  22229. return result;
  22230. };
  22231. /**
  22232. * Disposes the InstancedMesh.
  22233. * Returns nothing.
  22234. */
  22235. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  22236. // Remove from mesh
  22237. var index = this._sourceMesh.instances.indexOf(this);
  22238. this._sourceMesh.instances.splice(index, 1);
  22239. _super.prototype.dispose.call(this, doNotRecurse);
  22240. };
  22241. return InstancedMesh;
  22242. }(BABYLON.AbstractMesh));
  22243. BABYLON.InstancedMesh = InstancedMesh;
  22244. })(BABYLON || (BABYLON = {}));
  22245. //# sourceMappingURL=babylon.instancedMesh.js.map
  22246. var BABYLON;
  22247. (function (BABYLON) {
  22248. var _InstancesBatch = (function () {
  22249. function _InstancesBatch() {
  22250. this.mustReturn = false;
  22251. this.visibleInstances = new Array();
  22252. this.renderSelf = new Array();
  22253. }
  22254. return _InstancesBatch;
  22255. }());
  22256. BABYLON._InstancesBatch = _InstancesBatch;
  22257. var Mesh = (function (_super) {
  22258. __extends(Mesh, _super);
  22259. /**
  22260. * @constructor
  22261. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22262. * @param {Scene} scene The scene to add this mesh to.
  22263. * @param {Node} parent The parent of this mesh, if it has one
  22264. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22265. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22266. * When false, achieved by calling a clone(), also passing False.
  22267. * This will make creation of children, recursive.
  22268. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22269. */
  22270. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22271. if (parent === void 0) { parent = null; }
  22272. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22273. var _this = _super.call(this, name, scene) || this;
  22274. // Events
  22275. /**
  22276. * An event triggered before rendering the mesh
  22277. * @type {BABYLON.Observable}
  22278. */
  22279. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22280. /**
  22281. * An event triggered after rendering the mesh
  22282. * @type {BABYLON.Observable}
  22283. */
  22284. _this.onAfterRenderObservable = new BABYLON.Observable();
  22285. /**
  22286. * An event triggered before drawing the mesh
  22287. * @type {BABYLON.Observable}
  22288. */
  22289. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22290. // Members
  22291. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22292. _this.instances = new Array();
  22293. _this._LODLevels = new Array();
  22294. _this._visibleInstances = {};
  22295. _this._renderIdForInstances = new Array();
  22296. _this._batchCache = new _InstancesBatch();
  22297. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22298. _this._sideOrientation = Mesh._DEFAULTSIDE;
  22299. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22300. // Will be used to save a source mesh reference, If any
  22301. _this._source = null;
  22302. if (source) {
  22303. // Source mesh
  22304. _this._source = source;
  22305. // Geometry
  22306. if (source._geometry) {
  22307. source._geometry.applyToMesh(_this);
  22308. }
  22309. // Deep copy
  22310. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
  22311. // Parent
  22312. _this.parent = source.parent;
  22313. // Pivot
  22314. _this.setPivotMatrix(source.getPivotMatrix());
  22315. _this.id = name + "." + source.id;
  22316. // Material
  22317. _this.material = source.material;
  22318. var index;
  22319. if (!doNotCloneChildren) {
  22320. // Children
  22321. for (index = 0; index < scene.meshes.length; index++) {
  22322. var mesh = scene.meshes[index];
  22323. if (mesh.parent === source) {
  22324. // doNotCloneChildren is always going to be False
  22325. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22326. }
  22327. }
  22328. }
  22329. // Physics clone
  22330. var physicsEngine = _this.getScene().getPhysicsEngine();
  22331. if (clonePhysicsImpostor && physicsEngine) {
  22332. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22333. if (impostor) {
  22334. _this.physicsImpostor = impostor.clone(_this);
  22335. }
  22336. }
  22337. // Particles
  22338. for (index = 0; index < scene.particleSystems.length; index++) {
  22339. var system = scene.particleSystems[index];
  22340. if (system.emitter === source) {
  22341. system.clone(system.name, _this);
  22342. }
  22343. }
  22344. _this.computeWorldMatrix(true);
  22345. }
  22346. // Parent
  22347. if (parent !== null) {
  22348. _this.parent = parent;
  22349. }
  22350. return _this;
  22351. }
  22352. Object.defineProperty(Mesh, "FRONTSIDE", {
  22353. /**
  22354. * Mesh side orientation : usually the external or front surface
  22355. */
  22356. get: function () {
  22357. return Mesh._FRONTSIDE;
  22358. },
  22359. enumerable: true,
  22360. configurable: true
  22361. });
  22362. Object.defineProperty(Mesh, "BACKSIDE", {
  22363. /**
  22364. * Mesh side orientation : usually the internal or back surface
  22365. */
  22366. get: function () {
  22367. return Mesh._BACKSIDE;
  22368. },
  22369. enumerable: true,
  22370. configurable: true
  22371. });
  22372. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22373. /**
  22374. * Mesh side orientation : both internal and external or front and back surfaces
  22375. */
  22376. get: function () {
  22377. return Mesh._DOUBLESIDE;
  22378. },
  22379. enumerable: true,
  22380. configurable: true
  22381. });
  22382. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22383. /**
  22384. * Mesh side orientation : by default, `FRONTSIDE`
  22385. */
  22386. get: function () {
  22387. return Mesh._DEFAULTSIDE;
  22388. },
  22389. enumerable: true,
  22390. configurable: true
  22391. });
  22392. Object.defineProperty(Mesh, "NO_CAP", {
  22393. /**
  22394. * Mesh cap setting : no cap
  22395. */
  22396. get: function () {
  22397. return Mesh._NO_CAP;
  22398. },
  22399. enumerable: true,
  22400. configurable: true
  22401. });
  22402. Object.defineProperty(Mesh, "CAP_START", {
  22403. /**
  22404. * Mesh cap setting : one cap at the beginning of the mesh
  22405. */
  22406. get: function () {
  22407. return Mesh._CAP_START;
  22408. },
  22409. enumerable: true,
  22410. configurable: true
  22411. });
  22412. Object.defineProperty(Mesh, "CAP_END", {
  22413. /**
  22414. * Mesh cap setting : one cap at the end of the mesh
  22415. */
  22416. get: function () {
  22417. return Mesh._CAP_END;
  22418. },
  22419. enumerable: true,
  22420. configurable: true
  22421. });
  22422. Object.defineProperty(Mesh, "CAP_ALL", {
  22423. /**
  22424. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22425. */
  22426. get: function () {
  22427. return Mesh._CAP_ALL;
  22428. },
  22429. enumerable: true,
  22430. configurable: true
  22431. });
  22432. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22433. set: function (callback) {
  22434. if (this._onBeforeDrawObserver) {
  22435. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22436. }
  22437. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22438. },
  22439. enumerable: true,
  22440. configurable: true
  22441. });
  22442. Object.defineProperty(Mesh.prototype, "source", {
  22443. get: function () {
  22444. return this._source;
  22445. },
  22446. enumerable: true,
  22447. configurable: true
  22448. });
  22449. // Methods
  22450. /**
  22451. * Returns the string "Mesh".
  22452. */
  22453. Mesh.prototype.getClassName = function () {
  22454. return "Mesh";
  22455. };
  22456. /**
  22457. * Returns a string.
  22458. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22459. */
  22460. Mesh.prototype.toString = function (fullDetails) {
  22461. var ret = _super.prototype.toString.call(this, fullDetails);
  22462. ret += ", n vertices: " + this.getTotalVertices();
  22463. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22464. if (this.animations) {
  22465. for (var i = 0; i < this.animations.length; i++) {
  22466. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22467. }
  22468. }
  22469. if (fullDetails) {
  22470. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  22471. }
  22472. return ret;
  22473. };
  22474. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22475. /**
  22476. * True if the mesh has some Levels Of Details (LOD).
  22477. * Returns a boolean.
  22478. */
  22479. get: function () {
  22480. return this._LODLevels.length > 0;
  22481. },
  22482. enumerable: true,
  22483. configurable: true
  22484. });
  22485. Mesh.prototype._sortLODLevels = function () {
  22486. this._LODLevels.sort(function (a, b) {
  22487. if (a.distance < b.distance) {
  22488. return 1;
  22489. }
  22490. if (a.distance > b.distance) {
  22491. return -1;
  22492. }
  22493. return 0;
  22494. });
  22495. };
  22496. /**
  22497. * Add a mesh as LOD level triggered at the given distance.
  22498. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22499. * @param {number} distance The distance from the center of the object to show this level
  22500. * @param {Mesh} mesh The mesh to be added as LOD level
  22501. * @return {Mesh} This mesh (for chaining)
  22502. */
  22503. Mesh.prototype.addLODLevel = function (distance, mesh) {
  22504. if (mesh && mesh._masterMesh) {
  22505. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  22506. return this;
  22507. }
  22508. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  22509. this._LODLevels.push(level);
  22510. if (mesh) {
  22511. mesh._masterMesh = this;
  22512. }
  22513. this._sortLODLevels();
  22514. return this;
  22515. };
  22516. /**
  22517. * Returns the LOD level mesh at the passed distance or null if not found.
  22518. * It is related to the method `addLODLevel(distance, mesh)`.
  22519. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22520. * Returns an object Mesh or `null`.
  22521. */
  22522. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  22523. for (var index = 0; index < this._LODLevels.length; index++) {
  22524. var level = this._LODLevels[index];
  22525. if (level.distance === distance) {
  22526. return level.mesh;
  22527. }
  22528. }
  22529. return null;
  22530. };
  22531. /**
  22532. * Remove a mesh from the LOD array
  22533. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22534. * @param {Mesh} mesh The mesh to be removed.
  22535. * @return {Mesh} This mesh (for chaining)
  22536. */
  22537. Mesh.prototype.removeLODLevel = function (mesh) {
  22538. for (var index = 0; index < this._LODLevels.length; index++) {
  22539. if (this._LODLevels[index].mesh === mesh) {
  22540. this._LODLevels.splice(index, 1);
  22541. if (mesh) {
  22542. mesh._masterMesh = null;
  22543. }
  22544. }
  22545. }
  22546. this._sortLODLevels();
  22547. return this;
  22548. };
  22549. /**
  22550. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  22551. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22552. */
  22553. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  22554. if (!this._LODLevels || this._LODLevels.length === 0) {
  22555. return this;
  22556. }
  22557. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  22558. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  22559. if (this.onLODLevelSelection) {
  22560. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  22561. }
  22562. return this;
  22563. }
  22564. for (var index = 0; index < this._LODLevels.length; index++) {
  22565. var level = this._LODLevels[index];
  22566. if (level.distance < distanceToCamera) {
  22567. if (level.mesh) {
  22568. level.mesh._preActivate();
  22569. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  22570. }
  22571. if (this.onLODLevelSelection) {
  22572. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  22573. }
  22574. return level.mesh;
  22575. }
  22576. }
  22577. if (this.onLODLevelSelection) {
  22578. this.onLODLevelSelection(distanceToCamera, this, this);
  22579. }
  22580. return this;
  22581. };
  22582. Object.defineProperty(Mesh.prototype, "geometry", {
  22583. /**
  22584. * Returns the mesh internal Geometry object.
  22585. */
  22586. get: function () {
  22587. return this._geometry;
  22588. },
  22589. enumerable: true,
  22590. configurable: true
  22591. });
  22592. /**
  22593. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  22594. */
  22595. Mesh.prototype.getTotalVertices = function () {
  22596. if (!this._geometry) {
  22597. return 0;
  22598. }
  22599. return this._geometry.getTotalVertices();
  22600. };
  22601. /**
  22602. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  22603. * 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.
  22604. * Returns null if the mesh has no geometry or no vertex buffer.
  22605. * Possible `kind` values :
  22606. * - BABYLON.VertexBuffer.PositionKind
  22607. * - BABYLON.VertexBuffer.UVKind
  22608. * - BABYLON.VertexBuffer.UV2Kind
  22609. * - BABYLON.VertexBuffer.UV3Kind
  22610. * - BABYLON.VertexBuffer.UV4Kind
  22611. * - BABYLON.VertexBuffer.UV5Kind
  22612. * - BABYLON.VertexBuffer.UV6Kind
  22613. * - BABYLON.VertexBuffer.ColorKind
  22614. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22615. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22616. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22617. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22618. */
  22619. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  22620. if (!this._geometry) {
  22621. return null;
  22622. }
  22623. return this._geometry.getVerticesData(kind, copyWhenShared);
  22624. };
  22625. /**
  22626. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  22627. * Returns `undefined` if the mesh has no geometry.
  22628. * Possible `kind` values :
  22629. * - BABYLON.VertexBuffer.PositionKind
  22630. * - BABYLON.VertexBuffer.UVKind
  22631. * - BABYLON.VertexBuffer.UV2Kind
  22632. * - BABYLON.VertexBuffer.UV3Kind
  22633. * - BABYLON.VertexBuffer.UV4Kind
  22634. * - BABYLON.VertexBuffer.UV5Kind
  22635. * - BABYLON.VertexBuffer.UV6Kind
  22636. * - BABYLON.VertexBuffer.ColorKind
  22637. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22638. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22639. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22640. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22641. */
  22642. Mesh.prototype.getVertexBuffer = function (kind) {
  22643. if (!this._geometry) {
  22644. return undefined;
  22645. }
  22646. return this._geometry.getVertexBuffer(kind);
  22647. };
  22648. /**
  22649. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  22650. * Possible `kind` values :
  22651. * - BABYLON.VertexBuffer.PositionKind
  22652. * - BABYLON.VertexBuffer.UVKind
  22653. * - BABYLON.VertexBuffer.UV2Kind
  22654. * - BABYLON.VertexBuffer.UV3Kind
  22655. * - BABYLON.VertexBuffer.UV4Kind
  22656. * - BABYLON.VertexBuffer.UV5Kind
  22657. * - BABYLON.VertexBuffer.UV6Kind
  22658. * - BABYLON.VertexBuffer.ColorKind
  22659. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22660. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22661. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22662. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22663. */
  22664. Mesh.prototype.isVerticesDataPresent = function (kind) {
  22665. if (!this._geometry) {
  22666. if (this._delayInfo) {
  22667. return this._delayInfo.indexOf(kind) !== -1;
  22668. }
  22669. return false;
  22670. }
  22671. return this._geometry.isVerticesDataPresent(kind);
  22672. };
  22673. /**
  22674. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  22675. * Possible `kind` values :
  22676. * - BABYLON.VertexBuffer.PositionKind
  22677. * - BABYLON.VertexBuffer.UVKind
  22678. * - BABYLON.VertexBuffer.UV2Kind
  22679. * - BABYLON.VertexBuffer.UV3Kind
  22680. * - BABYLON.VertexBuffer.UV4Kind
  22681. * - BABYLON.VertexBuffer.UV5Kind
  22682. * - BABYLON.VertexBuffer.UV6Kind
  22683. * - BABYLON.VertexBuffer.ColorKind
  22684. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22685. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22686. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22687. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22688. */
  22689. Mesh.prototype.getVerticesDataKinds = function () {
  22690. if (!this._geometry) {
  22691. var result = [];
  22692. if (this._delayInfo) {
  22693. this._delayInfo.forEach(function (kind, index, array) {
  22694. result.push(kind);
  22695. });
  22696. }
  22697. return result;
  22698. }
  22699. return this._geometry.getVerticesDataKinds();
  22700. };
  22701. /**
  22702. * Returns a positive integer : the total number of indices in this mesh geometry.
  22703. * Returns zero if the mesh has no geometry.
  22704. */
  22705. Mesh.prototype.getTotalIndices = function () {
  22706. if (!this._geometry) {
  22707. return 0;
  22708. }
  22709. return this._geometry.getTotalIndices();
  22710. };
  22711. /**
  22712. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  22713. * 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.
  22714. * Returns an empty array if the mesh has no geometry.
  22715. */
  22716. Mesh.prototype.getIndices = function (copyWhenShared) {
  22717. if (!this._geometry) {
  22718. return [];
  22719. }
  22720. return this._geometry.getIndices(copyWhenShared);
  22721. };
  22722. Object.defineProperty(Mesh.prototype, "isBlocked", {
  22723. get: function () {
  22724. return this._masterMesh !== null && this._masterMesh !== undefined;
  22725. },
  22726. enumerable: true,
  22727. configurable: true
  22728. });
  22729. /**
  22730. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  22731. */
  22732. Mesh.prototype.isReady = function () {
  22733. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22734. return false;
  22735. }
  22736. return _super.prototype.isReady.call(this);
  22737. };
  22738. /**
  22739. * Boolean : true if the mesh has been disposed.
  22740. */
  22741. Mesh.prototype.isDisposed = function () {
  22742. return this._isDisposed;
  22743. };
  22744. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  22745. get: function () {
  22746. return this._sideOrientation;
  22747. },
  22748. /**
  22749. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  22750. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  22751. */
  22752. set: function (sideO) {
  22753. this._sideOrientation = sideO;
  22754. },
  22755. enumerable: true,
  22756. configurable: true
  22757. });
  22758. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  22759. /**
  22760. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  22761. * This property is pertinent only for updatable parametric shapes.
  22762. */
  22763. get: function () {
  22764. return this._areNormalsFrozen;
  22765. },
  22766. enumerable: true,
  22767. configurable: true
  22768. });
  22769. /**
  22770. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22771. * It has no effect at all on other shapes.
  22772. * It prevents the mesh normals from being recomputed on next `positions` array update.
  22773. * Returns the Mesh.
  22774. */
  22775. Mesh.prototype.freezeNormals = function () {
  22776. this._areNormalsFrozen = true;
  22777. return this;
  22778. };
  22779. /**
  22780. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22781. * It has no effect at all on other shapes.
  22782. * It reactivates the mesh normals computation if it was previously frozen.
  22783. * Returns the Mesh.
  22784. */
  22785. Mesh.prototype.unfreezeNormals = function () {
  22786. this._areNormalsFrozen = false;
  22787. return this;
  22788. };
  22789. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  22790. /**
  22791. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  22792. */
  22793. set: function (count) {
  22794. this._overridenInstanceCount = count;
  22795. },
  22796. enumerable: true,
  22797. configurable: true
  22798. });
  22799. // Methods
  22800. Mesh.prototype._preActivate = function () {
  22801. var sceneRenderId = this.getScene().getRenderId();
  22802. if (this._preActivateId === sceneRenderId) {
  22803. return this;
  22804. }
  22805. this._preActivateId = sceneRenderId;
  22806. this._visibleInstances = null;
  22807. return this;
  22808. };
  22809. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22810. if (this._visibleInstances) {
  22811. this._visibleInstances.intermediateDefaultRenderId = renderId;
  22812. }
  22813. return this;
  22814. };
  22815. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  22816. if (!this._visibleInstances) {
  22817. this._visibleInstances = {};
  22818. this._visibleInstances.defaultRenderId = renderId;
  22819. this._visibleInstances.selfDefaultRenderId = this._renderId;
  22820. }
  22821. if (!this._visibleInstances[renderId]) {
  22822. this._visibleInstances[renderId] = new Array();
  22823. }
  22824. this._visibleInstances[renderId].push(instance);
  22825. return this;
  22826. };
  22827. /**
  22828. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  22829. * This means the mesh underlying bounding box and sphere are recomputed.
  22830. * Returns the Mesh.
  22831. */
  22832. Mesh.prototype.refreshBoundingInfo = function () {
  22833. if (this._boundingInfo.isLocked) {
  22834. return;
  22835. }
  22836. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22837. if (data) {
  22838. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  22839. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22840. }
  22841. if (this.subMeshes) {
  22842. for (var index = 0; index < this.subMeshes.length; index++) {
  22843. this.subMeshes[index].refreshBoundingInfo();
  22844. }
  22845. }
  22846. this._updateBoundingInfo();
  22847. return this;
  22848. };
  22849. Mesh.prototype._createGlobalSubMesh = function () {
  22850. var totalVertices = this.getTotalVertices();
  22851. if (!totalVertices || !this.getIndices()) {
  22852. return null;
  22853. }
  22854. this.releaseSubMeshes();
  22855. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  22856. };
  22857. Mesh.prototype.subdivide = function (count) {
  22858. if (count < 1) {
  22859. return;
  22860. }
  22861. var totalIndices = this.getTotalIndices();
  22862. var subdivisionSize = (totalIndices / count) | 0;
  22863. var offset = 0;
  22864. // Ensure that subdivisionSize is a multiple of 3
  22865. while (subdivisionSize % 3 !== 0) {
  22866. subdivisionSize++;
  22867. }
  22868. this.releaseSubMeshes();
  22869. for (var index = 0; index < count; index++) {
  22870. if (offset >= totalIndices) {
  22871. break;
  22872. }
  22873. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  22874. offset += subdivisionSize;
  22875. }
  22876. this.synchronizeInstances();
  22877. };
  22878. /**
  22879. * Sets the vertex data of the mesh geometry for the requested `kind`.
  22880. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  22881. * The `data` are either a numeric array either a Float32Array.
  22882. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  22883. * 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).
  22884. * Note that a new underlying VertexBuffer object is created each call.
  22885. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  22886. *
  22887. * Possible `kind` values :
  22888. * - BABYLON.VertexBuffer.PositionKind
  22889. * - BABYLON.VertexBuffer.UVKind
  22890. * - BABYLON.VertexBuffer.UV2Kind
  22891. * - BABYLON.VertexBuffer.UV3Kind
  22892. * - BABYLON.VertexBuffer.UV4Kind
  22893. * - BABYLON.VertexBuffer.UV5Kind
  22894. * - BABYLON.VertexBuffer.UV6Kind
  22895. * - BABYLON.VertexBuffer.ColorKind
  22896. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22897. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22898. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22899. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22900. *
  22901. * Returns the Mesh.
  22902. */
  22903. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22904. if (!this._geometry) {
  22905. var vertexData = new BABYLON.VertexData();
  22906. vertexData.set(data, kind);
  22907. var scene = this.getScene();
  22908. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  22909. }
  22910. else {
  22911. this._geometry.setVerticesData(kind, data, updatable, stride);
  22912. }
  22913. return this;
  22914. };
  22915. /**
  22916. * Sets the mesh VertexBuffer.
  22917. * Returns the Mesh.
  22918. */
  22919. Mesh.prototype.setVerticesBuffer = function (buffer) {
  22920. if (!this._geometry) {
  22921. var scene = this.getScene();
  22922. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  22923. }
  22924. this._geometry.setVerticesBuffer(buffer);
  22925. return this;
  22926. };
  22927. /**
  22928. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  22929. * If the mesh has no geometry, it is simply returned as it is.
  22930. * The `data` are either a numeric array either a Float32Array.
  22931. * No new underlying VertexBuffer object is created.
  22932. * 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.
  22933. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  22934. *
  22935. * Possible `kind` values :
  22936. * - BABYLON.VertexBuffer.PositionKind
  22937. * - BABYLON.VertexBuffer.UVKind
  22938. * - BABYLON.VertexBuffer.UV2Kind
  22939. * - BABYLON.VertexBuffer.UV3Kind
  22940. * - BABYLON.VertexBuffer.UV4Kind
  22941. * - BABYLON.VertexBuffer.UV5Kind
  22942. * - BABYLON.VertexBuffer.UV6Kind
  22943. * - BABYLON.VertexBuffer.ColorKind
  22944. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22945. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22946. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22947. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22948. *
  22949. * Returns the Mesh.
  22950. */
  22951. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  22952. if (!this._geometry) {
  22953. return;
  22954. }
  22955. if (!makeItUnique) {
  22956. this._geometry.updateVerticesData(kind, data, updateExtends);
  22957. }
  22958. else {
  22959. this.makeGeometryUnique();
  22960. this.updateVerticesData(kind, data, updateExtends, false);
  22961. }
  22962. return this;
  22963. };
  22964. /**
  22965. * Deprecated since BabylonJS v2.3
  22966. */
  22967. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  22968. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  22969. if (!this._geometry) {
  22970. return;
  22971. }
  22972. if (!makeItUnique) {
  22973. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  22974. }
  22975. else {
  22976. this.makeGeometryUnique();
  22977. this.updateVerticesDataDirectly(kind, data, offset, false);
  22978. }
  22979. };
  22980. /**
  22981. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  22982. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  22983. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  22984. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  22985. * Returns the Mesh.
  22986. */
  22987. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  22988. if (computeNormals === void 0) { computeNormals = true; }
  22989. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22990. positionFunction(positions);
  22991. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22992. if (computeNormals) {
  22993. var indices = this.getIndices();
  22994. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22995. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22996. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22997. }
  22998. return this;
  22999. };
  23000. /**
  23001. * Creates a un-shared specific occurence of the geometry for the mesh.
  23002. * Returns the Mesh.
  23003. */
  23004. Mesh.prototype.makeGeometryUnique = function () {
  23005. if (!this._geometry) {
  23006. return;
  23007. }
  23008. var oldGeometry = this._geometry;
  23009. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23010. oldGeometry.releaseForMesh(this, true);
  23011. geometry.applyToMesh(this);
  23012. return this;
  23013. };
  23014. /**
  23015. * Sets the mesh indices.
  23016. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23017. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23018. * This method creates a new index buffer each call.
  23019. * Returns the Mesh.
  23020. */
  23021. Mesh.prototype.setIndices = function (indices, totalVertices) {
  23022. if (!this._geometry) {
  23023. var vertexData = new BABYLON.VertexData();
  23024. vertexData.indices = indices;
  23025. var scene = this.getScene();
  23026. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  23027. }
  23028. else {
  23029. this._geometry.setIndices(indices, totalVertices);
  23030. }
  23031. return this;
  23032. };
  23033. /**
  23034. * Invert the geometry to move from a right handed system to a left handed one.
  23035. * Returns the Mesh.
  23036. */
  23037. Mesh.prototype.toLeftHanded = function () {
  23038. if (!this._geometry) {
  23039. return;
  23040. }
  23041. this._geometry.toLeftHanded();
  23042. return this;
  23043. };
  23044. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23045. var engine = this.getScene().getEngine();
  23046. // Wireframe
  23047. var indexToBind;
  23048. if (this._unIndexed) {
  23049. indexToBind = null;
  23050. }
  23051. else {
  23052. switch (fillMode) {
  23053. case BABYLON.Material.PointFillMode:
  23054. indexToBind = null;
  23055. break;
  23056. case BABYLON.Material.WireFrameFillMode:
  23057. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23058. break;
  23059. default:
  23060. case BABYLON.Material.TriangleFillMode:
  23061. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23062. break;
  23063. }
  23064. }
  23065. // VBOs
  23066. this._geometry._bind(effect, indexToBind);
  23067. return this;
  23068. };
  23069. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23070. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23071. return this;
  23072. }
  23073. this.onBeforeDrawObservable.notifyObservers(this);
  23074. var engine = this.getScene().getEngine();
  23075. // Draw order
  23076. switch (fillMode) {
  23077. case BABYLON.Material.PointFillMode:
  23078. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23079. break;
  23080. case BABYLON.Material.WireFrameFillMode:
  23081. if (this._unIndexed) {
  23082. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23083. }
  23084. else {
  23085. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  23086. }
  23087. break;
  23088. default:
  23089. if (this._unIndexed) {
  23090. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23091. }
  23092. else {
  23093. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23094. }
  23095. }
  23096. return this;
  23097. };
  23098. /**
  23099. * Registers for this mesh a javascript function called just before the rendering process.
  23100. * This function is passed the current mesh.
  23101. * Return the Mesh.
  23102. */
  23103. Mesh.prototype.registerBeforeRender = function (func) {
  23104. this.onBeforeRenderObservable.add(func);
  23105. return this;
  23106. };
  23107. /**
  23108. * Disposes a previously registered javascript function called before the rendering.
  23109. * This function is passed the current mesh.
  23110. * Returns the Mesh.
  23111. */
  23112. Mesh.prototype.unregisterBeforeRender = function (func) {
  23113. this.onBeforeRenderObservable.removeCallback(func);
  23114. return this;
  23115. };
  23116. /**
  23117. * Registers for this mesh a javascript function called just after the rendering is complete.
  23118. * This function is passed the current mesh.
  23119. * Returns the Mesh.
  23120. */
  23121. Mesh.prototype.registerAfterRender = function (func) {
  23122. this.onAfterRenderObservable.add(func);
  23123. return this;
  23124. };
  23125. /**
  23126. * Disposes a previously registered javascript function called after the rendering.
  23127. * This function is passed the current mesh.
  23128. * Return the Mesh.
  23129. */
  23130. Mesh.prototype.unregisterAfterRender = function (func) {
  23131. this.onAfterRenderObservable.removeCallback(func);
  23132. return this;
  23133. };
  23134. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23135. var scene = this.getScene();
  23136. this._batchCache.mustReturn = false;
  23137. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23138. this._batchCache.visibleInstances[subMeshId] = null;
  23139. if (this._visibleInstances) {
  23140. var currentRenderId = scene.getRenderId();
  23141. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23142. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23143. var selfRenderId = this._renderId;
  23144. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23145. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23146. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23147. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23148. }
  23149. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  23150. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23151. this._batchCache.mustReturn = true;
  23152. return this._batchCache;
  23153. }
  23154. if (currentRenderId !== selfRenderId) {
  23155. this._batchCache.renderSelf[subMeshId] = false;
  23156. }
  23157. }
  23158. this._renderIdForInstances[subMeshId] = currentRenderId;
  23159. }
  23160. return this._batchCache;
  23161. };
  23162. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23163. var visibleInstances = batch.visibleInstances[subMesh._id];
  23164. var matricesCount = visibleInstances.length + 1;
  23165. var bufferSize = matricesCount * 16 * 4;
  23166. var currentInstancesBufferSize = this._instancesBufferSize;
  23167. var instancesBuffer = this._instancesBuffer;
  23168. while (this._instancesBufferSize < bufferSize) {
  23169. this._instancesBufferSize *= 2;
  23170. }
  23171. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23172. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23173. }
  23174. var offset = 0;
  23175. var instancesCount = 0;
  23176. var world = this.getWorldMatrix();
  23177. if (batch.renderSelf[subMesh._id]) {
  23178. world.copyToArray(this._instancesData, offset);
  23179. offset += 16;
  23180. instancesCount++;
  23181. }
  23182. if (visibleInstances) {
  23183. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23184. var instance = visibleInstances[instanceIndex];
  23185. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23186. offset += 16;
  23187. instancesCount++;
  23188. }
  23189. }
  23190. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23191. if (instancesBuffer) {
  23192. instancesBuffer.dispose();
  23193. }
  23194. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23195. this._instancesBuffer = instancesBuffer;
  23196. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23197. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23198. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23199. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23200. }
  23201. else {
  23202. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23203. }
  23204. this.geometry._bind(effect);
  23205. this._draw(subMesh, fillMode, instancesCount);
  23206. engine.unbindInstanceAttributes();
  23207. return this;
  23208. };
  23209. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23210. var scene = this.getScene();
  23211. var engine = scene.getEngine();
  23212. if (hardwareInstancedRendering) {
  23213. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23214. }
  23215. else {
  23216. if (batch.renderSelf[subMesh._id]) {
  23217. // Draw
  23218. if (onBeforeDraw) {
  23219. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23220. }
  23221. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23222. }
  23223. if (batch.visibleInstances[subMesh._id]) {
  23224. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23225. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23226. // World
  23227. var world = instance.getWorldMatrix();
  23228. if (onBeforeDraw) {
  23229. onBeforeDraw(true, world, effectiveMaterial);
  23230. }
  23231. // Draw
  23232. this._draw(subMesh, fillMode);
  23233. }
  23234. }
  23235. }
  23236. return this;
  23237. };
  23238. /**
  23239. * Triggers the draw call for the mesh.
  23240. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23241. * Returns the Mesh.
  23242. */
  23243. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23244. var scene = this.getScene();
  23245. // Managing instances
  23246. var batch = this._getInstancesRenderList(subMesh._id);
  23247. if (batch.mustReturn) {
  23248. return this;
  23249. }
  23250. // Checking geometry state
  23251. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23252. return this;
  23253. }
  23254. var callbackIndex;
  23255. this.onBeforeRenderObservable.notifyObservers(this);
  23256. var engine = scene.getEngine();
  23257. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23258. // Material
  23259. var effectiveMaterial = subMesh.getMaterial();
  23260. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23261. return this;
  23262. }
  23263. // Outline - step 1
  23264. var savedDepthWrite = engine.getDepthWrite();
  23265. if (this.renderOutline) {
  23266. engine.setDepthWrite(false);
  23267. scene.getOutlineRenderer().render(subMesh, batch);
  23268. engine.setDepthWrite(savedDepthWrite);
  23269. }
  23270. effectiveMaterial._preBind();
  23271. var effect = effectiveMaterial.getEffect();
  23272. // Bind
  23273. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  23274. this._bind(subMesh, effect, fillMode);
  23275. var world = this.getWorldMatrix();
  23276. effectiveMaterial.bind(world, this);
  23277. // Alpha mode
  23278. if (enableAlphaMode) {
  23279. engine.setAlphaMode(effectiveMaterial.alphaMode);
  23280. }
  23281. // Draw
  23282. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  23283. // Unbind
  23284. effectiveMaterial.unbind();
  23285. // Outline - step 2
  23286. if (this.renderOutline && savedDepthWrite) {
  23287. engine.setDepthWrite(true);
  23288. engine.setColorWrite(false);
  23289. scene.getOutlineRenderer().render(subMesh, batch);
  23290. engine.setColorWrite(true);
  23291. }
  23292. // Overlay
  23293. if (this.renderOverlay) {
  23294. var currentMode = engine.getAlphaMode();
  23295. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23296. scene.getOutlineRenderer().render(subMesh, batch, true);
  23297. engine.setAlphaMode(currentMode);
  23298. }
  23299. this.onAfterRenderObservable.notifyObservers(this);
  23300. return this;
  23301. };
  23302. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23303. if (isInstance) {
  23304. effectiveMaterial.bindOnlyWorldMatrix(world);
  23305. }
  23306. return this;
  23307. };
  23308. /**
  23309. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23310. */
  23311. Mesh.prototype.getEmittedParticleSystems = function () {
  23312. var results = new Array();
  23313. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23314. var particleSystem = this.getScene().particleSystems[index];
  23315. if (particleSystem.emitter === this) {
  23316. results.push(particleSystem);
  23317. }
  23318. }
  23319. return results;
  23320. };
  23321. /**
  23322. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23323. */
  23324. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23325. var results = new Array();
  23326. var descendants = this.getDescendants();
  23327. descendants.push(this);
  23328. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23329. var particleSystem = this.getScene().particleSystems[index];
  23330. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  23331. results.push(particleSystem);
  23332. }
  23333. }
  23334. return results;
  23335. };
  23336. Mesh.prototype._checkDelayState = function () {
  23337. var scene = this.getScene();
  23338. if (this._geometry) {
  23339. this._geometry.load(scene);
  23340. }
  23341. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23342. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23343. this._queueLoad(this, scene);
  23344. }
  23345. return this;
  23346. };
  23347. Mesh.prototype._queueLoad = function (mesh, scene) {
  23348. var _this = this;
  23349. scene._addPendingData(mesh);
  23350. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23351. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23352. if (data instanceof ArrayBuffer) {
  23353. _this._delayLoadingFunction(data, _this);
  23354. }
  23355. else {
  23356. _this._delayLoadingFunction(JSON.parse(data), _this);
  23357. }
  23358. _this.instances.forEach(function (instance) {
  23359. instance._syncSubMeshes();
  23360. });
  23361. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23362. scene._removePendingData(_this);
  23363. }, function () { }, scene.database, getBinaryData);
  23364. return this;
  23365. };
  23366. /**
  23367. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23368. */
  23369. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23370. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23371. return false;
  23372. }
  23373. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23374. return false;
  23375. }
  23376. this._checkDelayState();
  23377. return true;
  23378. };
  23379. /**
  23380. * Sets the mesh material by the material or multiMaterial `id` property.
  23381. * The material `id` is a string identifying the material or the multiMaterial.
  23382. * This method returns the Mesh.
  23383. */
  23384. Mesh.prototype.setMaterialByID = function (id) {
  23385. var materials = this.getScene().materials;
  23386. var index;
  23387. for (index = 0; index < materials.length; index++) {
  23388. if (materials[index].id === id) {
  23389. this.material = materials[index];
  23390. return this;
  23391. }
  23392. }
  23393. // Multi
  23394. var multiMaterials = this.getScene().multiMaterials;
  23395. for (index = 0; index < multiMaterials.length; index++) {
  23396. if (multiMaterials[index].id === id) {
  23397. this.material = multiMaterials[index];
  23398. return this;
  23399. }
  23400. }
  23401. return this;
  23402. };
  23403. /**
  23404. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23405. */
  23406. Mesh.prototype.getAnimatables = function () {
  23407. var results = [];
  23408. if (this.material) {
  23409. results.push(this.material);
  23410. }
  23411. if (this.skeleton) {
  23412. results.push(this.skeleton);
  23413. }
  23414. return results;
  23415. };
  23416. /**
  23417. * Modifies the mesh geometry according to the passed transformation matrix.
  23418. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23419. * The mesh normals are modified accordingly the same transformation.
  23420. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23421. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23422. * Returns the Mesh.
  23423. */
  23424. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23425. // Position
  23426. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23427. return this;
  23428. }
  23429. var submeshes = this.subMeshes.splice(0);
  23430. this._resetPointsArrayCache();
  23431. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23432. var temp = [];
  23433. var index;
  23434. for (index = 0; index < data.length; index += 3) {
  23435. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23436. }
  23437. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23438. // Normals
  23439. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23440. return this;
  23441. }
  23442. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23443. temp = [];
  23444. for (index = 0; index < data.length; index += 3) {
  23445. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23446. }
  23447. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23448. // flip faces?
  23449. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23450. this.flipFaces();
  23451. }
  23452. // Restore submeshes
  23453. this.releaseSubMeshes();
  23454. this.subMeshes = submeshes;
  23455. return this;
  23456. };
  23457. /**
  23458. * Modifies the mesh geometry according to its own current World Matrix.
  23459. * The mesh World Matrix is then reset.
  23460. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23461. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23462. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23463. * Returns the Mesh.
  23464. */
  23465. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23466. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23467. this.scaling.copyFromFloats(1, 1, 1);
  23468. this.position.copyFromFloats(0, 0, 0);
  23469. this.rotation.copyFromFloats(0, 0, 0);
  23470. //only if quaternion is already set
  23471. if (this.rotationQuaternion) {
  23472. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23473. }
  23474. this._worldMatrix = BABYLON.Matrix.Identity();
  23475. return this;
  23476. };
  23477. // Cache
  23478. Mesh.prototype._resetPointsArrayCache = function () {
  23479. this._positions = null;
  23480. return this;
  23481. };
  23482. Mesh.prototype._generatePointsArray = function () {
  23483. if (this._positions)
  23484. return true;
  23485. this._positions = [];
  23486. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23487. if (!data) {
  23488. return false;
  23489. }
  23490. for (var index = 0; index < data.length; index += 3) {
  23491. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  23492. }
  23493. return true;
  23494. };
  23495. /**
  23496. * Returns a new Mesh object generated from the current mesh properties.
  23497. * This method must not get confused with createInstance().
  23498. * The parameter `name` is a string, the name given to the new mesh.
  23499. * The optional parameter `newParent` can be any Node object (default `null`).
  23500. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23501. * 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.
  23502. */
  23503. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23504. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23505. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23506. };
  23507. /**
  23508. * Disposes the mesh.
  23509. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23510. */
  23511. Mesh.prototype.dispose = function (doNotRecurse) {
  23512. var _this = this;
  23513. if (this._geometry) {
  23514. this._geometry.releaseForMesh(this, true);
  23515. }
  23516. // Sources
  23517. var meshes = this.getScene().meshes;
  23518. meshes.forEach(function (mesh) {
  23519. if (mesh._source && mesh._source === _this) {
  23520. mesh._source = null;
  23521. }
  23522. });
  23523. this._source = null;
  23524. // Instances
  23525. if (this._instancesBuffer) {
  23526. this._instancesBuffer.dispose();
  23527. this._instancesBuffer = null;
  23528. }
  23529. while (this.instances.length) {
  23530. this.instances[0].dispose();
  23531. }
  23532. // Highlight layers.
  23533. var highlightLayers = this.getScene().highlightLayers;
  23534. for (var i = 0; i < highlightLayers.length; i++) {
  23535. var highlightLayer = highlightLayers[i];
  23536. if (highlightLayer) {
  23537. highlightLayer.removeMesh(this);
  23538. highlightLayer.removeExcludedMesh(this);
  23539. }
  23540. }
  23541. _super.prototype.dispose.call(this, doNotRecurse);
  23542. };
  23543. /**
  23544. * Modifies the mesh geometry according to a displacement map.
  23545. * 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.
  23546. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23547. * This method returns nothing.
  23548. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  23549. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23550. * 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.
  23551. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23552. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23553. *
  23554. * Returns the Mesh.
  23555. */
  23556. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  23557. var _this = this;
  23558. var scene = this.getScene();
  23559. var onload = function (img) {
  23560. // Getting height map data
  23561. var canvas = document.createElement("canvas");
  23562. var context = canvas.getContext("2d");
  23563. var heightMapWidth = img.width;
  23564. var heightMapHeight = img.height;
  23565. canvas.width = heightMapWidth;
  23566. canvas.height = heightMapHeight;
  23567. context.drawImage(img, 0, 0);
  23568. // Create VertexData from map data
  23569. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23570. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  23571. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  23572. //execute success callback, if set
  23573. if (onSuccess) {
  23574. onSuccess(_this);
  23575. }
  23576. };
  23577. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23578. return this;
  23579. };
  23580. /**
  23581. * Modifies the mesh geometry according to a displacementMap buffer.
  23582. * 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.
  23583. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23584. * This method returns nothing.
  23585. * 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.
  23586. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  23587. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23588. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23589. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23590. *
  23591. * Returns the Mesh.
  23592. */
  23593. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  23594. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  23595. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  23596. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23597. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  23598. return this;
  23599. }
  23600. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23601. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23602. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23603. var position = BABYLON.Vector3.Zero();
  23604. var normal = BABYLON.Vector3.Zero();
  23605. var uv = BABYLON.Vector2.Zero();
  23606. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  23607. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  23608. for (var index = 0; index < positions.length; index += 3) {
  23609. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  23610. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  23611. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  23612. // Compute height
  23613. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  23614. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  23615. var pos = (u + v * heightMapWidth) * 4;
  23616. var r = buffer[pos] / 255.0;
  23617. var g = buffer[pos + 1] / 255.0;
  23618. var b = buffer[pos + 2] / 255.0;
  23619. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23620. normal.normalize();
  23621. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  23622. position = position.add(normal);
  23623. position.toArray(positions, index);
  23624. }
  23625. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  23626. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  23627. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23628. return this;
  23629. };
  23630. /**
  23631. * Modify the mesh to get a flat shading rendering.
  23632. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  23633. * This method returns the Mesh.
  23634. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  23635. */
  23636. Mesh.prototype.convertToFlatShadedMesh = function () {
  23637. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  23638. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23639. var kinds = this.getVerticesDataKinds();
  23640. var vbs = [];
  23641. var data = [];
  23642. var newdata = [];
  23643. var updatableNormals = false;
  23644. var kindIndex;
  23645. var kind;
  23646. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23647. kind = kinds[kindIndex];
  23648. var vertexBuffer = this.getVertexBuffer(kind);
  23649. if (kind === BABYLON.VertexBuffer.NormalKind) {
  23650. updatableNormals = vertexBuffer.isUpdatable();
  23651. kinds.splice(kindIndex, 1);
  23652. kindIndex--;
  23653. continue;
  23654. }
  23655. vbs[kind] = vertexBuffer;
  23656. data[kind] = vbs[kind].getData();
  23657. newdata[kind] = [];
  23658. }
  23659. // Save previous submeshes
  23660. var previousSubmeshes = this.subMeshes.slice(0);
  23661. var indices = this.getIndices();
  23662. var totalIndices = this.getTotalIndices();
  23663. // Generating unique vertices per face
  23664. var index;
  23665. for (index = 0; index < totalIndices; index++) {
  23666. var vertexIndex = indices[index];
  23667. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23668. kind = kinds[kindIndex];
  23669. var stride = vbs[kind].getStrideSize();
  23670. for (var offset = 0; offset < stride; offset++) {
  23671. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23672. }
  23673. }
  23674. }
  23675. // Updating faces & normal
  23676. var normals = [];
  23677. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  23678. for (index = 0; index < totalIndices; index += 3) {
  23679. indices[index] = index;
  23680. indices[index + 1] = index + 1;
  23681. indices[index + 2] = index + 2;
  23682. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  23683. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  23684. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  23685. var p1p2 = p1.subtract(p2);
  23686. var p3p2 = p3.subtract(p2);
  23687. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23688. // Store same normals for every vertex
  23689. for (var localIndex = 0; localIndex < 3; localIndex++) {
  23690. normals.push(normal.x);
  23691. normals.push(normal.y);
  23692. normals.push(normal.z);
  23693. }
  23694. }
  23695. this.setIndices(indices);
  23696. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  23697. // Updating vertex buffers
  23698. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23699. kind = kinds[kindIndex];
  23700. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23701. }
  23702. // Updating submeshes
  23703. this.releaseSubMeshes();
  23704. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23705. var previousOne = previousSubmeshes[submeshIndex];
  23706. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23707. }
  23708. this.synchronizeInstances();
  23709. return this;
  23710. };
  23711. /**
  23712. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  23713. * In other words, more vertices, no more indices and a single bigger VBO.
  23714. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  23715. * Returns the Mesh.
  23716. */
  23717. Mesh.prototype.convertToUnIndexedMesh = function () {
  23718. /// <summary>Remove indices by unfolding faces into buffers</summary>
  23719. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23720. var kinds = this.getVerticesDataKinds();
  23721. var vbs = [];
  23722. var data = [];
  23723. var newdata = [];
  23724. var updatableNormals = false;
  23725. var kindIndex;
  23726. var kind;
  23727. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23728. kind = kinds[kindIndex];
  23729. var vertexBuffer = this.getVertexBuffer(kind);
  23730. vbs[kind] = vertexBuffer;
  23731. data[kind] = vbs[kind].getData();
  23732. newdata[kind] = [];
  23733. }
  23734. // Save previous submeshes
  23735. var previousSubmeshes = this.subMeshes.slice(0);
  23736. var indices = this.getIndices();
  23737. var totalIndices = this.getTotalIndices();
  23738. // Generating unique vertices per face
  23739. var index;
  23740. for (index = 0; index < totalIndices; index++) {
  23741. var vertexIndex = indices[index];
  23742. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23743. kind = kinds[kindIndex];
  23744. var stride = vbs[kind].getStrideSize();
  23745. for (var offset = 0; offset < stride; offset++) {
  23746. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23747. }
  23748. }
  23749. }
  23750. // Updating indices
  23751. for (index = 0; index < totalIndices; index += 3) {
  23752. indices[index] = index;
  23753. indices[index + 1] = index + 1;
  23754. indices[index + 2] = index + 2;
  23755. }
  23756. this.setIndices(indices);
  23757. // Updating vertex buffers
  23758. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23759. kind = kinds[kindIndex];
  23760. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23761. }
  23762. // Updating submeshes
  23763. this.releaseSubMeshes();
  23764. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23765. var previousOne = previousSubmeshes[submeshIndex];
  23766. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23767. }
  23768. this._unIndexed = true;
  23769. this.synchronizeInstances();
  23770. return this;
  23771. };
  23772. /**
  23773. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  23774. * This method returns the Mesh.
  23775. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  23776. */
  23777. Mesh.prototype.flipFaces = function (flipNormals) {
  23778. if (flipNormals === void 0) { flipNormals = false; }
  23779. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  23780. var i;
  23781. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23782. for (i = 0; i < vertex_data.normals.length; i++) {
  23783. vertex_data.normals[i] *= -1;
  23784. }
  23785. }
  23786. var temp;
  23787. for (i = 0; i < vertex_data.indices.length; i += 3) {
  23788. // reassign indices
  23789. temp = vertex_data.indices[i + 1];
  23790. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  23791. vertex_data.indices[i + 2] = temp;
  23792. }
  23793. vertex_data.applyToMesh(this);
  23794. return this;
  23795. };
  23796. // Instances
  23797. /**
  23798. * Creates a new InstancedMesh object from the mesh model.
  23799. * An instance shares the same properties and the same material than its model.
  23800. * Only these properties of each instance can then be set individually :
  23801. * - position
  23802. * - rotation
  23803. * - rotationQuaternion
  23804. * - setPivotMatrix
  23805. * - scaling
  23806. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  23807. * Warning : this method is not supported for Line mesh and LineSystem
  23808. */
  23809. Mesh.prototype.createInstance = function (name) {
  23810. return new BABYLON.InstancedMesh(name, this);
  23811. };
  23812. /**
  23813. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  23814. * After this call, all the mesh instances have the same submeshes than the current mesh.
  23815. * This method returns the Mesh.
  23816. */
  23817. Mesh.prototype.synchronizeInstances = function () {
  23818. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  23819. var instance = this.instances[instanceIndex];
  23820. instance._syncSubMeshes();
  23821. }
  23822. return this;
  23823. };
  23824. /**
  23825. * Simplify the mesh according to the given array of settings.
  23826. * Function will return immediately and will simplify async. It returns the Mesh.
  23827. * @param settings a collection of simplification settings.
  23828. * @param parallelProcessing should all levels calculate parallel or one after the other.
  23829. * @param type the type of simplification to run.
  23830. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  23831. */
  23832. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  23833. if (parallelProcessing === void 0) { parallelProcessing = true; }
  23834. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  23835. this.getScene().simplificationQueue.addTask({
  23836. settings: settings,
  23837. parallelProcessing: parallelProcessing,
  23838. mesh: this,
  23839. simplificationType: simplificationType,
  23840. successCallback: successCallback
  23841. });
  23842. return this;
  23843. };
  23844. /**
  23845. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  23846. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  23847. * This should be used together with the simplification to avoid disappearing triangles.
  23848. * Returns the Mesh.
  23849. * @param successCallback an optional success callback to be called after the optimization finished.
  23850. */
  23851. Mesh.prototype.optimizeIndices = function (successCallback) {
  23852. var _this = this;
  23853. var indices = this.getIndices();
  23854. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23855. var vectorPositions = [];
  23856. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  23857. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  23858. }
  23859. var dupes = [];
  23860. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  23861. var realPos = vectorPositions.length - 1 - iteration;
  23862. var testedPosition = vectorPositions[realPos];
  23863. for (var j = 0; j < realPos; ++j) {
  23864. var againstPosition = vectorPositions[j];
  23865. if (testedPosition.equals(againstPosition)) {
  23866. dupes[realPos] = j;
  23867. break;
  23868. }
  23869. }
  23870. }, function () {
  23871. for (var i = 0; i < indices.length; ++i) {
  23872. indices[i] = dupes[indices[i]] || indices[i];
  23873. }
  23874. //indices are now reordered
  23875. var originalSubMeshes = _this.subMeshes.slice(0);
  23876. _this.setIndices(indices);
  23877. _this.subMeshes = originalSubMeshes;
  23878. if (successCallback) {
  23879. successCallback(_this);
  23880. }
  23881. });
  23882. return this;
  23883. };
  23884. // Statics
  23885. /**
  23886. * Returns a new Mesh object what is a deep copy of the passed mesh.
  23887. * The parameter `parsedMesh` is the mesh to be copied.
  23888. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  23889. */
  23890. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  23891. var mesh = new Mesh(parsedMesh.name, scene);
  23892. mesh.id = parsedMesh.id;
  23893. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  23894. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  23895. if (parsedMesh.metadata !== undefined) {
  23896. mesh.metadata = parsedMesh.metadata;
  23897. }
  23898. if (parsedMesh.rotationQuaternion) {
  23899. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  23900. }
  23901. else if (parsedMesh.rotation) {
  23902. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  23903. }
  23904. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  23905. if (parsedMesh.localMatrix) {
  23906. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  23907. }
  23908. else if (parsedMesh.pivotMatrix) {
  23909. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  23910. }
  23911. mesh.setEnabled(parsedMesh.isEnabled);
  23912. mesh.isVisible = parsedMesh.isVisible;
  23913. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  23914. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  23915. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  23916. if (parsedMesh.applyFog !== undefined) {
  23917. mesh.applyFog = parsedMesh.applyFog;
  23918. }
  23919. if (parsedMesh.pickable !== undefined) {
  23920. mesh.isPickable = parsedMesh.pickable;
  23921. }
  23922. if (parsedMesh.alphaIndex !== undefined) {
  23923. mesh.alphaIndex = parsedMesh.alphaIndex;
  23924. }
  23925. mesh.receiveShadows = parsedMesh.receiveShadows;
  23926. mesh.billboardMode = parsedMesh.billboardMode;
  23927. if (parsedMesh.visibility !== undefined) {
  23928. mesh.visibility = parsedMesh.visibility;
  23929. }
  23930. mesh.checkCollisions = parsedMesh.checkCollisions;
  23931. if (parsedMesh.isBlocker !== undefined) {
  23932. mesh.isBlocker = parsedMesh.isBlocker;
  23933. }
  23934. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  23935. // freezeWorldMatrix
  23936. if (parsedMesh.freezeWorldMatrix) {
  23937. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  23938. }
  23939. // Parent
  23940. if (parsedMesh.parentId) {
  23941. mesh._waitingParentId = parsedMesh.parentId;
  23942. }
  23943. // Actions
  23944. if (parsedMesh.actions !== undefined) {
  23945. mesh._waitingActions = parsedMesh.actions;
  23946. }
  23947. // Overlay
  23948. if (parsedMesh.overlayAlpha !== undefined) {
  23949. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  23950. }
  23951. if (parsedMesh.overlayColor !== undefined) {
  23952. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  23953. }
  23954. if (parsedMesh.renderOverlay !== undefined) {
  23955. mesh.renderOverlay = parsedMesh.renderOverlay;
  23956. }
  23957. // Geometry
  23958. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  23959. if (parsedMesh.delayLoadingFile) {
  23960. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23961. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  23962. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  23963. if (parsedMesh._binaryInfo) {
  23964. mesh._binaryInfo = parsedMesh._binaryInfo;
  23965. }
  23966. mesh._delayInfo = [];
  23967. if (parsedMesh.hasUVs) {
  23968. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  23969. }
  23970. if (parsedMesh.hasUVs2) {
  23971. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  23972. }
  23973. if (parsedMesh.hasUVs3) {
  23974. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  23975. }
  23976. if (parsedMesh.hasUVs4) {
  23977. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  23978. }
  23979. if (parsedMesh.hasUVs5) {
  23980. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  23981. }
  23982. if (parsedMesh.hasUVs6) {
  23983. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  23984. }
  23985. if (parsedMesh.hasColors) {
  23986. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  23987. }
  23988. if (parsedMesh.hasMatricesIndices) {
  23989. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23990. }
  23991. if (parsedMesh.hasMatricesWeights) {
  23992. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23993. }
  23994. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  23995. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  23996. mesh._checkDelayState();
  23997. }
  23998. }
  23999. else {
  24000. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24001. }
  24002. // Material
  24003. if (parsedMesh.materialId) {
  24004. mesh.setMaterialByID(parsedMesh.materialId);
  24005. }
  24006. else {
  24007. mesh.material = null;
  24008. }
  24009. // Skeleton
  24010. if (parsedMesh.skeletonId > -1) {
  24011. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24012. if (parsedMesh.numBoneInfluencers) {
  24013. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24014. }
  24015. }
  24016. // Animations
  24017. if (parsedMesh.animations) {
  24018. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24019. var parsedAnimation = parsedMesh.animations[animationIndex];
  24020. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24021. }
  24022. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24023. }
  24024. if (parsedMesh.autoAnimate) {
  24025. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24026. }
  24027. // Layer Mask
  24028. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24029. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24030. }
  24031. else {
  24032. mesh.layerMask = 0x0FFFFFFF;
  24033. }
  24034. //(Deprecated) physics
  24035. if (parsedMesh.physicsImpostor) {
  24036. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24037. mass: parsedMesh.physicsMass,
  24038. friction: parsedMesh.physicsFriction,
  24039. restitution: parsedMesh.physicsRestitution
  24040. }, scene);
  24041. }
  24042. // Instances
  24043. if (parsedMesh.instances) {
  24044. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24045. var parsedInstance = parsedMesh.instances[index];
  24046. var instance = mesh.createInstance(parsedInstance.name);
  24047. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24048. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24049. if (parsedInstance.parentId) {
  24050. instance._waitingParentId = parsedInstance.parentId;
  24051. }
  24052. if (parsedInstance.rotationQuaternion) {
  24053. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24054. }
  24055. else if (parsedInstance.rotation) {
  24056. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24057. }
  24058. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24059. instance.checkCollisions = mesh.checkCollisions;
  24060. if (parsedMesh.animations) {
  24061. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24062. parsedAnimation = parsedMesh.animations[animationIndex];
  24063. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24064. }
  24065. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24066. }
  24067. }
  24068. }
  24069. return mesh;
  24070. };
  24071. /**
  24072. * Creates a ribbon mesh.
  24073. * Please consider using the same method from the MeshBuilder class instead.
  24074. * 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.
  24075. *
  24076. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24077. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24078. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24079. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24080. * 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.
  24081. * 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.
  24082. * 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
  24083. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24084. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24085. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24086. */
  24087. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24088. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24089. pathArray: pathArray,
  24090. closeArray: closeArray,
  24091. closePath: closePath,
  24092. offset: offset,
  24093. updatable: updatable,
  24094. sideOrientation: sideOrientation,
  24095. instance: instance
  24096. }, scene);
  24097. };
  24098. /**
  24099. * Creates a plane polygonal mesh. By default, this is a disc.
  24100. * Please consider using the same method from the MeshBuilder class instead.
  24101. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24102. * 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.
  24103. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24104. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24105. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24106. */
  24107. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24108. var options = {
  24109. radius: radius,
  24110. tessellation: tessellation,
  24111. sideOrientation: sideOrientation,
  24112. updatable: updatable
  24113. };
  24114. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24115. };
  24116. /**
  24117. * Creates a box mesh.
  24118. * Please consider using the same method from the MeshBuilder class instead.
  24119. * The parameter `size` sets the size (float) of each box side (default 1).
  24120. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24121. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24123. */
  24124. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24125. var options = {
  24126. size: size,
  24127. sideOrientation: sideOrientation,
  24128. updatable: updatable
  24129. };
  24130. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24131. };
  24132. /**
  24133. * Creates a sphere mesh.
  24134. * Please consider using the same method from the MeshBuilder class instead.
  24135. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24136. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24137. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24138. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24139. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24140. */
  24141. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24142. var options = {
  24143. segments: segments,
  24144. diameterX: diameter,
  24145. diameterY: diameter,
  24146. diameterZ: diameter,
  24147. sideOrientation: sideOrientation,
  24148. updatable: updatable
  24149. };
  24150. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24151. };
  24152. /**
  24153. * Creates a cylinder or a cone mesh.
  24154. * Please consider using the same method from the MeshBuilder class instead.
  24155. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24156. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24157. * 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.
  24158. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24159. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24160. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24161. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24162. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24163. */
  24164. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24165. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24166. if (scene !== undefined) {
  24167. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24168. updatable = scene;
  24169. }
  24170. scene = subdivisions;
  24171. subdivisions = 1;
  24172. }
  24173. var options = {
  24174. height: height,
  24175. diameterTop: diameterTop,
  24176. diameterBottom: diameterBottom,
  24177. tessellation: tessellation,
  24178. subdivisions: subdivisions,
  24179. sideOrientation: sideOrientation,
  24180. updatable: updatable
  24181. };
  24182. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24183. };
  24184. // Torus (Code from SharpDX.org)
  24185. /**
  24186. * Creates a torus mesh.
  24187. * Please consider using the same method from the MeshBuilder class instead.
  24188. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24189. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24190. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24191. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24192. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24193. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24194. */
  24195. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24196. var options = {
  24197. diameter: diameter,
  24198. thickness: thickness,
  24199. tessellation: tessellation,
  24200. sideOrientation: sideOrientation,
  24201. updatable: updatable
  24202. };
  24203. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24204. };
  24205. /**
  24206. * Creates a torus knot mesh.
  24207. * Please consider using the same method from the MeshBuilder class instead.
  24208. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24209. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24210. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24211. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24212. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24213. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24214. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24215. */
  24216. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24217. var options = {
  24218. radius: radius,
  24219. tube: tube,
  24220. radialSegments: radialSegments,
  24221. tubularSegments: tubularSegments,
  24222. p: p,
  24223. q: q,
  24224. sideOrientation: sideOrientation,
  24225. updatable: updatable
  24226. };
  24227. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24228. };
  24229. /**
  24230. * Creates a line mesh.
  24231. * Please consider using the same method from the MeshBuilder class instead.
  24232. * 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.
  24233. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24234. * The parameter `points` is an array successive Vector3.
  24235. * 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
  24236. * When updating an instance, remember that only point positions can change, not the number of points.
  24237. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24238. */
  24239. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24240. var options = {
  24241. points: points,
  24242. updatable: updatable,
  24243. instance: instance
  24244. };
  24245. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24246. };
  24247. /**
  24248. * Creates a dashed line mesh.
  24249. * Please consider using the same method from the MeshBuilder class instead.
  24250. * 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.
  24251. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24252. * The parameter `points` is an array successive Vector3.
  24253. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24254. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24255. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24256. * 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
  24257. * When updating an instance, remember that only point positions can change, not the number of points.
  24258. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24259. */
  24260. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24261. var options = {
  24262. points: points,
  24263. dashSize: dashSize,
  24264. gapSize: gapSize,
  24265. dashNb: dashNb,
  24266. updatable: updatable,
  24267. instance: instance
  24268. };
  24269. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24270. };
  24271. /**
  24272. * Creates an extruded shape mesh.
  24273. * 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.
  24274. * Please consider using the same method from the MeshBuilder class instead.
  24275. *
  24276. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24277. * 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
  24278. * extruded along the Z axis.
  24279. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24280. * 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.
  24281. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24282. * 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
  24283. * 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
  24284. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24285. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24286. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24287. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24288. */
  24289. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24290. var options = {
  24291. shape: shape,
  24292. path: path,
  24293. scale: scale,
  24294. rotation: rotation,
  24295. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24296. sideOrientation: sideOrientation,
  24297. instance: instance,
  24298. updatable: updatable
  24299. };
  24300. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24301. };
  24302. /**
  24303. * Creates an custom extruded shape mesh.
  24304. * 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.
  24305. * Please consider using the same method from the MeshBuilder class instead.
  24306. *
  24307. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24308. * 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
  24309. * extruded along the Z axis.
  24310. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24311. * 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
  24312. * and the distance of this point from the begining of the path :
  24313. * ```javascript
  24314. * var rotationFunction = function(i, distance) {
  24315. * // do things
  24316. * return rotationValue; }
  24317. * ```
  24318. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24319. * 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
  24320. * and the distance of this point from the begining of the path :
  24321. * ```javascript
  24322. * var scaleFunction = function(i, distance) {
  24323. * // do things
  24324. * return scaleValue;}
  24325. * ```
  24326. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24327. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24328. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24329. * 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
  24330. * 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
  24331. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24332. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24333. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24334. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24335. */
  24336. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24337. var options = {
  24338. shape: shape,
  24339. path: path,
  24340. scaleFunction: scaleFunction,
  24341. rotationFunction: rotationFunction,
  24342. ribbonCloseArray: ribbonCloseArray,
  24343. ribbonClosePath: ribbonClosePath,
  24344. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24345. sideOrientation: sideOrientation,
  24346. instance: instance,
  24347. updatable: updatable
  24348. };
  24349. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24350. };
  24351. /**
  24352. * Creates lathe mesh.
  24353. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  24354. * Please consider using the same method from the MeshBuilder class instead.
  24355. * 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
  24356. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  24357. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  24358. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  24359. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24360. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24361. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24362. */
  24363. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  24364. var options = {
  24365. shape: shape,
  24366. radius: radius,
  24367. tessellation: tessellation,
  24368. sideOrientation: sideOrientation,
  24369. updatable: updatable
  24370. };
  24371. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  24372. };
  24373. /**
  24374. * Creates a plane mesh.
  24375. * Please consider using the same method from the MeshBuilder class instead.
  24376. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  24377. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24378. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24379. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24380. */
  24381. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  24382. var options = {
  24383. size: size,
  24384. width: size,
  24385. height: size,
  24386. sideOrientation: sideOrientation,
  24387. updatable: updatable
  24388. };
  24389. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  24390. };
  24391. /**
  24392. * Creates a ground mesh.
  24393. * Please consider using the same method from the MeshBuilder class instead.
  24394. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  24395. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  24396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24397. */
  24398. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  24399. var options = {
  24400. width: width,
  24401. height: height,
  24402. subdivisions: subdivisions,
  24403. updatable: updatable
  24404. };
  24405. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  24406. };
  24407. /**
  24408. * Creates a tiled ground mesh.
  24409. * Please consider using the same method from the MeshBuilder class instead.
  24410. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  24411. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  24412. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  24413. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  24414. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  24415. * numbers of subdivisions on the ground width and height of each tile.
  24416. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24417. */
  24418. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  24419. var options = {
  24420. xmin: xmin,
  24421. zmin: zmin,
  24422. xmax: xmax,
  24423. zmax: zmax,
  24424. subdivisions: subdivisions,
  24425. precision: precision,
  24426. updatable: updatable
  24427. };
  24428. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  24429. };
  24430. /**
  24431. * Creates a ground mesh from a height map.
  24432. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  24433. * Please consider using the same method from the MeshBuilder class instead.
  24434. * The parameter `url` sets the URL of the height map image resource.
  24435. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  24436. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  24437. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  24438. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  24439. * 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).
  24440. * This function is passed the newly built mesh :
  24441. * ```javascript
  24442. * function(mesh) { // do things
  24443. * return; }
  24444. * ```
  24445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24446. */
  24447. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  24448. var options = {
  24449. width: width,
  24450. height: height,
  24451. subdivisions: subdivisions,
  24452. minHeight: minHeight,
  24453. maxHeight: maxHeight,
  24454. updatable: updatable,
  24455. onReady: onReady
  24456. };
  24457. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  24458. };
  24459. /**
  24460. * Creates a tube mesh.
  24461. * 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.
  24462. * Please consider using the same method from the MeshBuilder class instead.
  24463. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  24464. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  24465. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  24466. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  24467. * 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.
  24468. * It must return a radius value (positive float) :
  24469. * ```javascript
  24470. * var radiusFunction = function(i, distance) {
  24471. * // do things
  24472. * return radius; }
  24473. * ```
  24474. * 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
  24475. * 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
  24476. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24477. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24478. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24479. */
  24480. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  24481. var options = {
  24482. path: path,
  24483. radius: radius,
  24484. tessellation: tessellation,
  24485. radiusFunction: radiusFunction,
  24486. arc: 1,
  24487. cap: cap,
  24488. updatable: updatable,
  24489. sideOrientation: sideOrientation,
  24490. instance: instance
  24491. };
  24492. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  24493. };
  24494. /**
  24495. * Creates a polyhedron mesh.
  24496. * Please consider using the same method from the MeshBuilder class instead.
  24497. * 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
  24498. * to choose the wanted type.
  24499. * The parameter `size` (positive float, default 1) sets the polygon size.
  24500. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  24501. * 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`.
  24502. * 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
  24503. * 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)`).
  24504. * 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
  24505. * 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.
  24506. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24507. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24508. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24509. */
  24510. Mesh.CreatePolyhedron = function (name, options, scene) {
  24511. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  24512. };
  24513. /**
  24514. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  24515. * Please consider using the same method from the MeshBuilder class instead.
  24516. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  24517. * 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`).
  24518. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  24519. * 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.
  24520. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24521. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24522. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24523. */
  24524. Mesh.CreateIcoSphere = function (name, options, scene) {
  24525. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  24526. };
  24527. /**
  24528. * Creates a decal mesh.
  24529. * Please consider using the same method from the MeshBuilder class instead.
  24530. * 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.
  24531. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  24532. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  24533. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  24534. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  24535. */
  24536. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  24537. var options = {
  24538. position: position,
  24539. normal: normal,
  24540. size: size,
  24541. angle: angle
  24542. };
  24543. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  24544. };
  24545. // Skeletons
  24546. /**
  24547. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24548. */
  24549. Mesh.prototype.setPositionsForCPUSkinning = function () {
  24550. var source;
  24551. if (!this._sourcePositions) {
  24552. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24553. this._sourcePositions = new Float32Array(source);
  24554. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  24555. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  24556. }
  24557. }
  24558. return this._sourcePositions;
  24559. };
  24560. /**
  24561. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24562. */
  24563. Mesh.prototype.setNormalsForCPUSkinning = function () {
  24564. var source;
  24565. if (!this._sourceNormals) {
  24566. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24567. this._sourceNormals = new Float32Array(source);
  24568. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  24569. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  24570. }
  24571. }
  24572. return this._sourceNormals;
  24573. };
  24574. /**
  24575. * Updates the vertex buffer by applying transformation from the bones.
  24576. * Returns the Mesh.
  24577. *
  24578. * @param {skeleton} skeleton to apply
  24579. */
  24580. Mesh.prototype.applySkeleton = function (skeleton) {
  24581. if (!this.geometry) {
  24582. return this;
  24583. }
  24584. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  24585. return this;
  24586. }
  24587. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  24588. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24589. return this;
  24590. }
  24591. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24592. return this;
  24593. }
  24594. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24595. return this;
  24596. }
  24597. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24598. return this;
  24599. }
  24600. if (!this._sourcePositions) {
  24601. var submeshes = this.subMeshes.slice();
  24602. this.setPositionsForCPUSkinning();
  24603. this.subMeshes = submeshes;
  24604. }
  24605. if (!this._sourceNormals) {
  24606. this.setNormalsForCPUSkinning();
  24607. }
  24608. // positionsData checks for not being Float32Array will only pass at most once
  24609. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24610. if (!(positionsData instanceof Float32Array)) {
  24611. positionsData = new Float32Array(positionsData);
  24612. }
  24613. // normalsData checks for not being Float32Array will only pass at most once
  24614. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24615. if (!(normalsData instanceof Float32Array)) {
  24616. normalsData = new Float32Array(normalsData);
  24617. }
  24618. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24619. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24620. var needExtras = this.numBoneInfluencers > 4;
  24621. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  24622. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  24623. var skeletonMatrices = skeleton.getTransformMatrices(this);
  24624. var tempVector3 = BABYLON.Vector3.Zero();
  24625. var finalMatrix = new BABYLON.Matrix();
  24626. var tempMatrix = new BABYLON.Matrix();
  24627. var matWeightIdx = 0;
  24628. var inf;
  24629. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  24630. var weight;
  24631. for (inf = 0; inf < 4; inf++) {
  24632. weight = matricesWeightsData[matWeightIdx + inf];
  24633. if (weight > 0) {
  24634. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24635. finalMatrix.addToSelf(tempMatrix);
  24636. }
  24637. else
  24638. break;
  24639. }
  24640. if (needExtras) {
  24641. for (inf = 0; inf < 4; inf++) {
  24642. weight = matricesWeightsExtraData[matWeightIdx + inf];
  24643. if (weight > 0) {
  24644. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24645. finalMatrix.addToSelf(tempMatrix);
  24646. }
  24647. else
  24648. break;
  24649. }
  24650. }
  24651. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  24652. tempVector3.toArray(positionsData, index);
  24653. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  24654. tempVector3.toArray(normalsData, index);
  24655. finalMatrix.reset();
  24656. }
  24657. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  24658. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  24659. return this;
  24660. };
  24661. // Tools
  24662. /**
  24663. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  24664. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  24665. */
  24666. Mesh.MinMax = function (meshes) {
  24667. var minVector = null;
  24668. var maxVector = null;
  24669. meshes.forEach(function (mesh, index, array) {
  24670. var boundingBox = mesh.getBoundingInfo().boundingBox;
  24671. if (!minVector) {
  24672. minVector = boundingBox.minimumWorld;
  24673. maxVector = boundingBox.maximumWorld;
  24674. }
  24675. else {
  24676. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  24677. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  24678. }
  24679. });
  24680. return {
  24681. min: minVector,
  24682. max: maxVector
  24683. };
  24684. };
  24685. /**
  24686. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  24687. */
  24688. Mesh.Center = function (meshesOrMinMaxVector) {
  24689. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  24690. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  24691. };
  24692. /**
  24693. * Merge the array of meshes into a single mesh for performance reasons.
  24694. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  24695. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  24696. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  24697. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  24698. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  24699. */
  24700. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  24701. if (disposeSource === void 0) { disposeSource = true; }
  24702. var index;
  24703. if (!allow32BitsIndices) {
  24704. var totalVertices = 0;
  24705. // Counting vertices
  24706. for (index = 0; index < meshes.length; index++) {
  24707. if (meshes[index]) {
  24708. totalVertices += meshes[index].getTotalVertices();
  24709. if (totalVertices > 65536) {
  24710. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  24711. return null;
  24712. }
  24713. }
  24714. }
  24715. }
  24716. // Merge
  24717. var vertexData;
  24718. var otherVertexData;
  24719. var indiceArray = new Array();
  24720. var source;
  24721. for (index = 0; index < meshes.length; index++) {
  24722. if (meshes[index]) {
  24723. meshes[index].computeWorldMatrix(true);
  24724. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  24725. otherVertexData.transform(meshes[index].getWorldMatrix());
  24726. if (vertexData) {
  24727. vertexData.merge(otherVertexData);
  24728. }
  24729. else {
  24730. vertexData = otherVertexData;
  24731. source = meshes[index];
  24732. }
  24733. if (subdivideWithSubMeshes) {
  24734. indiceArray.push(meshes[index].getTotalIndices());
  24735. }
  24736. }
  24737. }
  24738. if (!meshSubclass) {
  24739. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  24740. }
  24741. vertexData.applyToMesh(meshSubclass);
  24742. // Setting properties
  24743. meshSubclass.material = source.material;
  24744. meshSubclass.checkCollisions = source.checkCollisions;
  24745. // Cleaning
  24746. if (disposeSource) {
  24747. for (index = 0; index < meshes.length; index++) {
  24748. if (meshes[index]) {
  24749. meshes[index].dispose();
  24750. }
  24751. }
  24752. }
  24753. // Subdivide
  24754. if (subdivideWithSubMeshes) {
  24755. //-- Suppresions du submesh global
  24756. meshSubclass.releaseSubMeshes();
  24757. index = 0;
  24758. var offset = 0;
  24759. //-- aplique la subdivision en fonction du tableau d'indices
  24760. while (index < indiceArray.length) {
  24761. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  24762. offset += indiceArray[index];
  24763. index++;
  24764. }
  24765. }
  24766. return meshSubclass;
  24767. };
  24768. return Mesh;
  24769. }(BABYLON.AbstractMesh));
  24770. // Consts
  24771. Mesh._FRONTSIDE = 0;
  24772. Mesh._BACKSIDE = 1;
  24773. Mesh._DOUBLESIDE = 2;
  24774. Mesh._DEFAULTSIDE = 0;
  24775. Mesh._NO_CAP = 0;
  24776. Mesh._CAP_START = 1;
  24777. Mesh._CAP_END = 2;
  24778. Mesh._CAP_ALL = 3;
  24779. BABYLON.Mesh = Mesh;
  24780. })(BABYLON || (BABYLON = {}));
  24781. //# sourceMappingURL=babylon.mesh.js.map
  24782. var BABYLON;
  24783. (function (BABYLON) {
  24784. var SubMesh = (function () {
  24785. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  24786. if (createBoundingBox === void 0) { createBoundingBox = true; }
  24787. this.materialIndex = materialIndex;
  24788. this.verticesStart = verticesStart;
  24789. this.verticesCount = verticesCount;
  24790. this.indexStart = indexStart;
  24791. this.indexCount = indexCount;
  24792. this._renderId = 0;
  24793. this._mesh = mesh;
  24794. this._renderingMesh = renderingMesh || mesh;
  24795. mesh.subMeshes.push(this);
  24796. this._trianglePlanes = [];
  24797. this._id = mesh.subMeshes.length - 1;
  24798. if (createBoundingBox) {
  24799. this.refreshBoundingInfo();
  24800. mesh.computeWorldMatrix(true);
  24801. }
  24802. }
  24803. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  24804. get: function () {
  24805. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  24806. },
  24807. enumerable: true,
  24808. configurable: true
  24809. });
  24810. /**
  24811. * Returns the submesh BoudingInfo object.
  24812. */
  24813. SubMesh.prototype.getBoundingInfo = function () {
  24814. if (this.IsGlobal) {
  24815. return this._mesh.getBoundingInfo();
  24816. }
  24817. return this._boundingInfo;
  24818. };
  24819. /**
  24820. * Sets the submesh BoundingInfo.
  24821. * Return the SubMesh.
  24822. */
  24823. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  24824. this._boundingInfo = boundingInfo;
  24825. return this;
  24826. };
  24827. /**
  24828. * Returns the mesh of the current submesh.
  24829. */
  24830. SubMesh.prototype.getMesh = function () {
  24831. return this._mesh;
  24832. };
  24833. /**
  24834. * Returns the rendering mesh of the submesh.
  24835. */
  24836. SubMesh.prototype.getRenderingMesh = function () {
  24837. return this._renderingMesh;
  24838. };
  24839. /**
  24840. * Returns the submesh material.
  24841. */
  24842. SubMesh.prototype.getMaterial = function () {
  24843. var rootMaterial = this._renderingMesh.material;
  24844. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  24845. var multiMaterial = rootMaterial;
  24846. return multiMaterial.getSubMaterial(this.materialIndex);
  24847. }
  24848. if (!rootMaterial) {
  24849. return this._mesh.getScene().defaultMaterial;
  24850. }
  24851. return rootMaterial;
  24852. };
  24853. // Methods
  24854. /**
  24855. * Sets a new updated BoundingInfo object to the submesh.
  24856. * Returns the SubMesh.
  24857. */
  24858. SubMesh.prototype.refreshBoundingInfo = function () {
  24859. this._lastColliderWorldVertices = null;
  24860. if (this.IsGlobal) {
  24861. return;
  24862. }
  24863. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24864. if (!data) {
  24865. this._boundingInfo = this._mesh._boundingInfo;
  24866. return;
  24867. }
  24868. var indices = this._renderingMesh.getIndices();
  24869. var extend;
  24870. //is this the only submesh?
  24871. if (this.indexStart === 0 && this.indexCount === indices.length) {
  24872. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  24873. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  24874. }
  24875. else {
  24876. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  24877. }
  24878. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24879. return this;
  24880. };
  24881. SubMesh.prototype._checkCollision = function (collider) {
  24882. return this.getBoundingInfo()._checkCollision(collider);
  24883. };
  24884. /**
  24885. * Updates the submesh BoundingInfo.
  24886. * Returns the Submesh.
  24887. */
  24888. SubMesh.prototype.updateBoundingInfo = function (world) {
  24889. if (!this.getBoundingInfo()) {
  24890. this.refreshBoundingInfo();
  24891. }
  24892. this.getBoundingInfo().update(world);
  24893. return this;
  24894. };
  24895. /**
  24896. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  24897. * Boolean returned.
  24898. */
  24899. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  24900. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  24901. };
  24902. /**
  24903. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  24904. * Boolean returned.
  24905. */
  24906. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  24907. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  24908. };
  24909. /**
  24910. * Renders the submesh.
  24911. * Returns it.
  24912. */
  24913. SubMesh.prototype.render = function (enableAlphaMode) {
  24914. this._renderingMesh.render(this, enableAlphaMode);
  24915. return this;
  24916. };
  24917. /**
  24918. * Returns a new Index Buffer.
  24919. * Type returned : WebGLBuffer.
  24920. */
  24921. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  24922. if (!this._linesIndexBuffer) {
  24923. var linesIndices = [];
  24924. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24925. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  24926. }
  24927. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  24928. this.linesIndexCount = linesIndices.length;
  24929. }
  24930. return this._linesIndexBuffer;
  24931. };
  24932. /**
  24933. * True is the passed Ray intersects the submesh bounding box.
  24934. * Boolean returned.
  24935. */
  24936. SubMesh.prototype.canIntersects = function (ray) {
  24937. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  24938. };
  24939. /**
  24940. * Returns an object IntersectionInfo.
  24941. */
  24942. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  24943. var intersectInfo = null;
  24944. // LineMesh first as it's also a Mesh...
  24945. if (this._mesh instanceof BABYLON.LinesMesh) {
  24946. var lineMesh = this._mesh;
  24947. // Line test
  24948. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  24949. var p0 = positions[indices[index]];
  24950. var p1 = positions[indices[index + 1]];
  24951. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  24952. if (length < 0) {
  24953. continue;
  24954. }
  24955. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  24956. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  24957. if (fastCheck) {
  24958. break;
  24959. }
  24960. }
  24961. }
  24962. }
  24963. else {
  24964. // Triangles test
  24965. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24966. var p0 = positions[indices[index]];
  24967. var p1 = positions[indices[index + 1]];
  24968. var p2 = positions[indices[index + 2]];
  24969. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  24970. if (currentIntersectInfo) {
  24971. if (currentIntersectInfo.distance < 0) {
  24972. continue;
  24973. }
  24974. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  24975. intersectInfo = currentIntersectInfo;
  24976. intersectInfo.faceId = index / 3;
  24977. if (fastCheck) {
  24978. break;
  24979. }
  24980. }
  24981. }
  24982. }
  24983. }
  24984. return intersectInfo;
  24985. };
  24986. // Clone
  24987. /**
  24988. * Creates a new Submesh from the passed Mesh.
  24989. */
  24990. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  24991. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  24992. if (!this.IsGlobal) {
  24993. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  24994. }
  24995. return result;
  24996. };
  24997. // Dispose
  24998. /**
  24999. * Disposes the Submesh.
  25000. * Returns nothing.
  25001. */
  25002. SubMesh.prototype.dispose = function () {
  25003. if (this._linesIndexBuffer) {
  25004. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25005. this._linesIndexBuffer = null;
  25006. }
  25007. // Remove from mesh
  25008. var index = this._mesh.subMeshes.indexOf(this);
  25009. this._mesh.subMeshes.splice(index, 1);
  25010. };
  25011. // Statics
  25012. /**
  25013. * Creates a new Submesh from the passed parameters :
  25014. * - materialIndex (integer) : the index of the main mesh material.
  25015. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25016. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25017. * - mesh (Mesh) : the main mesh to create the submesh from.
  25018. * - renderingMesh (optional Mesh) : rendering mesh.
  25019. */
  25020. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25021. var minVertexIndex = Number.MAX_VALUE;
  25022. var maxVertexIndex = -Number.MAX_VALUE;
  25023. renderingMesh = renderingMesh || mesh;
  25024. var indices = renderingMesh.getIndices();
  25025. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25026. var vertexIndex = indices[index];
  25027. if (vertexIndex < minVertexIndex)
  25028. minVertexIndex = vertexIndex;
  25029. if (vertexIndex > maxVertexIndex)
  25030. maxVertexIndex = vertexIndex;
  25031. }
  25032. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25033. };
  25034. return SubMesh;
  25035. }());
  25036. BABYLON.SubMesh = SubMesh;
  25037. })(BABYLON || (BABYLON = {}));
  25038. //# sourceMappingURL=babylon.subMesh.js.map
  25039. var BABYLON;
  25040. (function (BABYLON) {
  25041. var MeshBuilder = (function () {
  25042. function MeshBuilder() {
  25043. }
  25044. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  25045. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  25046. return BABYLON.Mesh.DOUBLESIDE;
  25047. }
  25048. if (orientation === undefined || orientation === null) {
  25049. return BABYLON.Mesh.FRONTSIDE;
  25050. }
  25051. return orientation;
  25052. };
  25053. /**
  25054. * Creates a box mesh.
  25055. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  25056. * The parameter `size` sets the size (float) of each box side (default 1).
  25057. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  25058. * 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).
  25059. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  25060. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25061. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25062. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25063. */
  25064. MeshBuilder.CreateBox = function (name, options, scene) {
  25065. var box = new BABYLON.Mesh(name, scene);
  25066. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25067. box.sideOrientation = options.sideOrientation;
  25068. var vertexData = BABYLON.VertexData.CreateBox(options);
  25069. vertexData.applyToMesh(box, options.updatable);
  25070. return box;
  25071. };
  25072. /**
  25073. * Creates a sphere mesh.
  25074. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  25075. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25076. * 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`).
  25077. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25078. * 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
  25079. * 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).
  25080. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25081. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25082. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25083. */
  25084. MeshBuilder.CreateSphere = function (name, options, scene) {
  25085. var sphere = new BABYLON.Mesh(name, scene);
  25086. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25087. sphere.sideOrientation = options.sideOrientation;
  25088. var vertexData = BABYLON.VertexData.CreateSphere(options);
  25089. vertexData.applyToMesh(sphere, options.updatable);
  25090. return sphere;
  25091. };
  25092. /**
  25093. * Creates a plane polygonal mesh. By default, this is a disc.
  25094. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  25095. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25096. * 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.
  25097. * 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
  25098. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25099. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25100. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25101. */
  25102. MeshBuilder.CreateDisc = function (name, options, scene) {
  25103. var disc = new BABYLON.Mesh(name, scene);
  25104. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25105. disc.sideOrientation = options.sideOrientation;
  25106. var vertexData = BABYLON.VertexData.CreateDisc(options);
  25107. vertexData.applyToMesh(disc, options.updatable);
  25108. return disc;
  25109. };
  25110. /**
  25111. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25112. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  25113. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25114. * 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`).
  25115. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25116. * 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.
  25117. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25118. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25119. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25120. */
  25121. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  25122. var sphere = new BABYLON.Mesh(name, scene);
  25123. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25124. sphere.sideOrientation = options.sideOrientation;
  25125. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  25126. vertexData.applyToMesh(sphere, options.updatable);
  25127. return sphere;
  25128. };
  25129. ;
  25130. /**
  25131. * Creates a ribbon mesh.
  25132. * 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.
  25133. *
  25134. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25135. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25136. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25137. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25138. * 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.
  25139. * 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.
  25140. * 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
  25141. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25142. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25143. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25144. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25145. */
  25146. MeshBuilder.CreateRibbon = function (name, options, scene) {
  25147. var pathArray = options.pathArray;
  25148. var closeArray = options.closeArray;
  25149. var closePath = options.closePath;
  25150. var offset = options.offset;
  25151. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25152. var instance = options.instance;
  25153. var updatable = options.updatable;
  25154. if (instance) {
  25155. // positionFunction : ribbon case
  25156. // only pathArray and sideOrientation parameters are taken into account for positions update
  25157. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  25158. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  25159. var positionFunction = function (positions) {
  25160. var minlg = pathArray[0].length;
  25161. var i = 0;
  25162. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  25163. for (var si = 1; si <= ns; si++) {
  25164. for (var p = 0; p < pathArray.length; p++) {
  25165. var path = pathArray[p];
  25166. var l = path.length;
  25167. minlg = (minlg < l) ? minlg : l;
  25168. var j = 0;
  25169. while (j < minlg) {
  25170. positions[i] = path[j].x;
  25171. positions[i + 1] = path[j].y;
  25172. positions[i + 2] = path[j].z;
  25173. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  25174. BABYLON.Tmp.Vector3[0].x = path[j].x;
  25175. }
  25176. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  25177. BABYLON.Tmp.Vector3[1].x = path[j].x;
  25178. }
  25179. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  25180. BABYLON.Tmp.Vector3[0].y = path[j].y;
  25181. }
  25182. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  25183. BABYLON.Tmp.Vector3[1].y = path[j].y;
  25184. }
  25185. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  25186. BABYLON.Tmp.Vector3[0].z = path[j].z;
  25187. }
  25188. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  25189. BABYLON.Tmp.Vector3[1].z = path[j].z;
  25190. }
  25191. j++;
  25192. i += 3;
  25193. }
  25194. if (instance._closePath) {
  25195. positions[i] = path[0].x;
  25196. positions[i + 1] = path[0].y;
  25197. positions[i + 2] = path[0].z;
  25198. i += 3;
  25199. }
  25200. }
  25201. }
  25202. };
  25203. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25204. positionFunction(positions);
  25205. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  25206. instance._boundingInfo.update(instance._worldMatrix);
  25207. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25208. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  25209. var indices = instance.getIndices();
  25210. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25211. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  25212. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  25213. if (instance._closePath) {
  25214. var indexFirst = 0;
  25215. var indexLast = 0;
  25216. for (var p = 0; p < pathArray.length; p++) {
  25217. indexFirst = instance._idx[p] * 3;
  25218. if (p + 1 < pathArray.length) {
  25219. indexLast = (instance._idx[p + 1] - 1) * 3;
  25220. }
  25221. else {
  25222. indexLast = normals.length - 3;
  25223. }
  25224. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25225. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25226. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25227. normals[indexLast] = normals[indexFirst];
  25228. normals[indexLast + 1] = normals[indexFirst + 1];
  25229. normals[indexLast + 2] = normals[indexFirst + 2];
  25230. }
  25231. }
  25232. if (!(instance.areNormalsFrozen)) {
  25233. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25234. }
  25235. }
  25236. return instance;
  25237. }
  25238. else {
  25239. var ribbon = new BABYLON.Mesh(name, scene);
  25240. ribbon.sideOrientation = sideOrientation;
  25241. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  25242. if (closePath) {
  25243. ribbon._idx = vertexData._idx;
  25244. }
  25245. ribbon._closePath = closePath;
  25246. ribbon._closeArray = closeArray;
  25247. vertexData.applyToMesh(ribbon, updatable);
  25248. return ribbon;
  25249. }
  25250. };
  25251. /**
  25252. * Creates a cylinder or a cone mesh.
  25253. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  25254. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25255. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25256. * 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.
  25257. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25258. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25259. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  25260. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  25261. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  25262. * 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).
  25263. * 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
  25264. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  25265. * 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
  25266. * 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.
  25267. * If `enclose` is false, a ring surface is one element.
  25268. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  25269. * 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
  25270. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25271. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25272. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25273. */
  25274. MeshBuilder.CreateCylinder = function (name, options, scene) {
  25275. var cylinder = new BABYLON.Mesh(name, scene);
  25276. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25277. cylinder.sideOrientation = options.sideOrientation;
  25278. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  25279. vertexData.applyToMesh(cylinder, options.updatable);
  25280. return cylinder;
  25281. };
  25282. /**
  25283. * Creates a torus mesh.
  25284. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  25285. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25286. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25287. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25288. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25289. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25290. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25291. */
  25292. MeshBuilder.CreateTorus = function (name, options, scene) {
  25293. var torus = new BABYLON.Mesh(name, scene);
  25294. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25295. torus.sideOrientation = options.sideOrientation;
  25296. var vertexData = BABYLON.VertexData.CreateTorus(options);
  25297. vertexData.applyToMesh(torus, options.updatable);
  25298. return torus;
  25299. };
  25300. /**
  25301. * Creates a torus knot mesh.
  25302. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  25303. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25304. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25305. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25306. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  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. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  25312. var torusKnot = new BABYLON.Mesh(name, scene);
  25313. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25314. torusKnot.sideOrientation = options.sideOrientation;
  25315. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  25316. vertexData.applyToMesh(torusKnot, options.updatable);
  25317. return torusKnot;
  25318. };
  25319. /**
  25320. * Creates a line system mesh.
  25321. * A line system is a pool of many lines gathered in a single mesh.
  25322. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  25323. * 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.
  25324. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  25325. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  25326. * 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
  25327. * 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
  25328. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  25329. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25330. */
  25331. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  25332. var instance = options.instance;
  25333. var lines = options.lines;
  25334. if (instance) {
  25335. var positionFunction = function (positions) {
  25336. var i = 0;
  25337. for (var l = 0; l < lines.length; l++) {
  25338. var points = lines[l];
  25339. for (var p = 0; p < points.length; p++) {
  25340. positions[i] = points[p].x;
  25341. positions[i + 1] = points[p].y;
  25342. positions[i + 2] = points[p].z;
  25343. i += 3;
  25344. }
  25345. }
  25346. };
  25347. instance.updateMeshPositions(positionFunction, false);
  25348. return instance;
  25349. }
  25350. // line system creation
  25351. var lineSystem = new BABYLON.LinesMesh(name, scene);
  25352. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  25353. vertexData.applyToMesh(lineSystem, options.updatable);
  25354. return lineSystem;
  25355. };
  25356. /**
  25357. * Creates a line mesh.
  25358. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  25359. * 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.
  25360. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25361. * The parameter `points` is an array successive Vector3.
  25362. * 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
  25363. * When updating an instance, remember that only point positions can change, not the number of points.
  25364. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25365. */
  25366. MeshBuilder.CreateLines = function (name, options, scene) {
  25367. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  25368. return lines;
  25369. };
  25370. /**
  25371. * Creates a dashed line mesh.
  25372. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  25373. * 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.
  25374. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25375. * The parameter `points` is an array successive Vector3.
  25376. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  25377. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  25378. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  25379. * 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
  25380. * When updating an instance, remember that only point positions can change, not the number of points.
  25381. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25382. */
  25383. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  25384. var points = options.points;
  25385. var instance = options.instance;
  25386. var gapSize = options.gapSize;
  25387. var dashNb = options.dashNb;
  25388. var dashSize = options.dashSize;
  25389. if (instance) {
  25390. var positionFunction = function (positions) {
  25391. var curvect = BABYLON.Vector3.Zero();
  25392. var nbSeg = positions.length / 6;
  25393. var lg = 0;
  25394. var nb = 0;
  25395. var shft = 0;
  25396. var dashshft = 0;
  25397. var curshft = 0;
  25398. var p = 0;
  25399. var i = 0;
  25400. var j = 0;
  25401. for (i = 0; i < points.length - 1; i++) {
  25402. points[i + 1].subtractToRef(points[i], curvect);
  25403. lg += curvect.length();
  25404. }
  25405. shft = lg / nbSeg;
  25406. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  25407. for (i = 0; i < points.length - 1; i++) {
  25408. points[i + 1].subtractToRef(points[i], curvect);
  25409. nb = Math.floor(curvect.length() / shft);
  25410. curvect.normalize();
  25411. j = 0;
  25412. while (j < nb && p < positions.length) {
  25413. curshft = shft * j;
  25414. positions[p] = points[i].x + curshft * curvect.x;
  25415. positions[p + 1] = points[i].y + curshft * curvect.y;
  25416. positions[p + 2] = points[i].z + curshft * curvect.z;
  25417. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  25418. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  25419. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  25420. p += 6;
  25421. j++;
  25422. }
  25423. }
  25424. while (p < positions.length) {
  25425. positions[p] = points[i].x;
  25426. positions[p + 1] = points[i].y;
  25427. positions[p + 2] = points[i].z;
  25428. p += 3;
  25429. }
  25430. };
  25431. instance.updateMeshPositions(positionFunction, false);
  25432. return instance;
  25433. }
  25434. // dashed lines creation
  25435. var dashedLines = new BABYLON.LinesMesh(name, scene);
  25436. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  25437. vertexData.applyToMesh(dashedLines, options.updatable);
  25438. dashedLines.dashSize = dashSize;
  25439. dashedLines.gapSize = gapSize;
  25440. return dashedLines;
  25441. };
  25442. /**
  25443. * Creates an extruded shape mesh.
  25444. * 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.
  25445. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  25446. *
  25447. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25448. * 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
  25449. * extruded along the Z axis.
  25450. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25451. * 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.
  25452. * The parameter `scale` (float, default 1) is the value to scale the shape.
  25453. * 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
  25454. * 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
  25455. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25456. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25457. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25458. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25459. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25460. */
  25461. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  25462. var path = options.path;
  25463. var shape = options.shape;
  25464. var scale = options.scale || 1;
  25465. var rotation = options.rotation || 0;
  25466. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  25467. var updatable = options.updatable;
  25468. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25469. var instance = options.instance;
  25470. var invertUV = options.invertUV || false;
  25471. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  25472. };
  25473. /**
  25474. * Creates an custom extruded shape mesh.
  25475. * 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.
  25476. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  25477. *
  25478. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25479. * 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
  25480. * extruded along the Z axis.
  25481. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25482. * 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
  25483. * and the distance of this point from the begining of the path :
  25484. * ```javascript
  25485. * var rotationFunction = function(i, distance) {
  25486. * // do things
  25487. * return rotationValue; }
  25488. * ```
  25489. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  25490. * 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
  25491. * and the distance of this point from the begining of the path :
  25492. * ```javascript
  25493. * var scaleFunction = function(i, distance) {
  25494. * // do things
  25495. * return scaleValue;}
  25496. * ```
  25497. * It must returns a float value that will be the scale value applied to the shape on each path point.
  25498. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  25499. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  25500. * 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
  25501. * 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
  25502. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25503. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25504. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25505. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25506. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25507. */
  25508. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  25509. var path = options.path;
  25510. var shape = options.shape;
  25511. var scaleFunction = options.scaleFunction || (function () { return 1; });
  25512. var rotationFunction = options.rotationFunction || (function () { return 0; });
  25513. var ribbonCloseArray = options.ribbonCloseArray || false;
  25514. var ribbonClosePath = options.ribbonClosePath || false;
  25515. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  25516. var updatable = options.updatable;
  25517. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25518. var instance = options.instance;
  25519. var invertUV = options.invertUV || false;
  25520. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  25521. };
  25522. /**
  25523. * Creates lathe mesh.
  25524. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25525. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  25526. *
  25527. * 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
  25528. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25529. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25530. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25531. * 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.
  25532. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  25533. * 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
  25534. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25535. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25536. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25537. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25538. */
  25539. MeshBuilder.CreateLathe = function (name, options, scene) {
  25540. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  25541. var closed = (options.closed === undefined) ? true : options.closed;
  25542. var shape = options.shape;
  25543. var radius = options.radius || 1;
  25544. var tessellation = options.tessellation || 64;
  25545. var updatable = options.updatable;
  25546. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25547. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  25548. var pi2 = Math.PI * 2;
  25549. var paths = new Array();
  25550. var invertUV = options.invertUV || false;
  25551. var i = 0;
  25552. var p = 0;
  25553. var step = pi2 / tessellation * arc;
  25554. var rotated;
  25555. var path = new Array();
  25556. ;
  25557. for (i = 0; i <= tessellation; i++) {
  25558. var path = [];
  25559. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  25560. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  25561. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  25562. }
  25563. for (p = 0; p < shape.length; p++) {
  25564. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  25565. path.push(rotated);
  25566. }
  25567. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  25568. 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));
  25569. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  25570. }
  25571. paths.push(path);
  25572. }
  25573. // lathe ribbon
  25574. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  25575. return lathe;
  25576. };
  25577. /**
  25578. * Creates a plane mesh.
  25579. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  25580. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25581. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  25582. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  25583. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25584. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25585. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25586. */
  25587. MeshBuilder.CreatePlane = function (name, options, scene) {
  25588. var plane = new BABYLON.Mesh(name, scene);
  25589. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25590. plane.sideOrientation = options.sideOrientation;
  25591. var vertexData = BABYLON.VertexData.CreatePlane(options);
  25592. vertexData.applyToMesh(plane, options.updatable);
  25593. if (options.sourcePlane) {
  25594. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  25595. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  25596. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  25597. plane.rotate(vectorProduct, product);
  25598. }
  25599. return plane;
  25600. };
  25601. /**
  25602. * Creates a ground mesh.
  25603. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  25604. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25605. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25606. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25607. */
  25608. MeshBuilder.CreateGround = function (name, options, scene) {
  25609. var ground = new BABYLON.GroundMesh(name, scene);
  25610. ground._setReady(false);
  25611. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  25612. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  25613. ground._width = options.width || 1;
  25614. ground._height = options.height || 1;
  25615. ground._maxX = ground._width / 2;
  25616. ground._maxZ = ground._height / 2;
  25617. ground._minX = -ground._maxX;
  25618. ground._minZ = -ground._maxZ;
  25619. var vertexData = BABYLON.VertexData.CreateGround(options);
  25620. vertexData.applyToMesh(ground, options.updatable);
  25621. ground._setReady(true);
  25622. return ground;
  25623. };
  25624. /**
  25625. * Creates a tiled ground mesh.
  25626. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  25627. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25628. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25629. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25630. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25631. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25632. * numbers of subdivisions on the ground width and height of each tile.
  25633. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25634. */
  25635. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  25636. var tiledGround = new BABYLON.Mesh(name, scene);
  25637. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  25638. vertexData.applyToMesh(tiledGround, options.updatable);
  25639. return tiledGround;
  25640. };
  25641. /**
  25642. * Creates a ground mesh from a height map.
  25643. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25644. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  25645. * The parameter `url` sets the URL of the height map image resource.
  25646. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25647. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25648. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25649. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25650. * 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.
  25651. * 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).
  25652. * This function is passed the newly built mesh :
  25653. * ```javascript
  25654. * function(mesh) { // do things
  25655. * return; }
  25656. * ```
  25657. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25658. */
  25659. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  25660. var width = options.width || 10.0;
  25661. var height = options.height || 10.0;
  25662. var subdivisions = options.subdivisions || 1 | 0;
  25663. var minHeight = options.minHeight || 0.0;
  25664. var maxHeight = options.maxHeight || 10.0;
  25665. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  25666. var updatable = options.updatable;
  25667. var onReady = options.onReady;
  25668. var ground = new BABYLON.GroundMesh(name, scene);
  25669. ground._subdivisionsX = subdivisions;
  25670. ground._subdivisionsY = subdivisions;
  25671. ground._width = width;
  25672. ground._height = height;
  25673. ground._maxX = ground._width / 2.0;
  25674. ground._maxZ = ground._height / 2.0;
  25675. ground._minX = -ground._maxX;
  25676. ground._minZ = -ground._maxZ;
  25677. ground._setReady(false);
  25678. var onload = function (img) {
  25679. // Getting height map data
  25680. var canvas = document.createElement("canvas");
  25681. var context = canvas.getContext("2d");
  25682. var bufferWidth = img.width;
  25683. var bufferHeight = img.height;
  25684. canvas.width = bufferWidth;
  25685. canvas.height = bufferHeight;
  25686. context.drawImage(img, 0, 0);
  25687. // Create VertexData from map data
  25688. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  25689. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  25690. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  25691. width: width, height: height,
  25692. subdivisions: subdivisions,
  25693. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  25694. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  25695. });
  25696. vertexData.applyToMesh(ground, updatable);
  25697. ground._setReady(true);
  25698. //execute ready callback, if set
  25699. if (onReady) {
  25700. onReady(ground);
  25701. }
  25702. };
  25703. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  25704. return ground;
  25705. };
  25706. /**
  25707. * Creates a tube mesh.
  25708. * 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.
  25709. *
  25710. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  25711. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25712. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25713. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25714. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25715. * 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.
  25716. * It must return a radius value (positive float) :
  25717. * ```javascript
  25718. * var radiusFunction = function(i, distance) {
  25719. * // do things
  25720. * return radius; }
  25721. * ```
  25722. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  25723. * 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
  25724. * 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
  25725. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25726. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25727. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25728. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25729. */
  25730. MeshBuilder.CreateTube = function (name, options, scene) {
  25731. var path = options.path;
  25732. var radius = options.radius || 1.0;
  25733. var tessellation = options.tessellation || 64 | 0;
  25734. var radiusFunction = options.radiusFunction;
  25735. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  25736. var invertUV = options.invertUV || false;
  25737. var updatable = options.updatable;
  25738. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25739. var instance = options.instance;
  25740. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  25741. // tube geometry
  25742. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  25743. var tangents = path3D.getTangents();
  25744. var normals = path3D.getNormals();
  25745. var distances = path3D.getDistances();
  25746. var pi2 = Math.PI * 2;
  25747. var step = pi2 / tessellation * arc;
  25748. var returnRadius = function () { return radius; };
  25749. var radiusFunctionFinal = radiusFunction || returnRadius;
  25750. var circlePath;
  25751. var rad;
  25752. var normal;
  25753. var rotated;
  25754. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  25755. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  25756. for (var i = 0; i < path.length; i++) {
  25757. rad = radiusFunctionFinal(i, distances[i]); // current radius
  25758. circlePath = Array(); // current circle array
  25759. normal = normals[i]; // current normal
  25760. for (var t = 0; t < tessellation; t++) {
  25761. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  25762. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  25763. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  25764. rotated.scaleInPlace(rad).addInPlace(path[i]);
  25765. circlePath[t] = rotated;
  25766. }
  25767. circlePaths[index] = circlePath;
  25768. index++;
  25769. }
  25770. // cap
  25771. var capPath = function (nbPoints, pathIndex) {
  25772. var pointCap = Array();
  25773. for (var i = 0; i < nbPoints; i++) {
  25774. pointCap.push(path[pathIndex]);
  25775. }
  25776. return pointCap;
  25777. };
  25778. switch (cap) {
  25779. case BABYLON.Mesh.NO_CAP:
  25780. break;
  25781. case BABYLON.Mesh.CAP_START:
  25782. circlePaths[0] = capPath(tessellation, 0);
  25783. circlePaths[1] = circlePaths[2].slice(0);
  25784. break;
  25785. case BABYLON.Mesh.CAP_END:
  25786. circlePaths[index] = circlePaths[index - 1].slice(0);
  25787. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  25788. break;
  25789. case BABYLON.Mesh.CAP_ALL:
  25790. circlePaths[0] = capPath(tessellation, 0);
  25791. circlePaths[1] = circlePaths[2].slice(0);
  25792. circlePaths[index] = circlePaths[index - 1].slice(0);
  25793. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  25794. break;
  25795. default:
  25796. break;
  25797. }
  25798. return circlePaths;
  25799. };
  25800. var path3D;
  25801. var pathArray;
  25802. if (instance) {
  25803. var arc = options.arc || instance.arc;
  25804. path3D = (instance.path3D).update(path);
  25805. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  25806. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  25807. instance.path3D = path3D;
  25808. instance.pathArray = pathArray;
  25809. instance.arc = arc;
  25810. return instance;
  25811. }
  25812. // tube creation
  25813. path3D = new BABYLON.Path3D(path);
  25814. var newPathArray = new Array();
  25815. cap = (cap < 0 || cap > 3) ? 0 : cap;
  25816. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  25817. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  25818. tube.pathArray = pathArray;
  25819. tube.path3D = path3D;
  25820. tube.tessellation = tessellation;
  25821. tube.cap = cap;
  25822. tube.arc = options.arc;
  25823. return tube;
  25824. };
  25825. /**
  25826. * Creates a polyhedron mesh.
  25827. *
  25828. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  25829. * 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
  25830. * to choose the wanted type.
  25831. * The parameter `size` (positive float, default 1) sets the polygon size.
  25832. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25833. * 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`.
  25834. * 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
  25835. * 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)`).
  25836. * 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
  25837. * 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.
  25838. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25839. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25840. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25841. */
  25842. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  25843. var polyhedron = new BABYLON.Mesh(name, scene);
  25844. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25845. polyhedron.sideOrientation = options.sideOrientation;
  25846. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  25847. vertexData.applyToMesh(polyhedron, options.updatable);
  25848. return polyhedron;
  25849. };
  25850. /**
  25851. * Creates a decal mesh.
  25852. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  25853. * 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.
  25854. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25855. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25856. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25857. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25858. */
  25859. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  25860. var indices = sourceMesh.getIndices();
  25861. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25862. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25863. var position = options.position || BABYLON.Vector3.Zero();
  25864. var normal = options.normal || BABYLON.Vector3.Up();
  25865. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  25866. var angle = options.angle || 0;
  25867. // Getting correct rotation
  25868. if (!normal) {
  25869. var target = new BABYLON.Vector3(0, 0, 1);
  25870. var camera = sourceMesh.getScene().activeCamera;
  25871. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  25872. normal = camera.globalPosition.subtract(cameraWorldTarget);
  25873. }
  25874. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  25875. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  25876. var pitch = Math.atan2(normal.y, len);
  25877. // Matrix
  25878. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  25879. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  25880. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  25881. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  25882. var vertexData = new BABYLON.VertexData();
  25883. vertexData.indices = [];
  25884. vertexData.positions = [];
  25885. vertexData.normals = [];
  25886. vertexData.uvs = [];
  25887. var currentVertexDataIndex = 0;
  25888. var extractDecalVector3 = function (indexId) {
  25889. var vertexId = indices[indexId];
  25890. var result = new BABYLON.PositionNormalVertex();
  25891. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  25892. // Send vector to decal local world
  25893. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  25894. // Get normal
  25895. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  25896. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  25897. return result;
  25898. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  25899. var clip = function (vertices, axis) {
  25900. if (vertices.length === 0) {
  25901. return vertices;
  25902. }
  25903. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  25904. var clipVertices = function (v0, v1) {
  25905. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  25906. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  25907. };
  25908. var result = new Array();
  25909. for (var index = 0; index < vertices.length; index += 3) {
  25910. var v1Out;
  25911. var v2Out;
  25912. var v3Out;
  25913. var total = 0;
  25914. var nV1, nV2, nV3, nV4;
  25915. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  25916. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  25917. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  25918. v1Out = d1 > 0;
  25919. v2Out = d2 > 0;
  25920. v3Out = d3 > 0;
  25921. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  25922. switch (total) {
  25923. case 0:
  25924. result.push(vertices[index]);
  25925. result.push(vertices[index + 1]);
  25926. result.push(vertices[index + 2]);
  25927. break;
  25928. case 1:
  25929. if (v1Out) {
  25930. nV1 = vertices[index + 1];
  25931. nV2 = vertices[index + 2];
  25932. nV3 = clipVertices(vertices[index], nV1);
  25933. nV4 = clipVertices(vertices[index], nV2);
  25934. }
  25935. if (v2Out) {
  25936. nV1 = vertices[index];
  25937. nV2 = vertices[index + 2];
  25938. nV3 = clipVertices(vertices[index + 1], nV1);
  25939. nV4 = clipVertices(vertices[index + 1], nV2);
  25940. result.push(nV3);
  25941. result.push(nV2.clone());
  25942. result.push(nV1.clone());
  25943. result.push(nV2.clone());
  25944. result.push(nV3.clone());
  25945. result.push(nV4);
  25946. break;
  25947. }
  25948. if (v3Out) {
  25949. nV1 = vertices[index];
  25950. nV2 = vertices[index + 1];
  25951. nV3 = clipVertices(vertices[index + 2], nV1);
  25952. nV4 = clipVertices(vertices[index + 2], nV2);
  25953. }
  25954. result.push(nV1.clone());
  25955. result.push(nV2.clone());
  25956. result.push(nV3);
  25957. result.push(nV4);
  25958. result.push(nV3.clone());
  25959. result.push(nV2.clone());
  25960. break;
  25961. case 2:
  25962. if (!v1Out) {
  25963. nV1 = vertices[index].clone();
  25964. nV2 = clipVertices(nV1, vertices[index + 1]);
  25965. nV3 = clipVertices(nV1, vertices[index + 2]);
  25966. result.push(nV1);
  25967. result.push(nV2);
  25968. result.push(nV3);
  25969. }
  25970. if (!v2Out) {
  25971. nV1 = vertices[index + 1].clone();
  25972. nV2 = clipVertices(nV1, vertices[index + 2]);
  25973. nV3 = clipVertices(nV1, vertices[index]);
  25974. result.push(nV1);
  25975. result.push(nV2);
  25976. result.push(nV3);
  25977. }
  25978. if (!v3Out) {
  25979. nV1 = vertices[index + 2].clone();
  25980. nV2 = clipVertices(nV1, vertices[index]);
  25981. nV3 = clipVertices(nV1, vertices[index + 1]);
  25982. result.push(nV1);
  25983. result.push(nV2);
  25984. result.push(nV3);
  25985. }
  25986. break;
  25987. case 3:
  25988. break;
  25989. }
  25990. }
  25991. return result;
  25992. };
  25993. for (var index = 0; index < indices.length; index += 3) {
  25994. var faceVertices = new Array();
  25995. faceVertices.push(extractDecalVector3(index));
  25996. faceVertices.push(extractDecalVector3(index + 1));
  25997. faceVertices.push(extractDecalVector3(index + 2));
  25998. // Clip
  25999. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  26000. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  26001. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  26002. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  26003. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  26004. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  26005. if (faceVertices.length === 0) {
  26006. continue;
  26007. }
  26008. // Add UVs and get back to world
  26009. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  26010. var vertex = faceVertices[vIndex];
  26011. //TODO check for Int32Array | Uint32Array | Uint16Array
  26012. vertexData.indices.push(currentVertexDataIndex);
  26013. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  26014. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  26015. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  26016. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  26017. currentVertexDataIndex++;
  26018. }
  26019. }
  26020. // Return mesh
  26021. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  26022. vertexData.applyToMesh(decal);
  26023. decal.position = position.clone();
  26024. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  26025. return decal;
  26026. };
  26027. // Privates
  26028. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  26029. // extrusion geometry
  26030. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  26031. var tangents = path3D.getTangents();
  26032. var normals = path3D.getNormals();
  26033. var binormals = path3D.getBinormals();
  26034. var distances = path3D.getDistances();
  26035. var angle = 0;
  26036. var returnScale = function () { return scale; };
  26037. var returnRotation = function () { return rotation; };
  26038. var rotate = custom ? rotateFunction : returnRotation;
  26039. var scl = custom ? scaleFunction : returnScale;
  26040. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  26041. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  26042. for (var i = 0; i < curve.length; i++) {
  26043. var shapePath = new Array();
  26044. var angleStep = rotate(i, distances[i]);
  26045. var scaleRatio = scl(i, distances[i]);
  26046. for (var p = 0; p < shape.length; p++) {
  26047. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  26048. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  26049. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  26050. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  26051. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  26052. shapePath[p] = rotated;
  26053. }
  26054. shapePaths[index] = shapePath;
  26055. angle += angleStep;
  26056. index++;
  26057. }
  26058. // cap
  26059. var capPath = function (shapePath) {
  26060. var pointCap = Array();
  26061. var barycenter = BABYLON.Vector3.Zero();
  26062. var i;
  26063. for (i = 0; i < shapePath.length; i++) {
  26064. barycenter.addInPlace(shapePath[i]);
  26065. }
  26066. barycenter.scaleInPlace(1.0 / shapePath.length);
  26067. for (i = 0; i < shapePath.length; i++) {
  26068. pointCap.push(barycenter);
  26069. }
  26070. return pointCap;
  26071. };
  26072. switch (cap) {
  26073. case BABYLON.Mesh.NO_CAP:
  26074. break;
  26075. case BABYLON.Mesh.CAP_START:
  26076. shapePaths[0] = capPath(shapePaths[2]);
  26077. shapePaths[1] = shapePaths[2];
  26078. break;
  26079. case BABYLON.Mesh.CAP_END:
  26080. shapePaths[index] = shapePaths[index - 1];
  26081. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  26082. break;
  26083. case BABYLON.Mesh.CAP_ALL:
  26084. shapePaths[0] = capPath(shapePaths[2]);
  26085. shapePaths[1] = shapePaths[2];
  26086. shapePaths[index] = shapePaths[index - 1];
  26087. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  26088. break;
  26089. default:
  26090. break;
  26091. }
  26092. return shapePaths;
  26093. };
  26094. var path3D;
  26095. var pathArray;
  26096. if (instance) {
  26097. path3D = (instance.path3D).update(curve);
  26098. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  26099. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  26100. return instance;
  26101. }
  26102. // extruded shape creation
  26103. path3D = new BABYLON.Path3D(curve);
  26104. var newShapePaths = new Array();
  26105. cap = (cap < 0 || cap > 3) ? 0 : cap;
  26106. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  26107. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  26108. extrudedGeneric.pathArray = pathArray;
  26109. extrudedGeneric.path3D = path3D;
  26110. extrudedGeneric.cap = cap;
  26111. return extrudedGeneric;
  26112. };
  26113. return MeshBuilder;
  26114. }());
  26115. BABYLON.MeshBuilder = MeshBuilder;
  26116. })(BABYLON || (BABYLON = {}));
  26117. //# sourceMappingURL=babylon.meshBuilder.js.map
  26118. var BABYLON;
  26119. (function (BABYLON) {
  26120. var BaseTexture = (function () {
  26121. function BaseTexture(scene) {
  26122. this.hasAlpha = false;
  26123. this.getAlphaFromRGB = false;
  26124. this.level = 1;
  26125. this.coordinatesIndex = 0;
  26126. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26127. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26128. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26129. this.anisotropicFilteringLevel = 4;
  26130. this.isCube = false;
  26131. this.isRenderTarget = false;
  26132. this.animations = new Array();
  26133. /**
  26134. * An event triggered when the texture is disposed.
  26135. * @type {BABYLON.Observable}
  26136. */
  26137. this.onDisposeObservable = new BABYLON.Observable();
  26138. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26139. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26140. this._scene.textures.push(this);
  26141. this._uid = null;
  26142. }
  26143. Object.defineProperty(BaseTexture.prototype, "uid", {
  26144. get: function () {
  26145. if (!this._uid) {
  26146. this._uid = BABYLON.Tools.RandomId();
  26147. }
  26148. return this._uid;
  26149. },
  26150. enumerable: true,
  26151. configurable: true
  26152. });
  26153. BaseTexture.prototype.toString = function () {
  26154. return this.name;
  26155. };
  26156. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26157. set: function (callback) {
  26158. if (this._onDisposeObserver) {
  26159. this.onDisposeObservable.remove(this._onDisposeObserver);
  26160. }
  26161. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26162. },
  26163. enumerable: true,
  26164. configurable: true
  26165. });
  26166. BaseTexture.prototype.getScene = function () {
  26167. return this._scene;
  26168. };
  26169. BaseTexture.prototype.getTextureMatrix = function () {
  26170. return null;
  26171. };
  26172. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26173. return null;
  26174. };
  26175. BaseTexture.prototype.getInternalTexture = function () {
  26176. return this._texture;
  26177. };
  26178. BaseTexture.prototype.isReady = function () {
  26179. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26180. return true;
  26181. }
  26182. if (this._texture) {
  26183. return this._texture.isReady;
  26184. }
  26185. return false;
  26186. };
  26187. BaseTexture.prototype.getSize = function () {
  26188. if (this._texture._width) {
  26189. return new BABYLON.Size(this._texture._width, this._texture._height);
  26190. }
  26191. if (this._texture._size) {
  26192. return new BABYLON.Size(this._texture._size, this._texture._size);
  26193. }
  26194. return BABYLON.Size.Zero();
  26195. };
  26196. BaseTexture.prototype.getBaseSize = function () {
  26197. if (!this.isReady() || !this._texture)
  26198. return BABYLON.Size.Zero();
  26199. if (this._texture._size) {
  26200. return new BABYLON.Size(this._texture._size, this._texture._size);
  26201. }
  26202. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  26203. };
  26204. BaseTexture.prototype.scale = function (ratio) {
  26205. };
  26206. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26207. get: function () {
  26208. return false;
  26209. },
  26210. enumerable: true,
  26211. configurable: true
  26212. });
  26213. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  26214. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26215. for (var index = 0; index < texturesCache.length; index++) {
  26216. var texturesCacheEntry = texturesCache[index];
  26217. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  26218. texturesCache.splice(index, 1);
  26219. return;
  26220. }
  26221. }
  26222. };
  26223. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26224. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26225. for (var index = 0; index < texturesCache.length; index++) {
  26226. var texturesCacheEntry = texturesCache[index];
  26227. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  26228. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26229. texturesCacheEntry.references++;
  26230. return texturesCacheEntry;
  26231. }
  26232. }
  26233. }
  26234. return null;
  26235. };
  26236. BaseTexture.prototype.delayLoad = function () {
  26237. };
  26238. BaseTexture.prototype.clone = function () {
  26239. return null;
  26240. };
  26241. BaseTexture.prototype.releaseInternalTexture = function () {
  26242. if (this._texture) {
  26243. this._scene.getEngine().releaseInternalTexture(this._texture);
  26244. delete this._texture;
  26245. }
  26246. };
  26247. BaseTexture.prototype.dispose = function () {
  26248. // Animations
  26249. this.getScene().stopAnimation(this);
  26250. // Remove from scene
  26251. this._scene._removePendingData(this);
  26252. var index = this._scene.textures.indexOf(this);
  26253. if (index >= 0) {
  26254. this._scene.textures.splice(index, 1);
  26255. }
  26256. if (this._texture === undefined) {
  26257. return;
  26258. }
  26259. // Release
  26260. this.releaseInternalTexture();
  26261. // Callback
  26262. this.onDisposeObservable.notifyObservers(this);
  26263. this.onDisposeObservable.clear();
  26264. };
  26265. BaseTexture.prototype.serialize = function () {
  26266. if (!this.name) {
  26267. return null;
  26268. }
  26269. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26270. // Animations
  26271. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26272. return serializationObject;
  26273. };
  26274. return BaseTexture;
  26275. }());
  26276. __decorate([
  26277. BABYLON.serialize()
  26278. ], BaseTexture.prototype, "name", void 0);
  26279. __decorate([
  26280. BABYLON.serialize()
  26281. ], BaseTexture.prototype, "hasAlpha", void 0);
  26282. __decorate([
  26283. BABYLON.serialize()
  26284. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26285. __decorate([
  26286. BABYLON.serialize()
  26287. ], BaseTexture.prototype, "level", void 0);
  26288. __decorate([
  26289. BABYLON.serialize()
  26290. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26291. __decorate([
  26292. BABYLON.serialize()
  26293. ], BaseTexture.prototype, "coordinatesMode", void 0);
  26294. __decorate([
  26295. BABYLON.serialize()
  26296. ], BaseTexture.prototype, "wrapU", void 0);
  26297. __decorate([
  26298. BABYLON.serialize()
  26299. ], BaseTexture.prototype, "wrapV", void 0);
  26300. __decorate([
  26301. BABYLON.serialize()
  26302. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26303. __decorate([
  26304. BABYLON.serialize()
  26305. ], BaseTexture.prototype, "isCube", void 0);
  26306. __decorate([
  26307. BABYLON.serialize()
  26308. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26309. BABYLON.BaseTexture = BaseTexture;
  26310. })(BABYLON || (BABYLON = {}));
  26311. //# sourceMappingURL=babylon.baseTexture.js.map
  26312. var BABYLON;
  26313. (function (BABYLON) {
  26314. var Texture = (function (_super) {
  26315. __extends(Texture, _super);
  26316. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26317. if (noMipmap === void 0) { noMipmap = false; }
  26318. if (invertY === void 0) { invertY = true; }
  26319. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26320. if (onLoad === void 0) { onLoad = null; }
  26321. if (onError === void 0) { onError = null; }
  26322. if (buffer === void 0) { buffer = null; }
  26323. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26324. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26325. var _this = _super.call(this, scene) || this;
  26326. _this.uOffset = 0;
  26327. _this.vOffset = 0;
  26328. _this.uScale = 1.0;
  26329. _this.vScale = 1.0;
  26330. _this.uAng = 0;
  26331. _this.vAng = 0;
  26332. _this.wAng = 0;
  26333. _this.name = url;
  26334. _this.url = url;
  26335. _this._noMipmap = noMipmap;
  26336. _this._invertY = invertY;
  26337. _this._samplingMode = samplingMode;
  26338. _this._buffer = buffer;
  26339. _this._deleteBuffer = deleteBuffer;
  26340. _this._format = format;
  26341. if (!url) {
  26342. return _this;
  26343. }
  26344. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  26345. var load = function () {
  26346. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  26347. _this.onLoadObservable.notifyObservers(true);
  26348. }
  26349. if (onLoad) {
  26350. onLoad();
  26351. }
  26352. };
  26353. if (!_this._texture) {
  26354. if (!scene.useDelayedTextureLoading) {
  26355. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  26356. if (deleteBuffer) {
  26357. delete _this._buffer;
  26358. }
  26359. }
  26360. else {
  26361. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26362. _this._delayedOnLoad = load;
  26363. _this._delayedOnError = onError;
  26364. }
  26365. }
  26366. else {
  26367. if (_this._texture.isReady) {
  26368. BABYLON.Tools.SetImmediate(function () { return load(); });
  26369. }
  26370. else {
  26371. _this._texture.onLoadedCallbacks.push(load);
  26372. }
  26373. }
  26374. return _this;
  26375. }
  26376. Object.defineProperty(Texture.prototype, "noMipmap", {
  26377. get: function () {
  26378. return this._noMipmap;
  26379. },
  26380. enumerable: true,
  26381. configurable: true
  26382. });
  26383. Texture.prototype.delayLoad = function () {
  26384. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26385. return;
  26386. }
  26387. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26388. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26389. if (!this._texture) {
  26390. 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);
  26391. if (this._deleteBuffer) {
  26392. delete this._buffer;
  26393. }
  26394. }
  26395. };
  26396. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26397. if (!this._texture) {
  26398. return;
  26399. }
  26400. this._samplingMode = samplingMode;
  26401. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26402. };
  26403. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26404. x *= this.uScale;
  26405. y *= this.vScale;
  26406. x -= 0.5 * this.uScale;
  26407. y -= 0.5 * this.vScale;
  26408. z -= 0.5;
  26409. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26410. t.x += 0.5 * this.uScale + this.uOffset;
  26411. t.y += 0.5 * this.vScale + this.vOffset;
  26412. t.z += 0.5;
  26413. };
  26414. Texture.prototype.getTextureMatrix = function () {
  26415. if (this.uOffset === this._cachedUOffset &&
  26416. this.vOffset === this._cachedVOffset &&
  26417. this.uScale === this._cachedUScale &&
  26418. this.vScale === this._cachedVScale &&
  26419. this.uAng === this._cachedUAng &&
  26420. this.vAng === this._cachedVAng &&
  26421. this.wAng === this._cachedWAng) {
  26422. return this._cachedTextureMatrix;
  26423. }
  26424. this._cachedUOffset = this.uOffset;
  26425. this._cachedVOffset = this.vOffset;
  26426. this._cachedUScale = this.uScale;
  26427. this._cachedVScale = this.vScale;
  26428. this._cachedUAng = this.uAng;
  26429. this._cachedVAng = this.vAng;
  26430. this._cachedWAng = this.wAng;
  26431. if (!this._cachedTextureMatrix) {
  26432. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26433. this._rowGenerationMatrix = new BABYLON.Matrix();
  26434. this._t0 = BABYLON.Vector3.Zero();
  26435. this._t1 = BABYLON.Vector3.Zero();
  26436. this._t2 = BABYLON.Vector3.Zero();
  26437. }
  26438. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26439. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26440. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26441. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26442. this._t1.subtractInPlace(this._t0);
  26443. this._t2.subtractInPlace(this._t0);
  26444. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26445. this._cachedTextureMatrix.m[0] = this._t1.x;
  26446. this._cachedTextureMatrix.m[1] = this._t1.y;
  26447. this._cachedTextureMatrix.m[2] = this._t1.z;
  26448. this._cachedTextureMatrix.m[4] = this._t2.x;
  26449. this._cachedTextureMatrix.m[5] = this._t2.y;
  26450. this._cachedTextureMatrix.m[6] = this._t2.z;
  26451. this._cachedTextureMatrix.m[8] = this._t0.x;
  26452. this._cachedTextureMatrix.m[9] = this._t0.y;
  26453. this._cachedTextureMatrix.m[10] = this._t0.z;
  26454. return this._cachedTextureMatrix;
  26455. };
  26456. Texture.prototype.getReflectionTextureMatrix = function () {
  26457. if (this.uOffset === this._cachedUOffset &&
  26458. this.vOffset === this._cachedVOffset &&
  26459. this.uScale === this._cachedUScale &&
  26460. this.vScale === this._cachedVScale &&
  26461. this.coordinatesMode === this._cachedCoordinatesMode) {
  26462. return this._cachedTextureMatrix;
  26463. }
  26464. if (!this._cachedTextureMatrix) {
  26465. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26466. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26467. }
  26468. this._cachedCoordinatesMode = this.coordinatesMode;
  26469. switch (this.coordinatesMode) {
  26470. case Texture.PLANAR_MODE:
  26471. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26472. this._cachedTextureMatrix[0] = this.uScale;
  26473. this._cachedTextureMatrix[5] = this.vScale;
  26474. this._cachedTextureMatrix[12] = this.uOffset;
  26475. this._cachedTextureMatrix[13] = this.vOffset;
  26476. break;
  26477. case Texture.PROJECTION_MODE:
  26478. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26479. this._projectionModeMatrix.m[0] = 0.5;
  26480. this._projectionModeMatrix.m[5] = -0.5;
  26481. this._projectionModeMatrix.m[10] = 0.0;
  26482. this._projectionModeMatrix.m[12] = 0.5;
  26483. this._projectionModeMatrix.m[13] = 0.5;
  26484. this._projectionModeMatrix.m[14] = 1.0;
  26485. this._projectionModeMatrix.m[15] = 1.0;
  26486. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26487. break;
  26488. default:
  26489. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26490. break;
  26491. }
  26492. return this._cachedTextureMatrix;
  26493. };
  26494. Texture.prototype.clone = function () {
  26495. var _this = this;
  26496. return BABYLON.SerializationHelper.Clone(function () {
  26497. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26498. }, this);
  26499. };
  26500. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26501. get: function () {
  26502. if (!this._onLoadObservarble) {
  26503. this._onLoadObservarble = new BABYLON.Observable();
  26504. }
  26505. return this._onLoadObservarble;
  26506. },
  26507. enumerable: true,
  26508. configurable: true
  26509. });
  26510. // Statics
  26511. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26512. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26513. if (onLoad === void 0) { onLoad = null; }
  26514. if (onError === void 0) { onError = null; }
  26515. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26516. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26517. };
  26518. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26519. if (parsedTexture.customType) {
  26520. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26521. return customTexture.Parse(parsedTexture, scene, rootUrl);
  26522. }
  26523. if (parsedTexture.isCube) {
  26524. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26525. }
  26526. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26527. return null;
  26528. }
  26529. var texture = BABYLON.SerializationHelper.Parse(function () {
  26530. if (parsedTexture.mirrorPlane) {
  26531. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  26532. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26533. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26534. return mirrorTexture;
  26535. }
  26536. else if (parsedTexture.isRenderTarget) {
  26537. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  26538. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26539. return renderTargetTexture;
  26540. }
  26541. else {
  26542. var texture;
  26543. if (parsedTexture.base64String) {
  26544. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  26545. }
  26546. else {
  26547. texture = new Texture(rootUrl + parsedTexture.name, scene);
  26548. }
  26549. return texture;
  26550. }
  26551. }, parsedTexture, scene);
  26552. // Animations
  26553. if (parsedTexture.animations) {
  26554. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26555. var parsedAnimation = parsedTexture.animations[animationIndex];
  26556. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26557. }
  26558. }
  26559. return texture;
  26560. };
  26561. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26562. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26563. if (noMipmap === void 0) { noMipmap = false; }
  26564. if (invertY === void 0) { invertY = true; }
  26565. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26566. if (onLoad === void 0) { onLoad = null; }
  26567. if (onError === void 0) { onError = null; }
  26568. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26569. if (name.substr(0, 5) !== "data:") {
  26570. name = "data:" + name;
  26571. }
  26572. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26573. };
  26574. return Texture;
  26575. }(BABYLON.BaseTexture));
  26576. // Constants
  26577. Texture.NEAREST_SAMPLINGMODE = 1;
  26578. Texture.BILINEAR_SAMPLINGMODE = 2;
  26579. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26580. Texture.EXPLICIT_MODE = 0;
  26581. Texture.SPHERICAL_MODE = 1;
  26582. Texture.PLANAR_MODE = 2;
  26583. Texture.CUBIC_MODE = 3;
  26584. Texture.PROJECTION_MODE = 4;
  26585. Texture.SKYBOX_MODE = 5;
  26586. Texture.INVCUBIC_MODE = 6;
  26587. Texture.EQUIRECTANGULAR_MODE = 7;
  26588. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26589. Texture.CLAMP_ADDRESSMODE = 0;
  26590. Texture.WRAP_ADDRESSMODE = 1;
  26591. Texture.MIRROR_ADDRESSMODE = 2;
  26592. __decorate([
  26593. BABYLON.serialize()
  26594. ], Texture.prototype, "url", void 0);
  26595. __decorate([
  26596. BABYLON.serialize()
  26597. ], Texture.prototype, "uOffset", void 0);
  26598. __decorate([
  26599. BABYLON.serialize()
  26600. ], Texture.prototype, "vOffset", void 0);
  26601. __decorate([
  26602. BABYLON.serialize()
  26603. ], Texture.prototype, "uScale", void 0);
  26604. __decorate([
  26605. BABYLON.serialize()
  26606. ], Texture.prototype, "vScale", void 0);
  26607. __decorate([
  26608. BABYLON.serialize()
  26609. ], Texture.prototype, "uAng", void 0);
  26610. __decorate([
  26611. BABYLON.serialize()
  26612. ], Texture.prototype, "vAng", void 0);
  26613. __decorate([
  26614. BABYLON.serialize()
  26615. ], Texture.prototype, "wAng", void 0);
  26616. BABYLON.Texture = Texture;
  26617. })(BABYLON || (BABYLON = {}));
  26618. //# sourceMappingURL=babylon.texture.js.map
  26619. var BABYLON;
  26620. (function (BABYLON) {
  26621. var CubeTexture = (function (_super) {
  26622. __extends(CubeTexture, _super);
  26623. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  26624. if (onLoad === void 0) { onLoad = null; }
  26625. if (onError === void 0) { onError = null; }
  26626. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26627. var _this = _super.call(this, scene) || this;
  26628. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  26629. _this.name = rootUrl;
  26630. _this.url = rootUrl;
  26631. _this._noMipmap = noMipmap;
  26632. _this.hasAlpha = false;
  26633. _this._format = format;
  26634. if (!rootUrl && !files) {
  26635. return _this;
  26636. }
  26637. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  26638. if (!files) {
  26639. if (!extensions) {
  26640. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  26641. }
  26642. files = [];
  26643. for (var index = 0; index < extensions.length; index++) {
  26644. files.push(rootUrl + extensions[index]);
  26645. }
  26646. _this._extensions = extensions;
  26647. }
  26648. _this._files = files;
  26649. if (!_this._texture) {
  26650. if (!scene.useDelayedTextureLoading) {
  26651. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  26652. }
  26653. else {
  26654. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26655. }
  26656. }
  26657. else if (onLoad) {
  26658. if (_this._texture.isReady) {
  26659. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  26660. }
  26661. else {
  26662. _this._texture.onLoadedCallbacks.push(onLoad);
  26663. }
  26664. }
  26665. _this.isCube = true;
  26666. _this._textureMatrix = BABYLON.Matrix.Identity();
  26667. return _this;
  26668. }
  26669. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  26670. return new CubeTexture("", scene, null, noMipmap, files);
  26671. };
  26672. // Methods
  26673. CubeTexture.prototype.delayLoad = function () {
  26674. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26675. return;
  26676. }
  26677. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26678. this._texture = this._getFromCache(this.url, this._noMipmap);
  26679. if (!this._texture) {
  26680. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  26681. }
  26682. };
  26683. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  26684. return this._textureMatrix;
  26685. };
  26686. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  26687. var texture = BABYLON.SerializationHelper.Parse(function () {
  26688. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  26689. }, parsedTexture, scene);
  26690. // Animations
  26691. if (parsedTexture.animations) {
  26692. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26693. var parsedAnimation = parsedTexture.animations[animationIndex];
  26694. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26695. }
  26696. }
  26697. return texture;
  26698. };
  26699. CubeTexture.prototype.clone = function () {
  26700. var _this = this;
  26701. return BABYLON.SerializationHelper.Clone(function () {
  26702. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  26703. }, this);
  26704. };
  26705. return CubeTexture;
  26706. }(BABYLON.BaseTexture));
  26707. BABYLON.CubeTexture = CubeTexture;
  26708. })(BABYLON || (BABYLON = {}));
  26709. //# sourceMappingURL=babylon.cubeTexture.js.map
  26710. var BABYLON;
  26711. (function (BABYLON) {
  26712. var RenderTargetTexture = (function (_super) {
  26713. __extends(RenderTargetTexture, _super);
  26714. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  26715. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  26716. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  26717. if (isCube === void 0) { isCube = false; }
  26718. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26719. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  26720. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  26721. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  26722. _this.isCube = isCube;
  26723. /**
  26724. * Use this list to define the list of mesh you want to render.
  26725. */
  26726. _this.renderList = new Array();
  26727. _this.renderParticles = true;
  26728. _this.renderSprites = false;
  26729. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  26730. // Events
  26731. /**
  26732. * An event triggered when the texture is unbind.
  26733. * @type {BABYLON.Observable}
  26734. */
  26735. _this.onAfterUnbindObservable = new BABYLON.Observable();
  26736. /**
  26737. * An event triggered before rendering the texture
  26738. * @type {BABYLON.Observable}
  26739. */
  26740. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26741. /**
  26742. * An event triggered after rendering the texture
  26743. * @type {BABYLON.Observable}
  26744. */
  26745. _this.onAfterRenderObservable = new BABYLON.Observable();
  26746. /**
  26747. * An event triggered after the texture clear
  26748. * @type {BABYLON.Observable}
  26749. */
  26750. _this.onClearObservable = new BABYLON.Observable();
  26751. _this._currentRefreshId = -1;
  26752. _this._refreshRate = 1;
  26753. _this.name = name;
  26754. _this.isRenderTarget = true;
  26755. _this._size = size;
  26756. _this._generateMipMaps = generateMipMaps;
  26757. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  26758. _this._renderTargetOptions = {
  26759. generateMipMaps: generateMipMaps,
  26760. type: type,
  26761. samplingMode: samplingMode,
  26762. generateDepthBuffer: generateDepthBuffer,
  26763. generateStencilBuffer: generateStencilBuffer
  26764. };
  26765. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  26766. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26767. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26768. }
  26769. if (isCube) {
  26770. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  26771. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  26772. _this._textureMatrix = BABYLON.Matrix.Identity();
  26773. }
  26774. else {
  26775. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  26776. }
  26777. // Rendering groups
  26778. _this._renderingManager = new BABYLON.RenderingManager(scene);
  26779. return _this;
  26780. }
  26781. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  26782. get: function () {
  26783. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  26784. },
  26785. enumerable: true,
  26786. configurable: true
  26787. });
  26788. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  26789. get: function () {
  26790. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  26791. },
  26792. enumerable: true,
  26793. configurable: true
  26794. });
  26795. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  26796. get: function () {
  26797. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  26798. },
  26799. enumerable: true,
  26800. configurable: true
  26801. });
  26802. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  26803. set: function (callback) {
  26804. if (this._onAfterUnbindObserver) {
  26805. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  26806. }
  26807. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  26808. },
  26809. enumerable: true,
  26810. configurable: true
  26811. });
  26812. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  26813. set: function (callback) {
  26814. if (this._onBeforeRenderObserver) {
  26815. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  26816. }
  26817. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  26818. },
  26819. enumerable: true,
  26820. configurable: true
  26821. });
  26822. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  26823. set: function (callback) {
  26824. if (this._onAfterRenderObserver) {
  26825. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  26826. }
  26827. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  26828. },
  26829. enumerable: true,
  26830. configurable: true
  26831. });
  26832. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  26833. set: function (callback) {
  26834. if (this._onClearObserver) {
  26835. this.onClearObservable.remove(this._onClearObserver);
  26836. }
  26837. this._onClearObserver = this.onClearObservable.add(callback);
  26838. },
  26839. enumerable: true,
  26840. configurable: true
  26841. });
  26842. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  26843. this._currentRefreshId = -1;
  26844. };
  26845. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  26846. get: function () {
  26847. return this._refreshRate;
  26848. },
  26849. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  26850. set: function (value) {
  26851. this._refreshRate = value;
  26852. this.resetRefreshCounter();
  26853. },
  26854. enumerable: true,
  26855. configurable: true
  26856. });
  26857. RenderTargetTexture.prototype._shouldRender = function () {
  26858. if (this._currentRefreshId === -1) {
  26859. this._currentRefreshId = 1;
  26860. return true;
  26861. }
  26862. if (this.refreshRate === this._currentRefreshId) {
  26863. this._currentRefreshId = 1;
  26864. return true;
  26865. }
  26866. this._currentRefreshId++;
  26867. return false;
  26868. };
  26869. RenderTargetTexture.prototype.isReady = function () {
  26870. if (!this.getScene().renderTargetsEnabled) {
  26871. return false;
  26872. }
  26873. return _super.prototype.isReady.call(this);
  26874. };
  26875. RenderTargetTexture.prototype.getRenderSize = function () {
  26876. return this._size;
  26877. };
  26878. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  26879. get: function () {
  26880. return true;
  26881. },
  26882. enumerable: true,
  26883. configurable: true
  26884. });
  26885. RenderTargetTexture.prototype.scale = function (ratio) {
  26886. var newSize = this._size * ratio;
  26887. this.resize(newSize);
  26888. };
  26889. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  26890. if (this.isCube) {
  26891. return this._textureMatrix;
  26892. }
  26893. return _super.prototype.getReflectionTextureMatrix.call(this);
  26894. };
  26895. RenderTargetTexture.prototype.resize = function (size) {
  26896. this.releaseInternalTexture();
  26897. if (this.isCube) {
  26898. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  26899. }
  26900. else {
  26901. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  26902. }
  26903. };
  26904. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  26905. var scene = this.getScene();
  26906. var engine = scene.getEngine();
  26907. if (this.useCameraPostProcesses !== undefined) {
  26908. useCameraPostProcess = this.useCameraPostProcesses;
  26909. }
  26910. if (this._waitingRenderList) {
  26911. this.renderList = [];
  26912. for (var index = 0; index < this._waitingRenderList.length; index++) {
  26913. var id = this._waitingRenderList[index];
  26914. this.renderList.push(scene.getMeshByID(id));
  26915. }
  26916. delete this._waitingRenderList;
  26917. }
  26918. // Is predicate defined?
  26919. if (this.renderListPredicate) {
  26920. this.renderList.splice(0); // Clear previous renderList
  26921. var sceneMeshes = this.getScene().meshes;
  26922. for (var index = 0; index < sceneMeshes.length; index++) {
  26923. var mesh = sceneMeshes[index];
  26924. if (this.renderListPredicate(mesh)) {
  26925. this.renderList.push(mesh);
  26926. }
  26927. }
  26928. }
  26929. if (this.renderList && this.renderList.length === 0) {
  26930. return;
  26931. }
  26932. // Set custom projection.
  26933. // Needs to be before binding to prevent changing the aspect ratio.
  26934. if (this.activeCamera) {
  26935. engine.setViewport(this.activeCamera.viewport);
  26936. if (this.activeCamera !== scene.activeCamera) {
  26937. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  26938. }
  26939. }
  26940. else {
  26941. engine.setViewport(scene.activeCamera.viewport);
  26942. }
  26943. // Prepare renderingManager
  26944. this._renderingManager.reset();
  26945. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  26946. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  26947. var sceneRenderId = scene.getRenderId();
  26948. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  26949. var mesh = currentRenderList[meshIndex];
  26950. if (mesh) {
  26951. if (!mesh.isReady()) {
  26952. // Reset _currentRefreshId
  26953. this.resetRefreshCounter();
  26954. continue;
  26955. }
  26956. mesh._preActivateForIntermediateRendering(sceneRenderId);
  26957. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  26958. mesh._activate(sceneRenderId);
  26959. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26960. var subMesh = mesh.subMeshes[subIndex];
  26961. scene._activeIndices.addCount(subMesh.indexCount, false);
  26962. this._renderingManager.dispatch(subMesh);
  26963. }
  26964. }
  26965. }
  26966. }
  26967. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  26968. var particleSystem = scene.particleSystems[particleIndex];
  26969. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  26970. continue;
  26971. }
  26972. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  26973. this._renderingManager.dispatchParticles(particleSystem);
  26974. }
  26975. }
  26976. if (this.isCube) {
  26977. for (var face = 0; face < 6; face++) {
  26978. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  26979. scene.incrementRenderId();
  26980. scene.resetCachedMaterial();
  26981. }
  26982. }
  26983. else {
  26984. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  26985. }
  26986. this.onAfterUnbindObservable.notifyObservers(this);
  26987. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  26988. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  26989. }
  26990. engine.setViewport(scene.activeCamera.viewport);
  26991. scene.resetCachedMaterial();
  26992. };
  26993. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  26994. var scene = this.getScene();
  26995. var engine = scene.getEngine();
  26996. // Bind
  26997. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  26998. if (this.isCube) {
  26999. engine.bindFramebuffer(this._texture, faceIndex);
  27000. }
  27001. else {
  27002. engine.bindFramebuffer(this._texture);
  27003. }
  27004. }
  27005. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  27006. // Clear
  27007. if (this.onClearObservable.hasObservers()) {
  27008. this.onClearObservable.notifyObservers(engine);
  27009. }
  27010. else {
  27011. engine.clear(scene.clearColor, true, true, true);
  27012. }
  27013. if (!this._doNotChangeAspectRatio) {
  27014. scene.updateTransformMatrix(true);
  27015. }
  27016. // Render
  27017. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  27018. if (useCameraPostProcess) {
  27019. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  27020. }
  27021. if (!this._doNotChangeAspectRatio) {
  27022. scene.updateTransformMatrix(true);
  27023. }
  27024. this.onAfterRenderObservable.notifyObservers(faceIndex);
  27025. // Dump ?
  27026. if (dumpForDebug) {
  27027. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  27028. }
  27029. // Unbind
  27030. if (!this.isCube || faceIndex === 5) {
  27031. if (this.isCube) {
  27032. if (faceIndex === 5) {
  27033. engine.generateMipMapsForCubemap(this._texture);
  27034. }
  27035. }
  27036. engine.unBindFramebuffer(this._texture, this.isCube);
  27037. }
  27038. };
  27039. /**
  27040. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  27041. * This allowed control for front to back rendering or reversly depending of the special needs.
  27042. *
  27043. * @param renderingGroupId The rendering group id corresponding to its index
  27044. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  27045. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  27046. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  27047. */
  27048. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  27049. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  27050. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  27051. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  27052. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  27053. };
  27054. /**
  27055. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  27056. *
  27057. * @param renderingGroupId The rendering group id corresponding to its index
  27058. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  27059. */
  27060. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  27061. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  27062. };
  27063. RenderTargetTexture.prototype.clone = function () {
  27064. var textureSize = this.getSize();
  27065. 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);
  27066. // Base texture
  27067. newTexture.hasAlpha = this.hasAlpha;
  27068. newTexture.level = this.level;
  27069. // RenderTarget Texture
  27070. newTexture.coordinatesMode = this.coordinatesMode;
  27071. newTexture.renderList = this.renderList.slice(0);
  27072. return newTexture;
  27073. };
  27074. RenderTargetTexture.prototype.serialize = function () {
  27075. if (!this.name) {
  27076. return null;
  27077. }
  27078. var serializationObject = _super.prototype.serialize.call(this);
  27079. serializationObject.renderTargetSize = this.getRenderSize();
  27080. serializationObject.renderList = [];
  27081. for (var index = 0; index < this.renderList.length; index++) {
  27082. serializationObject.renderList.push(this.renderList[index].id);
  27083. }
  27084. return serializationObject;
  27085. };
  27086. return RenderTargetTexture;
  27087. }(BABYLON.Texture));
  27088. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  27089. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  27090. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  27091. BABYLON.RenderTargetTexture = RenderTargetTexture;
  27092. })(BABYLON || (BABYLON = {}));
  27093. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  27094. var BABYLON;
  27095. (function (BABYLON) {
  27096. var ProceduralTexture = (function (_super) {
  27097. __extends(ProceduralTexture, _super);
  27098. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  27099. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27100. if (isCube === void 0) { isCube = false; }
  27101. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  27102. _this.isCube = isCube;
  27103. _this.isEnabled = true;
  27104. _this._currentRefreshId = -1;
  27105. _this._refreshRate = 1;
  27106. _this._vertexBuffers = {};
  27107. _this._uniforms = new Array();
  27108. _this._samplers = new Array();
  27109. _this._textures = new Array();
  27110. _this._floats = new Array();
  27111. _this._floatsArrays = {};
  27112. _this._colors3 = new Array();
  27113. _this._colors4 = new Array();
  27114. _this._vectors2 = new Array();
  27115. _this._vectors3 = new Array();
  27116. _this._matrices = new Array();
  27117. _this._fallbackTextureUsed = false;
  27118. scene._proceduralTextures.push(_this);
  27119. _this.name = name;
  27120. _this.isRenderTarget = true;
  27121. _this._size = size;
  27122. _this._generateMipMaps = generateMipMaps;
  27123. _this.setFragment(fragment);
  27124. _this._fallbackTexture = fallbackTexture;
  27125. var engine = scene.getEngine();
  27126. if (isCube) {
  27127. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  27128. _this.setFloat("face", 0);
  27129. }
  27130. else {
  27131. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  27132. }
  27133. // VBO
  27134. var vertices = [];
  27135. vertices.push(1, 1);
  27136. vertices.push(-1, 1);
  27137. vertices.push(-1, -1);
  27138. vertices.push(1, -1);
  27139. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27140. // Indices
  27141. var indices = [];
  27142. indices.push(0);
  27143. indices.push(1);
  27144. indices.push(2);
  27145. indices.push(0);
  27146. indices.push(2);
  27147. indices.push(3);
  27148. _this._indexBuffer = engine.createIndexBuffer(indices);
  27149. return _this;
  27150. }
  27151. ProceduralTexture.prototype.reset = function () {
  27152. if (this._effect === undefined) {
  27153. return;
  27154. }
  27155. var engine = this.getScene().getEngine();
  27156. engine._releaseEffect(this._effect);
  27157. };
  27158. ProceduralTexture.prototype.isReady = function () {
  27159. var _this = this;
  27160. var engine = this.getScene().getEngine();
  27161. var shaders;
  27162. if (!this._fragment) {
  27163. return false;
  27164. }
  27165. if (this._fallbackTextureUsed) {
  27166. return true;
  27167. }
  27168. if (this._fragment.fragmentElement !== undefined) {
  27169. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  27170. }
  27171. else {
  27172. shaders = { vertex: "procedural", fragment: this._fragment };
  27173. }
  27174. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  27175. _this.releaseInternalTexture();
  27176. if (_this._fallbackTexture) {
  27177. _this._texture = _this._fallbackTexture._texture;
  27178. _this._texture.references++;
  27179. }
  27180. _this._fallbackTextureUsed = true;
  27181. });
  27182. return this._effect.isReady();
  27183. };
  27184. ProceduralTexture.prototype.resetRefreshCounter = function () {
  27185. this._currentRefreshId = -1;
  27186. };
  27187. ProceduralTexture.prototype.setFragment = function (fragment) {
  27188. this._fragment = fragment;
  27189. };
  27190. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  27191. get: function () {
  27192. return this._refreshRate;
  27193. },
  27194. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  27195. set: function (value) {
  27196. this._refreshRate = value;
  27197. this.resetRefreshCounter();
  27198. },
  27199. enumerable: true,
  27200. configurable: true
  27201. });
  27202. ProceduralTexture.prototype._shouldRender = function () {
  27203. if (!this.isEnabled || !this.isReady() || !this._texture) {
  27204. return false;
  27205. }
  27206. if (this._fallbackTextureUsed) {
  27207. return false;
  27208. }
  27209. if (this._currentRefreshId === -1) {
  27210. this._currentRefreshId = 1;
  27211. return true;
  27212. }
  27213. if (this.refreshRate === this._currentRefreshId) {
  27214. this._currentRefreshId = 1;
  27215. return true;
  27216. }
  27217. this._currentRefreshId++;
  27218. return false;
  27219. };
  27220. ProceduralTexture.prototype.getRenderSize = function () {
  27221. return this._size;
  27222. };
  27223. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  27224. if (this._fallbackTextureUsed) {
  27225. return;
  27226. }
  27227. this.releaseInternalTexture();
  27228. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  27229. };
  27230. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  27231. if (this._uniforms.indexOf(uniformName) === -1) {
  27232. this._uniforms.push(uniformName);
  27233. }
  27234. };
  27235. ProceduralTexture.prototype.setTexture = function (name, texture) {
  27236. if (this._samplers.indexOf(name) === -1) {
  27237. this._samplers.push(name);
  27238. }
  27239. this._textures[name] = texture;
  27240. return this;
  27241. };
  27242. ProceduralTexture.prototype.setFloat = function (name, value) {
  27243. this._checkUniform(name);
  27244. this._floats[name] = value;
  27245. return this;
  27246. };
  27247. ProceduralTexture.prototype.setFloats = function (name, value) {
  27248. this._checkUniform(name);
  27249. this._floatsArrays[name] = value;
  27250. return this;
  27251. };
  27252. ProceduralTexture.prototype.setColor3 = function (name, value) {
  27253. this._checkUniform(name);
  27254. this._colors3[name] = value;
  27255. return this;
  27256. };
  27257. ProceduralTexture.prototype.setColor4 = function (name, value) {
  27258. this._checkUniform(name);
  27259. this._colors4[name] = value;
  27260. return this;
  27261. };
  27262. ProceduralTexture.prototype.setVector2 = function (name, value) {
  27263. this._checkUniform(name);
  27264. this._vectors2[name] = value;
  27265. return this;
  27266. };
  27267. ProceduralTexture.prototype.setVector3 = function (name, value) {
  27268. this._checkUniform(name);
  27269. this._vectors3[name] = value;
  27270. return this;
  27271. };
  27272. ProceduralTexture.prototype.setMatrix = function (name, value) {
  27273. this._checkUniform(name);
  27274. this._matrices[name] = value;
  27275. return this;
  27276. };
  27277. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  27278. var scene = this.getScene();
  27279. var engine = scene.getEngine();
  27280. // Render
  27281. engine.enableEffect(this._effect);
  27282. engine.setState(false);
  27283. // Texture
  27284. for (var name in this._textures) {
  27285. this._effect.setTexture(name, this._textures[name]);
  27286. }
  27287. // Float
  27288. for (name in this._floats) {
  27289. this._effect.setFloat(name, this._floats[name]);
  27290. }
  27291. // Floats
  27292. for (name in this._floatsArrays) {
  27293. this._effect.setArray(name, this._floatsArrays[name]);
  27294. }
  27295. // Color3
  27296. for (name in this._colors3) {
  27297. this._effect.setColor3(name, this._colors3[name]);
  27298. }
  27299. // Color4
  27300. for (name in this._colors4) {
  27301. var color = this._colors4[name];
  27302. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  27303. }
  27304. // Vector2
  27305. for (name in this._vectors2) {
  27306. this._effect.setVector2(name, this._vectors2[name]);
  27307. }
  27308. // Vector3
  27309. for (name in this._vectors3) {
  27310. this._effect.setVector3(name, this._vectors3[name]);
  27311. }
  27312. // Matrix
  27313. for (name in this._matrices) {
  27314. this._effect.setMatrix(name, this._matrices[name]);
  27315. }
  27316. if (this.isCube) {
  27317. for (var face = 0; face < 6; face++) {
  27318. engine.bindFramebuffer(this._texture, face);
  27319. // VBOs
  27320. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  27321. this._effect.setFloat("face", face);
  27322. // Clear
  27323. engine.clear(scene.clearColor, true, true, true);
  27324. // Draw order
  27325. engine.draw(true, 0, 6);
  27326. // Mipmaps
  27327. if (face === 5) {
  27328. engine.generateMipMapsForCubemap(this._texture);
  27329. }
  27330. }
  27331. }
  27332. else {
  27333. engine.bindFramebuffer(this._texture);
  27334. // VBOs
  27335. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  27336. // Clear
  27337. engine.clear(scene.clearColor, true, true, true);
  27338. // Draw order
  27339. engine.draw(true, 0, 6);
  27340. }
  27341. // Unbind
  27342. engine.unBindFramebuffer(this._texture, this.isCube);
  27343. if (this.onGenerated) {
  27344. this.onGenerated();
  27345. }
  27346. };
  27347. ProceduralTexture.prototype.clone = function () {
  27348. var textureSize = this.getSize();
  27349. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  27350. // Base texture
  27351. newTexture.hasAlpha = this.hasAlpha;
  27352. newTexture.level = this.level;
  27353. // RenderTarget Texture
  27354. newTexture.coordinatesMode = this.coordinatesMode;
  27355. return newTexture;
  27356. };
  27357. ProceduralTexture.prototype.dispose = function () {
  27358. var index = this.getScene()._proceduralTextures.indexOf(this);
  27359. if (index >= 0) {
  27360. this.getScene()._proceduralTextures.splice(index, 1);
  27361. }
  27362. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27363. if (vertexBuffer) {
  27364. vertexBuffer.dispose();
  27365. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27366. }
  27367. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  27368. this._indexBuffer = null;
  27369. }
  27370. _super.prototype.dispose.call(this);
  27371. };
  27372. return ProceduralTexture;
  27373. }(BABYLON.Texture));
  27374. BABYLON.ProceduralTexture = ProceduralTexture;
  27375. })(BABYLON || (BABYLON = {}));
  27376. //# sourceMappingURL=babylon.proceduralTexture.js.map
  27377. /// <reference path="babylon.renderTargetTexture.ts" />
  27378. var BABYLON;
  27379. (function (BABYLON) {
  27380. var MirrorTexture = (function (_super) {
  27381. __extends(MirrorTexture, _super);
  27382. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  27383. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  27384. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  27385. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  27386. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  27387. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  27388. _this._transformMatrix = BABYLON.Matrix.Zero();
  27389. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  27390. _this.onBeforeRenderObservable.add(function () {
  27391. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  27392. _this._savedViewMatrix = scene.getViewMatrix();
  27393. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  27394. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  27395. scene.clipPlane = _this.mirrorPlane;
  27396. scene.getEngine().cullBackFaces = false;
  27397. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  27398. });
  27399. _this.onAfterRenderObservable.add(function () {
  27400. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  27401. scene.getEngine().cullBackFaces = true;
  27402. scene._mirroredCameraPosition = null;
  27403. delete scene.clipPlane;
  27404. });
  27405. return _this;
  27406. }
  27407. MirrorTexture.prototype.clone = function () {
  27408. var textureSize = this.getSize();
  27409. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  27410. // Base texture
  27411. newTexture.hasAlpha = this.hasAlpha;
  27412. newTexture.level = this.level;
  27413. // Mirror Texture
  27414. newTexture.mirrorPlane = this.mirrorPlane.clone();
  27415. newTexture.renderList = this.renderList.slice(0);
  27416. return newTexture;
  27417. };
  27418. MirrorTexture.prototype.serialize = function () {
  27419. if (!this.name) {
  27420. return null;
  27421. }
  27422. var serializationObject = _super.prototype.serialize.call(this);
  27423. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  27424. return serializationObject;
  27425. };
  27426. return MirrorTexture;
  27427. }(BABYLON.RenderTargetTexture));
  27428. BABYLON.MirrorTexture = MirrorTexture;
  27429. })(BABYLON || (BABYLON = {}));
  27430. //# sourceMappingURL=babylon.mirrorTexture.js.map
  27431. /// <reference path="babylon.renderTargetTexture.ts" />
  27432. var BABYLON;
  27433. (function (BABYLON) {
  27434. /**
  27435. * Creates a refraction texture used by refraction channel of the standard material.
  27436. * @param name the texture name
  27437. * @param size size of the underlying texture
  27438. * @param scene root scene
  27439. */
  27440. var RefractionTexture = (function (_super) {
  27441. __extends(RefractionTexture, _super);
  27442. function RefractionTexture(name, size, scene, generateMipMaps) {
  27443. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  27444. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  27445. _this.depth = 2.0;
  27446. _this.onBeforeRenderObservable.add(function () {
  27447. scene.clipPlane = _this.refractionPlane;
  27448. });
  27449. _this.onAfterRenderObservable.add(function () {
  27450. delete scene.clipPlane;
  27451. });
  27452. return _this;
  27453. }
  27454. RefractionTexture.prototype.clone = function () {
  27455. var textureSize = this.getSize();
  27456. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  27457. // Base texture
  27458. newTexture.hasAlpha = this.hasAlpha;
  27459. newTexture.level = this.level;
  27460. // Refraction Texture
  27461. newTexture.refractionPlane = this.refractionPlane.clone();
  27462. newTexture.renderList = this.renderList.slice(0);
  27463. newTexture.depth = this.depth;
  27464. return newTexture;
  27465. };
  27466. RefractionTexture.prototype.serialize = function () {
  27467. if (!this.name) {
  27468. return null;
  27469. }
  27470. var serializationObject = _super.prototype.serialize.call(this);
  27471. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  27472. serializationObject.depth = this.depth;
  27473. return serializationObject;
  27474. };
  27475. return RefractionTexture;
  27476. }(BABYLON.RenderTargetTexture));
  27477. BABYLON.RefractionTexture = RefractionTexture;
  27478. })(BABYLON || (BABYLON = {}));
  27479. //# sourceMappingURL=babylon.refractionTexture.js.map
  27480. /// <reference path="babylon.texture.ts" />
  27481. var BABYLON;
  27482. (function (BABYLON) {
  27483. var DynamicTexture = (function (_super) {
  27484. __extends(DynamicTexture, _super);
  27485. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  27486. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27487. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27488. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  27489. _this.name = name;
  27490. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27491. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27492. _this._generateMipMaps = generateMipMaps;
  27493. if (options.getContext) {
  27494. _this._canvas = options;
  27495. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  27496. }
  27497. else {
  27498. _this._canvas = document.createElement("canvas");
  27499. if (options.width) {
  27500. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  27501. }
  27502. else {
  27503. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  27504. }
  27505. }
  27506. var textureSize = _this.getSize();
  27507. _this._canvas.width = textureSize.width;
  27508. _this._canvas.height = textureSize.height;
  27509. _this._context = _this._canvas.getContext("2d");
  27510. return _this;
  27511. }
  27512. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  27513. get: function () {
  27514. return true;
  27515. },
  27516. enumerable: true,
  27517. configurable: true
  27518. });
  27519. DynamicTexture.prototype.scale = function (ratio) {
  27520. var textureSize = this.getSize();
  27521. textureSize.width *= ratio;
  27522. textureSize.height *= ratio;
  27523. this._canvas.width = textureSize.width;
  27524. this._canvas.height = textureSize.height;
  27525. this.releaseInternalTexture();
  27526. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  27527. };
  27528. DynamicTexture.prototype.getContext = function () {
  27529. return this._context;
  27530. };
  27531. DynamicTexture.prototype.clear = function () {
  27532. var size = this.getSize();
  27533. this._context.fillRect(0, 0, size.width, size.height);
  27534. };
  27535. DynamicTexture.prototype.update = function (invertY) {
  27536. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  27537. };
  27538. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  27539. if (update === void 0) { update = true; }
  27540. var size = this.getSize();
  27541. if (clearColor) {
  27542. this._context.fillStyle = clearColor;
  27543. this._context.fillRect(0, 0, size.width, size.height);
  27544. }
  27545. this._context.font = font;
  27546. if (x === null) {
  27547. var textSize = this._context.measureText(text);
  27548. x = (size.width - textSize.width) / 2;
  27549. }
  27550. this._context.fillStyle = color;
  27551. this._context.fillText(text, x, y);
  27552. if (update) {
  27553. this.update(invertY);
  27554. }
  27555. };
  27556. DynamicTexture.prototype.clone = function () {
  27557. var textureSize = this.getSize();
  27558. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  27559. // Base texture
  27560. newTexture.hasAlpha = this.hasAlpha;
  27561. newTexture.level = this.level;
  27562. // Dynamic Texture
  27563. newTexture.wrapU = this.wrapU;
  27564. newTexture.wrapV = this.wrapV;
  27565. return newTexture;
  27566. };
  27567. return DynamicTexture;
  27568. }(BABYLON.Texture));
  27569. BABYLON.DynamicTexture = DynamicTexture;
  27570. })(BABYLON || (BABYLON = {}));
  27571. //# sourceMappingURL=babylon.dynamicTexture.js.map
  27572. var BABYLON;
  27573. (function (BABYLON) {
  27574. var VideoTexture = (function (_super) {
  27575. __extends(VideoTexture, _super);
  27576. /**
  27577. * Creates a video texture.
  27578. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  27579. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  27580. * @param {BABYLON.Scene} scene is obviously the current scene.
  27581. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  27582. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  27583. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  27584. */
  27585. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  27586. if (generateMipMaps === void 0) { generateMipMaps = false; }
  27587. if (invertY === void 0) { invertY = false; }
  27588. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27589. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  27590. _this._autoLaunch = true;
  27591. var urls;
  27592. _this.name = name;
  27593. if (urlsOrVideo instanceof HTMLVideoElement) {
  27594. _this.video = urlsOrVideo;
  27595. }
  27596. else {
  27597. urls = urlsOrVideo;
  27598. _this.video = document.createElement("video");
  27599. _this.video.autoplay = false;
  27600. _this.video.loop = true;
  27601. }
  27602. _this._generateMipMaps = generateMipMaps;
  27603. _this._samplingMode = samplingMode;
  27604. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  27605. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  27606. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  27607. }
  27608. else {
  27609. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27610. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27611. _this._generateMipMaps = false;
  27612. }
  27613. if (urls) {
  27614. _this.video.addEventListener("canplaythrough", function () {
  27615. _this._createTexture();
  27616. });
  27617. urls.forEach(function (url) {
  27618. var source = document.createElement("source");
  27619. source.src = url;
  27620. _this.video.appendChild(source);
  27621. });
  27622. }
  27623. else {
  27624. _this._createTexture();
  27625. }
  27626. _this._lastUpdate = BABYLON.Tools.Now;
  27627. return _this;
  27628. }
  27629. VideoTexture.prototype._createTexture = function () {
  27630. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  27631. this._texture.isReady = true;
  27632. };
  27633. VideoTexture.prototype.update = function () {
  27634. if (this._autoLaunch) {
  27635. this._autoLaunch = false;
  27636. this.video.play();
  27637. }
  27638. var now = BABYLON.Tools.Now;
  27639. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  27640. return false;
  27641. }
  27642. this._lastUpdate = now;
  27643. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  27644. return true;
  27645. };
  27646. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  27647. var video = document.createElement("video");
  27648. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  27649. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  27650. if (navigator.getUserMedia) {
  27651. navigator.getUserMedia({
  27652. video: {
  27653. width: {
  27654. min: (constraints && constraints.minWidth) || 256,
  27655. max: (constraints && constraints.maxWidth) || 640
  27656. },
  27657. height: {
  27658. min: (constraints && constraints.minHeight) || 256,
  27659. max: (constraints && constraints.maxHeight) || 480
  27660. }
  27661. }
  27662. }, function (stream) {
  27663. if (video.mozSrcObject !== undefined) {
  27664. video.mozSrcObject = stream;
  27665. }
  27666. else {
  27667. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  27668. }
  27669. video.play();
  27670. if (onReady) {
  27671. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  27672. }
  27673. }, function (e) {
  27674. BABYLON.Tools.Error(e.name);
  27675. });
  27676. }
  27677. };
  27678. return VideoTexture;
  27679. }(BABYLON.Texture));
  27680. BABYLON.VideoTexture = VideoTexture;
  27681. })(BABYLON || (BABYLON = {}));
  27682. //# sourceMappingURL=babylon.videoTexture.js.map
  27683. /// <reference path="babylon.proceduralTexture.ts" />
  27684. var BABYLON;
  27685. (function (BABYLON) {
  27686. var CustomProceduralTexture = (function (_super) {
  27687. __extends(CustomProceduralTexture, _super);
  27688. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  27689. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  27690. _this._animate = true;
  27691. _this._time = 0;
  27692. _this._texturePath = texturePath;
  27693. //Try to load json
  27694. _this.loadJson(texturePath);
  27695. _this.refreshRate = 1;
  27696. return _this;
  27697. }
  27698. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  27699. var _this = this;
  27700. var that = this;
  27701. function noConfigFile() {
  27702. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  27703. try {
  27704. that.setFragment(that._texturePath);
  27705. }
  27706. catch (ex) {
  27707. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  27708. }
  27709. }
  27710. var configFileUrl = jsonUrl + "/config.json";
  27711. var xhr = new XMLHttpRequest();
  27712. xhr.open("GET", configFileUrl, true);
  27713. xhr.addEventListener("load", function () {
  27714. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  27715. try {
  27716. _this._config = JSON.parse(xhr.response);
  27717. _this.updateShaderUniforms();
  27718. _this.updateTextures();
  27719. _this.setFragment(_this._texturePath + "/custom");
  27720. _this._animate = _this._config.animate;
  27721. _this.refreshRate = _this._config.refreshrate;
  27722. }
  27723. catch (ex) {
  27724. noConfigFile();
  27725. }
  27726. }
  27727. else {
  27728. noConfigFile();
  27729. }
  27730. }, false);
  27731. xhr.addEventListener("error", function () {
  27732. noConfigFile();
  27733. }, false);
  27734. try {
  27735. xhr.send();
  27736. }
  27737. catch (ex) {
  27738. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  27739. }
  27740. };
  27741. CustomProceduralTexture.prototype.isReady = function () {
  27742. if (!_super.prototype.isReady.call(this)) {
  27743. return false;
  27744. }
  27745. for (var name in this._textures) {
  27746. var texture = this._textures[name];
  27747. if (!texture.isReady()) {
  27748. return false;
  27749. }
  27750. }
  27751. return true;
  27752. };
  27753. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  27754. if (this._animate) {
  27755. this._time += this.getScene().getAnimationRatio() * 0.03;
  27756. this.updateShaderUniforms();
  27757. }
  27758. _super.prototype.render.call(this, useCameraPostProcess);
  27759. };
  27760. CustomProceduralTexture.prototype.updateTextures = function () {
  27761. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  27762. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  27763. }
  27764. };
  27765. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  27766. if (this._config) {
  27767. for (var j = 0; j < this._config.uniforms.length; j++) {
  27768. var uniform = this._config.uniforms[j];
  27769. switch (uniform.type) {
  27770. case "float":
  27771. this.setFloat(uniform.name, uniform.value);
  27772. break;
  27773. case "color3":
  27774. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  27775. break;
  27776. case "color4":
  27777. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  27778. break;
  27779. case "vector2":
  27780. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  27781. break;
  27782. case "vector3":
  27783. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  27784. break;
  27785. }
  27786. }
  27787. }
  27788. this.setFloat("time", this._time);
  27789. };
  27790. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  27791. get: function () {
  27792. return this._animate;
  27793. },
  27794. set: function (value) {
  27795. this._animate = value;
  27796. },
  27797. enumerable: true,
  27798. configurable: true
  27799. });
  27800. return CustomProceduralTexture;
  27801. }(BABYLON.ProceduralTexture));
  27802. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  27803. })(BABYLON || (BABYLON = {}));
  27804. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  27805. var BABYLON;
  27806. (function (BABYLON) {
  27807. var EffectFallbacks = (function () {
  27808. function EffectFallbacks() {
  27809. this._defines = {};
  27810. this._currentRank = 32;
  27811. this._maxRank = -1;
  27812. }
  27813. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27814. if (!this._defines[rank]) {
  27815. if (rank < this._currentRank) {
  27816. this._currentRank = rank;
  27817. }
  27818. if (rank > this._maxRank) {
  27819. this._maxRank = rank;
  27820. }
  27821. this._defines[rank] = new Array();
  27822. }
  27823. this._defines[rank].push(define);
  27824. };
  27825. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  27826. this._meshRank = rank;
  27827. this._mesh = mesh;
  27828. if (rank > this._maxRank) {
  27829. this._maxRank = rank;
  27830. }
  27831. };
  27832. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  27833. get: function () {
  27834. return this._currentRank <= this._maxRank;
  27835. },
  27836. enumerable: true,
  27837. configurable: true
  27838. });
  27839. EffectFallbacks.prototype.reduce = function (currentDefines) {
  27840. var currentFallbacks = this._defines[this._currentRank];
  27841. for (var index = 0; index < currentFallbacks.length; index++) {
  27842. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  27843. }
  27844. if (this._mesh && this._currentRank === this._meshRank) {
  27845. this._mesh.computeBonesUsingShaders = false;
  27846. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  27847. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  27848. }
  27849. this._currentRank++;
  27850. return currentDefines;
  27851. };
  27852. return EffectFallbacks;
  27853. }());
  27854. BABYLON.EffectFallbacks = EffectFallbacks;
  27855. var Effect = (function () {
  27856. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  27857. var _this = this;
  27858. this.uniqueId = 0;
  27859. this._isReady = false;
  27860. this._compilationError = "";
  27861. this._valueCache = {};
  27862. this._engine = engine;
  27863. this.name = baseName;
  27864. this.defines = defines;
  27865. this._uniformsNames = uniformsNames.concat(samplers);
  27866. this._samplers = samplers;
  27867. this._attributesNames = attributesNames;
  27868. this.onError = onError;
  27869. this.onCompiled = onCompiled;
  27870. this._indexParameters = indexParameters;
  27871. this.uniqueId = Effect._uniqueIdSeed++;
  27872. var vertexSource;
  27873. var fragmentSource;
  27874. if (baseName.vertexElement) {
  27875. vertexSource = document.getElementById(baseName.vertexElement);
  27876. if (!vertexSource) {
  27877. vertexSource = baseName.vertexElement;
  27878. }
  27879. }
  27880. else {
  27881. vertexSource = baseName.vertex || baseName;
  27882. }
  27883. if (baseName.fragmentElement) {
  27884. fragmentSource = document.getElementById(baseName.fragmentElement);
  27885. if (!fragmentSource) {
  27886. fragmentSource = baseName.fragmentElement;
  27887. }
  27888. }
  27889. else {
  27890. fragmentSource = baseName.fragment || baseName;
  27891. }
  27892. this._loadVertexShader(vertexSource, function (vertexCode) {
  27893. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  27894. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  27895. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  27896. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  27897. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  27898. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, attributesNames, defines, fallbacks);
  27899. });
  27900. });
  27901. });
  27902. });
  27903. });
  27904. });
  27905. }
  27906. Object.defineProperty(Effect.prototype, "key", {
  27907. get: function () {
  27908. return this._key;
  27909. },
  27910. enumerable: true,
  27911. configurable: true
  27912. });
  27913. // Properties
  27914. Effect.prototype.isReady = function () {
  27915. return this._isReady;
  27916. };
  27917. Effect.prototype.getProgram = function () {
  27918. return this._program;
  27919. };
  27920. Effect.prototype.getAttributesNames = function () {
  27921. return this._attributesNames;
  27922. };
  27923. Effect.prototype.getAttributeLocation = function (index) {
  27924. return this._attributes[index];
  27925. };
  27926. Effect.prototype.getAttributeLocationByName = function (name) {
  27927. var index = this._attributesNames.indexOf(name);
  27928. return this._attributes[index];
  27929. };
  27930. Effect.prototype.getAttributesCount = function () {
  27931. return this._attributes.length;
  27932. };
  27933. Effect.prototype.getUniformIndex = function (uniformName) {
  27934. return this._uniformsNames.indexOf(uniformName);
  27935. };
  27936. Effect.prototype.getUniform = function (uniformName) {
  27937. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  27938. };
  27939. Effect.prototype.getSamplers = function () {
  27940. return this._samplers;
  27941. };
  27942. Effect.prototype.getCompilationError = function () {
  27943. return this._compilationError;
  27944. };
  27945. Effect.prototype.getVertexShaderSource = function () {
  27946. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  27947. };
  27948. Effect.prototype.getFragmentShaderSource = function () {
  27949. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  27950. };
  27951. // Methods
  27952. Effect.prototype._loadVertexShader = function (vertex, callback) {
  27953. // DOM element ?
  27954. if (vertex instanceof HTMLElement) {
  27955. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  27956. callback(vertexCode);
  27957. return;
  27958. }
  27959. // Base64 encoded ?
  27960. if (vertex.substr(0, 7) === "base64:") {
  27961. var vertexBinary = window.atob(vertex.substr(7));
  27962. callback(vertexBinary);
  27963. return;
  27964. }
  27965. // Is in local store ?
  27966. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  27967. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  27968. return;
  27969. }
  27970. var vertexShaderUrl;
  27971. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  27972. vertexShaderUrl = vertex;
  27973. }
  27974. else {
  27975. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  27976. }
  27977. // Vertex shader
  27978. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  27979. };
  27980. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  27981. // DOM element ?
  27982. if (fragment instanceof HTMLElement) {
  27983. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  27984. callback(fragmentCode);
  27985. return;
  27986. }
  27987. // Base64 encoded ?
  27988. if (fragment.substr(0, 7) === "base64:") {
  27989. var fragmentBinary = window.atob(fragment.substr(7));
  27990. callback(fragmentBinary);
  27991. return;
  27992. }
  27993. // Is in local store ?
  27994. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  27995. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  27996. return;
  27997. }
  27998. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  27999. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  28000. return;
  28001. }
  28002. var fragmentShaderUrl;
  28003. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  28004. fragmentShaderUrl = fragment;
  28005. }
  28006. else {
  28007. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  28008. }
  28009. // Fragment shader
  28010. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  28011. };
  28012. Effect.prototype._dumpShadersName = function () {
  28013. if (this.name.vertexElement) {
  28014. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  28015. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  28016. }
  28017. else if (this.name.vertex) {
  28018. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  28019. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  28020. }
  28021. else {
  28022. BABYLON.Tools.Error("Vertex shader:" + this.name);
  28023. BABYLON.Tools.Error("Fragment shader:" + this.name);
  28024. }
  28025. };
  28026. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  28027. var preparedSourceCode = this._processPrecision(sourceCode);
  28028. if (this._engine.webGLVersion == 1) {
  28029. callback(preparedSourceCode);
  28030. return;
  28031. }
  28032. // Already converted
  28033. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  28034. callback(preparedSourceCode);
  28035. return;
  28036. }
  28037. // Remove extensions
  28038. // #extension GL_OES_standard_derivatives : enable
  28039. // #extension GL_EXT_shader_texture_lod : enable
  28040. // #extension GL_EXT_frag_depth : enable
  28041. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  28042. var result = preparedSourceCode.replace(regex, "");
  28043. // Migrate to GLSL v300
  28044. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  28045. result = result.replace(/attribute[ \t]/g, "in ");
  28046. result = result.replace(/[ \t]attribute/g, " in");
  28047. if (isFragment) {
  28048. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  28049. result = result.replace(/texture2D\(/g, "texture(");
  28050. result = result.replace(/textureCube\(/g, "texture(");
  28051. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  28052. result = result.replace(/gl_FragColor/g, "glFragColor");
  28053. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  28054. }
  28055. callback(result);
  28056. };
  28057. Effect.prototype._processIncludes = function (sourceCode, callback) {
  28058. var _this = this;
  28059. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  28060. var match = regex.exec(sourceCode);
  28061. var returnValue = new String(sourceCode);
  28062. while (match != null) {
  28063. var includeFile = match[1];
  28064. if (Effect.IncludesShadersStore[includeFile]) {
  28065. // Substitution
  28066. var includeContent = Effect.IncludesShadersStore[includeFile];
  28067. if (match[2]) {
  28068. var splits = match[3].split(",");
  28069. for (var index = 0; index < splits.length; index += 2) {
  28070. var source = new RegExp(splits[index], "g");
  28071. var dest = splits[index + 1];
  28072. includeContent = includeContent.replace(source, dest);
  28073. }
  28074. }
  28075. if (match[4]) {
  28076. var indexString = match[5];
  28077. if (indexString.indexOf("..") !== -1) {
  28078. var indexSplits = indexString.split("..");
  28079. var minIndex = parseInt(indexSplits[0]);
  28080. var maxIndex = parseInt(indexSplits[1]);
  28081. var sourceIncludeContent = includeContent.slice(0);
  28082. includeContent = "";
  28083. if (isNaN(maxIndex)) {
  28084. maxIndex = this._indexParameters[indexSplits[1]];
  28085. }
  28086. for (var i = minIndex; i <= maxIndex; i++) {
  28087. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  28088. }
  28089. }
  28090. else {
  28091. includeContent = includeContent.replace(/\{X\}/g, indexString);
  28092. }
  28093. }
  28094. // Replace
  28095. returnValue = returnValue.replace(match[0], includeContent);
  28096. }
  28097. else {
  28098. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  28099. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  28100. Effect.IncludesShadersStore[includeFile] = fileContent;
  28101. _this._processIncludes(returnValue, callback);
  28102. });
  28103. return;
  28104. }
  28105. match = regex.exec(sourceCode);
  28106. }
  28107. callback(returnValue);
  28108. };
  28109. Effect.prototype._processPrecision = function (source) {
  28110. if (source.indexOf("precision highp float") === -1) {
  28111. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  28112. source = "precision mediump float;\n" + source;
  28113. }
  28114. else {
  28115. source = "precision highp float;\n" + source;
  28116. }
  28117. }
  28118. else {
  28119. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  28120. source = source.replace("precision highp float", "precision mediump float");
  28121. }
  28122. }
  28123. return source;
  28124. };
  28125. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  28126. try {
  28127. var engine = this._engine;
  28128. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  28129. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  28130. this._attributes = engine.getAttributes(this._program, attributesNames);
  28131. var index;
  28132. for (index = 0; index < this._samplers.length; index++) {
  28133. var sampler = this.getUniform(this._samplers[index]);
  28134. if (sampler == null) {
  28135. this._samplers.splice(index, 1);
  28136. index--;
  28137. }
  28138. }
  28139. engine.bindSamplers(this);
  28140. this._compilationError = "";
  28141. this._isReady = true;
  28142. if (this.onCompiled) {
  28143. this.onCompiled(this);
  28144. }
  28145. }
  28146. catch (e) {
  28147. this._compilationError = e.message;
  28148. // Let's go through fallbacks then
  28149. BABYLON.Tools.Error("Unable to compile effect: ");
  28150. BABYLON.Tools.Error("Defines: " + defines);
  28151. BABYLON.Tools.Error("Error: " + this._compilationError);
  28152. this._dumpShadersName();
  28153. if (fallbacks && fallbacks.isMoreFallbacks) {
  28154. BABYLON.Tools.Error("Trying next fallback.");
  28155. defines = fallbacks.reduce(defines);
  28156. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  28157. }
  28158. else {
  28159. if (this.onError) {
  28160. this.onError(this, this._compilationError);
  28161. }
  28162. }
  28163. }
  28164. };
  28165. Object.defineProperty(Effect.prototype, "isSupported", {
  28166. get: function () {
  28167. return this._compilationError === "";
  28168. },
  28169. enumerable: true,
  28170. configurable: true
  28171. });
  28172. Effect.prototype._bindTexture = function (channel, texture) {
  28173. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  28174. };
  28175. Effect.prototype.setTexture = function (channel, texture) {
  28176. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  28177. };
  28178. Effect.prototype.setTextureArray = function (channel, textures) {
  28179. if (this._samplers.indexOf(channel + "Ex") === -1) {
  28180. var initialPos = this._samplers.indexOf(channel);
  28181. for (var index = 1; index < textures.length; index++) {
  28182. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  28183. }
  28184. }
  28185. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  28186. };
  28187. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  28188. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  28189. };
  28190. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  28191. var changed = false;
  28192. var cache = this._valueCache[uniformName];
  28193. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  28194. changed = true;
  28195. cache = new BABYLON.Matrix();
  28196. }
  28197. var tm = cache.m;
  28198. var om = matrix.m;
  28199. for (var index = 0; index < 16; index++) {
  28200. if (tm[index] !== om[index]) {
  28201. tm[index] = om[index];
  28202. changed = true;
  28203. }
  28204. }
  28205. this._valueCache[uniformName] = cache;
  28206. return changed;
  28207. };
  28208. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  28209. var cache = this._valueCache[uniformName];
  28210. if (!cache) {
  28211. cache = [x, y];
  28212. this._valueCache[uniformName] = cache;
  28213. return true;
  28214. }
  28215. var changed = false;
  28216. if (cache[0] !== x) {
  28217. cache[0] = x;
  28218. changed = true;
  28219. }
  28220. if (cache[1] !== y) {
  28221. cache[1] = y;
  28222. changed = true;
  28223. }
  28224. return changed;
  28225. };
  28226. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  28227. var cache = this._valueCache[uniformName];
  28228. if (!cache) {
  28229. cache = [x, y, z];
  28230. this._valueCache[uniformName] = cache;
  28231. return true;
  28232. }
  28233. var changed = false;
  28234. if (cache[0] !== x) {
  28235. cache[0] = x;
  28236. changed = true;
  28237. }
  28238. if (cache[1] !== y) {
  28239. cache[1] = y;
  28240. changed = true;
  28241. }
  28242. if (cache[2] !== z) {
  28243. cache[2] = z;
  28244. changed = true;
  28245. }
  28246. return changed;
  28247. };
  28248. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  28249. var cache = this._valueCache[uniformName];
  28250. if (!cache) {
  28251. cache = [x, y, z, w];
  28252. this._valueCache[uniformName] = cache;
  28253. return true;
  28254. }
  28255. var changed = false;
  28256. if (cache[0] !== x) {
  28257. cache[0] = x;
  28258. changed = true;
  28259. }
  28260. if (cache[1] !== y) {
  28261. cache[1] = y;
  28262. changed = true;
  28263. }
  28264. if (cache[2] !== z) {
  28265. cache[2] = z;
  28266. changed = true;
  28267. }
  28268. if (cache[3] !== w) {
  28269. cache[3] = w;
  28270. changed = true;
  28271. }
  28272. return changed;
  28273. };
  28274. Effect.prototype.setIntArray = function (uniformName, array) {
  28275. this._valueCache[uniformName] = null;
  28276. this._engine.setIntArray(this.getUniform(uniformName), array);
  28277. return this;
  28278. };
  28279. Effect.prototype.setIntArray2 = function (uniformName, array) {
  28280. this._valueCache[uniformName] = null;
  28281. this._engine.setIntArray2(this.getUniform(uniformName), array);
  28282. return this;
  28283. };
  28284. Effect.prototype.setIntArray3 = function (uniformName, array) {
  28285. this._valueCache[uniformName] = null;
  28286. this._engine.setIntArray3(this.getUniform(uniformName), array);
  28287. return this;
  28288. };
  28289. Effect.prototype.setIntArray4 = function (uniformName, array) {
  28290. this._valueCache[uniformName] = null;
  28291. this._engine.setIntArray4(this.getUniform(uniformName), array);
  28292. return this;
  28293. };
  28294. Effect.prototype.setFloatArray = function (uniformName, array) {
  28295. this._valueCache[uniformName] = null;
  28296. this._engine.setFloatArray(this.getUniform(uniformName), array);
  28297. return this;
  28298. };
  28299. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  28300. this._valueCache[uniformName] = null;
  28301. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  28302. return this;
  28303. };
  28304. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  28305. this._valueCache[uniformName] = null;
  28306. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  28307. return this;
  28308. };
  28309. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  28310. this._valueCache[uniformName] = null;
  28311. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  28312. return this;
  28313. };
  28314. Effect.prototype.setArray = function (uniformName, array) {
  28315. this._valueCache[uniformName] = null;
  28316. this._engine.setArray(this.getUniform(uniformName), array);
  28317. return this;
  28318. };
  28319. Effect.prototype.setArray2 = function (uniformName, array) {
  28320. this._valueCache[uniformName] = null;
  28321. this._engine.setArray2(this.getUniform(uniformName), array);
  28322. return this;
  28323. };
  28324. Effect.prototype.setArray3 = function (uniformName, array) {
  28325. this._valueCache[uniformName] = null;
  28326. this._engine.setArray3(this.getUniform(uniformName), array);
  28327. return this;
  28328. };
  28329. Effect.prototype.setArray4 = function (uniformName, array) {
  28330. this._valueCache[uniformName] = null;
  28331. this._engine.setArray4(this.getUniform(uniformName), array);
  28332. return this;
  28333. };
  28334. Effect.prototype.setMatrices = function (uniformName, matrices) {
  28335. this._valueCache[uniformName] = null;
  28336. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  28337. return this;
  28338. };
  28339. Effect.prototype.setMatrix = function (uniformName, matrix) {
  28340. if (this._cacheMatrix(uniformName, matrix)) {
  28341. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  28342. }
  28343. return this;
  28344. };
  28345. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  28346. this._valueCache[uniformName] = null;
  28347. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  28348. return this;
  28349. };
  28350. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  28351. this._valueCache[uniformName] = null;
  28352. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  28353. return this;
  28354. };
  28355. Effect.prototype.setFloat = function (uniformName, value) {
  28356. var cache = this._valueCache[uniformName];
  28357. if (cache !== undefined && cache === value)
  28358. return this;
  28359. this._valueCache[uniformName] = value;
  28360. this._engine.setFloat(this.getUniform(uniformName), value);
  28361. return this;
  28362. };
  28363. Effect.prototype.setBool = function (uniformName, bool) {
  28364. var cache = this._valueCache[uniformName];
  28365. if (cache !== undefined && cache === bool)
  28366. return this;
  28367. this._valueCache[uniformName] = bool;
  28368. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  28369. return this;
  28370. };
  28371. Effect.prototype.setVector2 = function (uniformName, vector2) {
  28372. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  28373. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  28374. }
  28375. return this;
  28376. };
  28377. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  28378. if (this._cacheFloat2(uniformName, x, y)) {
  28379. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  28380. }
  28381. return this;
  28382. };
  28383. Effect.prototype.setVector3 = function (uniformName, vector3) {
  28384. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  28385. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  28386. }
  28387. return this;
  28388. };
  28389. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  28390. if (this._cacheFloat3(uniformName, x, y, z)) {
  28391. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  28392. }
  28393. return this;
  28394. };
  28395. Effect.prototype.setVector4 = function (uniformName, vector4) {
  28396. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  28397. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  28398. }
  28399. return this;
  28400. };
  28401. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  28402. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  28403. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  28404. }
  28405. return this;
  28406. };
  28407. Effect.prototype.setColor3 = function (uniformName, color3) {
  28408. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  28409. this._engine.setColor3(this.getUniform(uniformName), color3);
  28410. }
  28411. return this;
  28412. };
  28413. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  28414. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  28415. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  28416. }
  28417. return this;
  28418. };
  28419. Effect.prototype._recombineShader = function (node) {
  28420. if (node.define) {
  28421. if (node.condition) {
  28422. var defineIndex = this.defines.indexOf("#define " + node.define);
  28423. if (defineIndex === -1) {
  28424. return null;
  28425. }
  28426. var nextComma = this.defines.indexOf("\n", defineIndex);
  28427. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  28428. var condition = defineValue + node.condition;
  28429. if (!eval(condition)) {
  28430. return null;
  28431. }
  28432. }
  28433. else if (node.ndef) {
  28434. if (this.defines.indexOf("#define " + node.define) !== -1) {
  28435. return null;
  28436. }
  28437. }
  28438. else if (this.defines.indexOf("#define " + node.define) === -1) {
  28439. return null;
  28440. }
  28441. }
  28442. var result = "";
  28443. for (var index = 0; index < node.children.length; index++) {
  28444. var line = node.children[index];
  28445. if (line.children) {
  28446. var combined = this._recombineShader(line);
  28447. if (combined !== null) {
  28448. result += combined + "\r\n";
  28449. }
  28450. continue;
  28451. }
  28452. if (line.length > 0) {
  28453. result += line + "\r\n";
  28454. }
  28455. }
  28456. return result;
  28457. };
  28458. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  28459. var root = {
  28460. children: []
  28461. };
  28462. var currentNode = root;
  28463. var lines = shaderString.split("\n");
  28464. for (var index = 0; index < lines.length; index++) {
  28465. var line = lines[index].trim();
  28466. // #ifdef
  28467. var pos = line.indexOf("#ifdef ");
  28468. if (pos !== -1) {
  28469. var define = line.substr(pos + 7);
  28470. var newNode = {
  28471. condition: null,
  28472. ndef: false,
  28473. define: define,
  28474. children: [],
  28475. parent: currentNode
  28476. };
  28477. currentNode.children.push(newNode);
  28478. currentNode = newNode;
  28479. continue;
  28480. }
  28481. // #ifndef
  28482. var pos = line.indexOf("#ifndef ");
  28483. if (pos !== -1) {
  28484. var define = line.substr(pos + 8);
  28485. newNode = {
  28486. condition: null,
  28487. define: define,
  28488. ndef: true,
  28489. children: [],
  28490. parent: currentNode
  28491. };
  28492. currentNode.children.push(newNode);
  28493. currentNode = newNode;
  28494. continue;
  28495. }
  28496. // #if
  28497. var pos = line.indexOf("#if ");
  28498. if (pos !== -1) {
  28499. var define = line.substr(pos + 4).trim();
  28500. var conditionPos = define.indexOf(" ");
  28501. newNode = {
  28502. condition: define.substr(conditionPos + 1),
  28503. define: define.substr(0, conditionPos),
  28504. ndef: false,
  28505. children: [],
  28506. parent: currentNode
  28507. };
  28508. currentNode.children.push(newNode);
  28509. currentNode = newNode;
  28510. continue;
  28511. }
  28512. // #endif
  28513. pos = line.indexOf("#endif");
  28514. if (pos !== -1) {
  28515. currentNode = currentNode.parent;
  28516. continue;
  28517. }
  28518. currentNode.children.push(line);
  28519. }
  28520. // Recombine
  28521. return this._recombineShader(root);
  28522. };
  28523. return Effect;
  28524. }());
  28525. Effect._uniqueIdSeed = 0;
  28526. // Statics
  28527. Effect.ShadersStore = {};
  28528. Effect.IncludesShadersStore = {};
  28529. BABYLON.Effect = Effect;
  28530. })(BABYLON || (BABYLON = {}));
  28531. //# sourceMappingURL=babylon.effect.js.map
  28532. var BABYLON;
  28533. (function (BABYLON) {
  28534. var MaterialHelper = (function () {
  28535. function MaterialHelper() {
  28536. }
  28537. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  28538. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  28539. var lightIndex = 0;
  28540. var needNormals = false;
  28541. var needRebuild = false;
  28542. var needShadows = false;
  28543. var lightmapMode = false;
  28544. for (var index = 0; index < scene.lights.length; index++) {
  28545. var light = scene.lights[index];
  28546. if (!light.isEnabled()) {
  28547. continue;
  28548. }
  28549. // Excluded check
  28550. if (light._excludedMeshesIds.length > 0) {
  28551. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  28552. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  28553. if (excludedMesh) {
  28554. light.excludedMeshes.push(excludedMesh);
  28555. }
  28556. }
  28557. light._excludedMeshesIds = [];
  28558. }
  28559. // Included check
  28560. if (light._includedOnlyMeshesIds.length > 0) {
  28561. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  28562. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  28563. if (includedOnlyMesh) {
  28564. light.includedOnlyMeshes.push(includedOnlyMesh);
  28565. }
  28566. }
  28567. light._includedOnlyMeshesIds = [];
  28568. }
  28569. if (!light.canAffectMesh(mesh)) {
  28570. continue;
  28571. }
  28572. needNormals = true;
  28573. if (defines["LIGHT" + lightIndex] === undefined) {
  28574. needRebuild = true;
  28575. }
  28576. defines["LIGHT" + lightIndex] = true;
  28577. var type;
  28578. if (light instanceof BABYLON.SpotLight) {
  28579. type = "SPOTLIGHT" + lightIndex;
  28580. }
  28581. else if (light instanceof BABYLON.HemisphericLight) {
  28582. type = "HEMILIGHT" + lightIndex;
  28583. }
  28584. else if (light instanceof BABYLON.PointLight) {
  28585. type = "POINTLIGHT" + lightIndex;
  28586. }
  28587. else {
  28588. type = "DIRLIGHT" + lightIndex;
  28589. }
  28590. if (defines[type] === undefined) {
  28591. needRebuild = true;
  28592. }
  28593. defines[type] = true;
  28594. // Specular
  28595. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  28596. defines["SPECULARTERM"] = true;
  28597. }
  28598. // Shadows
  28599. if (scene.shadowsEnabled) {
  28600. var shadowGenerator = light.getShadowGenerator();
  28601. if (mesh && mesh.receiveShadows && shadowGenerator) {
  28602. if (defines["SHADOW" + lightIndex] === undefined) {
  28603. needRebuild = true;
  28604. }
  28605. defines["SHADOW" + lightIndex] = true;
  28606. defines["SHADOWS"] = true;
  28607. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  28608. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  28609. needRebuild = true;
  28610. }
  28611. defines["SHADOWVSM" + lightIndex] = true;
  28612. }
  28613. if (shadowGenerator.usePoissonSampling) {
  28614. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  28615. needRebuild = true;
  28616. }
  28617. defines["SHADOWPCF" + lightIndex] = true;
  28618. }
  28619. needShadows = true;
  28620. }
  28621. }
  28622. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  28623. lightmapMode = true;
  28624. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  28625. needRebuild = true;
  28626. }
  28627. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  28628. needRebuild = true;
  28629. }
  28630. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  28631. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  28632. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  28633. }
  28634. }
  28635. lightIndex++;
  28636. if (lightIndex === maxSimultaneousLights)
  28637. break;
  28638. }
  28639. var caps = scene.getEngine().getCaps();
  28640. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  28641. if (defines["SHADOWFULLFLOAT"] === undefined) {
  28642. needRebuild = true;
  28643. }
  28644. defines["SHADOWFULLFLOAT"] = true;
  28645. }
  28646. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  28647. needRebuild = true;
  28648. }
  28649. if (lightmapMode) {
  28650. defines["LIGHTMAPEXCLUDED"] = true;
  28651. }
  28652. if (needRebuild) {
  28653. defines.rebuild();
  28654. }
  28655. return needNormals;
  28656. };
  28657. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  28658. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  28659. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  28660. if (!defines["LIGHT" + lightIndex]) {
  28661. break;
  28662. }
  28663. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  28664. samplersList.push("shadowSampler" + lightIndex);
  28665. }
  28666. };
  28667. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  28668. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  28669. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  28670. if (!defines["LIGHT" + lightIndex]) {
  28671. break;
  28672. }
  28673. if (lightIndex > 0) {
  28674. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  28675. }
  28676. if (defines["SHADOW" + lightIndex]) {
  28677. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  28678. }
  28679. if (defines["SHADOWPCF" + lightIndex]) {
  28680. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  28681. }
  28682. if (defines["SHADOWVSM" + lightIndex]) {
  28683. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  28684. }
  28685. }
  28686. };
  28687. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  28688. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  28689. fallbacks.addCPUSkinningFallback(0, mesh);
  28690. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28691. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28692. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  28693. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  28694. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  28695. }
  28696. }
  28697. };
  28698. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  28699. if (defines["INSTANCES"]) {
  28700. attribs.push("world0");
  28701. attribs.push("world1");
  28702. attribs.push("world2");
  28703. attribs.push("world3");
  28704. }
  28705. };
  28706. // Bindings
  28707. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  28708. var shadowGenerator = light.getShadowGenerator();
  28709. if (mesh.receiveShadows && shadowGenerator) {
  28710. if (!light.needCube()) {
  28711. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  28712. }
  28713. else {
  28714. if (!depthValuesAlreadySet) {
  28715. depthValuesAlreadySet = true;
  28716. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  28717. }
  28718. }
  28719. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  28720. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  28721. }
  28722. return depthValuesAlreadySet;
  28723. };
  28724. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  28725. if (light instanceof BABYLON.PointLight) {
  28726. // Point Light
  28727. light.transferToEffect(effect, "vLightData" + lightIndex);
  28728. }
  28729. else if (light instanceof BABYLON.DirectionalLight) {
  28730. // Directional Light
  28731. light.transferToEffect(effect, "vLightData" + lightIndex);
  28732. }
  28733. else if (light instanceof BABYLON.SpotLight) {
  28734. // Spot Light
  28735. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  28736. }
  28737. else if (light instanceof BABYLON.HemisphericLight) {
  28738. // Hemispheric Light
  28739. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  28740. }
  28741. };
  28742. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  28743. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  28744. var lightIndex = 0;
  28745. var depthValuesAlreadySet = false;
  28746. for (var index = 0; index < scene.lights.length; index++) {
  28747. var light = scene.lights[index];
  28748. if (!light.isEnabled()) {
  28749. continue;
  28750. }
  28751. if (!light.canAffectMesh(mesh)) {
  28752. continue;
  28753. }
  28754. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  28755. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  28756. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  28757. if (defines["SPECULARTERM"]) {
  28758. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  28759. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  28760. }
  28761. // Shadows
  28762. if (scene.shadowsEnabled) {
  28763. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  28764. }
  28765. lightIndex++;
  28766. if (lightIndex === maxSimultaneousLights)
  28767. break;
  28768. }
  28769. };
  28770. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  28771. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  28772. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  28773. effect.setColor3("vFogColor", scene.fogColor);
  28774. }
  28775. };
  28776. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  28777. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28778. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  28779. if (matrices) {
  28780. effect.setMatrices("mBones", matrices);
  28781. }
  28782. }
  28783. };
  28784. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  28785. if (defines["LOGARITHMICDEPTH"]) {
  28786. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  28787. }
  28788. };
  28789. MaterialHelper.BindClipPlane = function (effect, scene) {
  28790. if (scene.clipPlane) {
  28791. var clipPlane = scene.clipPlane;
  28792. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  28793. }
  28794. };
  28795. return MaterialHelper;
  28796. }());
  28797. BABYLON.MaterialHelper = MaterialHelper;
  28798. })(BABYLON || (BABYLON = {}));
  28799. //# sourceMappingURL=babylon.materialHelper.js.map
  28800. var BABYLON;
  28801. (function (BABYLON) {
  28802. var FresnelParameters = (function () {
  28803. function FresnelParameters() {
  28804. this.isEnabled = true;
  28805. this.leftColor = BABYLON.Color3.White();
  28806. this.rightColor = BABYLON.Color3.Black();
  28807. this.bias = 0;
  28808. this.power = 1;
  28809. }
  28810. FresnelParameters.prototype.clone = function () {
  28811. var newFresnelParameters = new FresnelParameters();
  28812. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  28813. return newFresnelParameters;
  28814. };
  28815. FresnelParameters.prototype.serialize = function () {
  28816. var serializationObject = {};
  28817. serializationObject.isEnabled = this.isEnabled;
  28818. serializationObject.leftColor = this.leftColor;
  28819. serializationObject.rightColor = this.rightColor;
  28820. serializationObject.bias = this.bias;
  28821. serializationObject.power = this.power;
  28822. return serializationObject;
  28823. };
  28824. FresnelParameters.Parse = function (parsedFresnelParameters) {
  28825. var fresnelParameters = new FresnelParameters();
  28826. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  28827. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  28828. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  28829. fresnelParameters.bias = parsedFresnelParameters.bias;
  28830. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  28831. return fresnelParameters;
  28832. };
  28833. return FresnelParameters;
  28834. }());
  28835. BABYLON.FresnelParameters = FresnelParameters;
  28836. })(BABYLON || (BABYLON = {}));
  28837. //# sourceMappingURL=babylon.fresnelParameters.js.map
  28838. var BABYLON;
  28839. (function (BABYLON) {
  28840. var MaterialDefines = (function () {
  28841. function MaterialDefines() {
  28842. }
  28843. MaterialDefines.prototype.rebuild = function () {
  28844. if (this._keys) {
  28845. delete this._keys;
  28846. }
  28847. this._keys = Object.keys(this);
  28848. };
  28849. MaterialDefines.prototype.isEqual = function (other) {
  28850. if (this._keys.length !== other._keys.length) {
  28851. return false;
  28852. }
  28853. for (var index = 0; index < this._keys.length; index++) {
  28854. var prop = this._keys[index];
  28855. if (this[prop] !== other[prop]) {
  28856. return false;
  28857. }
  28858. }
  28859. return true;
  28860. };
  28861. MaterialDefines.prototype.cloneTo = function (other) {
  28862. if (this._keys.length !== other._keys.length) {
  28863. other._keys = this._keys.slice(0);
  28864. }
  28865. for (var index = 0; index < this._keys.length; index++) {
  28866. var prop = this._keys[index];
  28867. other[prop] = this[prop];
  28868. }
  28869. };
  28870. MaterialDefines.prototype.reset = function () {
  28871. for (var index = 0; index < this._keys.length; index++) {
  28872. var prop = this._keys[index];
  28873. if (typeof (this[prop]) === "number") {
  28874. this[prop] = 0;
  28875. }
  28876. else {
  28877. this[prop] = false;
  28878. }
  28879. }
  28880. };
  28881. MaterialDefines.prototype.toString = function () {
  28882. var result = "";
  28883. for (var index = 0; index < this._keys.length; index++) {
  28884. var prop = this._keys[index];
  28885. if (typeof (this[prop]) === "number") {
  28886. result += "#define " + prop + " " + this[prop] + "\n";
  28887. }
  28888. else if (this[prop]) {
  28889. result += "#define " + prop + "\n";
  28890. }
  28891. }
  28892. return result;
  28893. };
  28894. return MaterialDefines;
  28895. }());
  28896. BABYLON.MaterialDefines = MaterialDefines;
  28897. var Material = (function () {
  28898. function Material(name, scene, doNotAdd) {
  28899. this.checkReadyOnEveryCall = false;
  28900. this.checkReadyOnlyOnce = false;
  28901. this.state = "";
  28902. this.alpha = 1.0;
  28903. this.backFaceCulling = true;
  28904. this.doNotSerialize = false;
  28905. /**
  28906. * An event triggered when the material is disposed.
  28907. * @type {BABYLON.Observable}
  28908. */
  28909. this.onDisposeObservable = new BABYLON.Observable();
  28910. /**
  28911. * An event triggered when the material is bound.
  28912. * @type {BABYLON.Observable}
  28913. */
  28914. this.onBindObservable = new BABYLON.Observable();
  28915. /**
  28916. * An event triggered when the material is unbound.
  28917. * @type {BABYLON.Observable}
  28918. */
  28919. this.onUnBindObservable = new BABYLON.Observable();
  28920. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  28921. this.disableDepthWrite = false;
  28922. this.fogEnabled = true;
  28923. this.pointSize = 1.0;
  28924. this.zOffset = 0;
  28925. this._wasPreviouslyReady = false;
  28926. this._fillMode = Material.TriangleFillMode;
  28927. this.name = name;
  28928. this.id = name;
  28929. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  28930. if (scene.useRightHandedSystem) {
  28931. this.sideOrientation = Material.ClockWiseSideOrientation;
  28932. }
  28933. else {
  28934. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  28935. }
  28936. if (!doNotAdd) {
  28937. scene.materials.push(this);
  28938. }
  28939. }
  28940. Object.defineProperty(Material, "TriangleFillMode", {
  28941. get: function () {
  28942. return Material._TriangleFillMode;
  28943. },
  28944. enumerable: true,
  28945. configurable: true
  28946. });
  28947. Object.defineProperty(Material, "WireFrameFillMode", {
  28948. get: function () {
  28949. return Material._WireFrameFillMode;
  28950. },
  28951. enumerable: true,
  28952. configurable: true
  28953. });
  28954. Object.defineProperty(Material, "PointFillMode", {
  28955. get: function () {
  28956. return Material._PointFillMode;
  28957. },
  28958. enumerable: true,
  28959. configurable: true
  28960. });
  28961. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28962. get: function () {
  28963. return Material._ClockWiseSideOrientation;
  28964. },
  28965. enumerable: true,
  28966. configurable: true
  28967. });
  28968. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28969. get: function () {
  28970. return Material._CounterClockWiseSideOrientation;
  28971. },
  28972. enumerable: true,
  28973. configurable: true
  28974. });
  28975. Object.defineProperty(Material.prototype, "onDispose", {
  28976. set: function (callback) {
  28977. if (this._onDisposeObserver) {
  28978. this.onDisposeObservable.remove(this._onDisposeObserver);
  28979. }
  28980. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28981. },
  28982. enumerable: true,
  28983. configurable: true
  28984. });
  28985. Object.defineProperty(Material.prototype, "onBind", {
  28986. set: function (callback) {
  28987. if (this._onBindObserver) {
  28988. this.onBindObservable.remove(this._onBindObserver);
  28989. }
  28990. this._onBindObserver = this.onBindObservable.add(callback);
  28991. },
  28992. enumerable: true,
  28993. configurable: true
  28994. });
  28995. Object.defineProperty(Material.prototype, "wireframe", {
  28996. get: function () {
  28997. return this._fillMode === Material.WireFrameFillMode;
  28998. },
  28999. set: function (value) {
  29000. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  29001. },
  29002. enumerable: true,
  29003. configurable: true
  29004. });
  29005. Object.defineProperty(Material.prototype, "pointsCloud", {
  29006. get: function () {
  29007. return this._fillMode === Material.PointFillMode;
  29008. },
  29009. set: function (value) {
  29010. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29011. },
  29012. enumerable: true,
  29013. configurable: true
  29014. });
  29015. Object.defineProperty(Material.prototype, "fillMode", {
  29016. get: function () {
  29017. return this._fillMode;
  29018. },
  29019. set: function (value) {
  29020. this._fillMode = value;
  29021. },
  29022. enumerable: true,
  29023. configurable: true
  29024. });
  29025. /**
  29026. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29027. * subclasses should override adding information pertainent to themselves
  29028. */
  29029. Material.prototype.toString = function (fullDetails) {
  29030. var ret = "Name: " + this.name;
  29031. if (fullDetails) {
  29032. }
  29033. return ret;
  29034. };
  29035. Material.prototype.getClassName = function () {
  29036. return "Material";
  29037. };
  29038. Object.defineProperty(Material.prototype, "isFrozen", {
  29039. get: function () {
  29040. return this.checkReadyOnlyOnce;
  29041. },
  29042. enumerable: true,
  29043. configurable: true
  29044. });
  29045. Material.prototype.freeze = function () {
  29046. this.checkReadyOnlyOnce = true;
  29047. };
  29048. Material.prototype.unfreeze = function () {
  29049. this.checkReadyOnlyOnce = false;
  29050. };
  29051. Material.prototype.isReady = function (mesh, useInstances) {
  29052. return true;
  29053. };
  29054. Material.prototype.getEffect = function () {
  29055. return this._effect;
  29056. };
  29057. Material.prototype.getScene = function () {
  29058. return this._scene;
  29059. };
  29060. Material.prototype.needAlphaBlending = function () {
  29061. return (this.alpha < 1.0);
  29062. };
  29063. Material.prototype.needAlphaTesting = function () {
  29064. return false;
  29065. };
  29066. Material.prototype.getAlphaTestTexture = function () {
  29067. return null;
  29068. };
  29069. Material.prototype.markDirty = function () {
  29070. this._wasPreviouslyReady = false;
  29071. };
  29072. Material.prototype._preBind = function () {
  29073. var engine = this._scene.getEngine();
  29074. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  29075. engine.enableEffect(this._effect);
  29076. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29077. };
  29078. Material.prototype.bind = function (world, mesh) {
  29079. this._scene._cachedMaterial = this;
  29080. this.onBindObservable.notifyObservers(mesh);
  29081. if (this.disableDepthWrite) {
  29082. var engine = this._scene.getEngine();
  29083. this._cachedDepthWriteState = engine.getDepthWrite();
  29084. engine.setDepthWrite(false);
  29085. }
  29086. };
  29087. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29088. };
  29089. Material.prototype.unbind = function () {
  29090. this.onUnBindObservable.notifyObservers(this);
  29091. if (this.disableDepthWrite) {
  29092. var engine = this._scene.getEngine();
  29093. engine.setDepthWrite(this._cachedDepthWriteState);
  29094. }
  29095. };
  29096. Material.prototype.clone = function (name) {
  29097. return null;
  29098. };
  29099. Material.prototype.getBindedMeshes = function () {
  29100. var result = new Array();
  29101. for (var index = 0; index < this._scene.meshes.length; index++) {
  29102. var mesh = this._scene.meshes[index];
  29103. if (mesh.material === this) {
  29104. result.push(mesh);
  29105. }
  29106. }
  29107. return result;
  29108. };
  29109. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29110. // Animations
  29111. this.getScene().stopAnimation(this);
  29112. // Remove from scene
  29113. var index = this._scene.materials.indexOf(this);
  29114. if (index >= 0) {
  29115. this._scene.materials.splice(index, 1);
  29116. }
  29117. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29118. if (forceDisposeEffect && this._effect) {
  29119. this._scene.getEngine()._releaseEffect(this._effect);
  29120. this._effect = null;
  29121. }
  29122. // Remove from meshes
  29123. for (index = 0; index < this._scene.meshes.length; index++) {
  29124. var mesh = this._scene.meshes[index];
  29125. if (mesh.material === this) {
  29126. mesh.material = null;
  29127. }
  29128. }
  29129. // Callback
  29130. this.onDisposeObservable.notifyObservers(this);
  29131. this.onDisposeObservable.clear();
  29132. this.onBindObservable.clear();
  29133. this.onUnBindObservable.clear();
  29134. };
  29135. Material.prototype.serialize = function () {
  29136. return BABYLON.SerializationHelper.Serialize(this);
  29137. };
  29138. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29139. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29140. multiMaterial.id = parsedMultiMaterial.id;
  29141. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29142. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29143. var subMatId = parsedMultiMaterial.materials[matIndex];
  29144. if (subMatId) {
  29145. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29146. }
  29147. else {
  29148. multiMaterial.subMaterials.push(null);
  29149. }
  29150. }
  29151. return multiMaterial;
  29152. };
  29153. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29154. if (!parsedMaterial.customType) {
  29155. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29156. }
  29157. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29158. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29159. ;
  29160. };
  29161. return Material;
  29162. }());
  29163. Material._TriangleFillMode = 0;
  29164. Material._WireFrameFillMode = 1;
  29165. Material._PointFillMode = 2;
  29166. Material._ClockWiseSideOrientation = 0;
  29167. Material._CounterClockWiseSideOrientation = 1;
  29168. __decorate([
  29169. BABYLON.serialize()
  29170. ], Material.prototype, "id", void 0);
  29171. __decorate([
  29172. BABYLON.serialize()
  29173. ], Material.prototype, "name", void 0);
  29174. __decorate([
  29175. BABYLON.serialize()
  29176. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29177. __decorate([
  29178. BABYLON.serialize()
  29179. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29180. __decorate([
  29181. BABYLON.serialize()
  29182. ], Material.prototype, "state", void 0);
  29183. __decorate([
  29184. BABYLON.serialize()
  29185. ], Material.prototype, "alpha", void 0);
  29186. __decorate([
  29187. BABYLON.serialize()
  29188. ], Material.prototype, "backFaceCulling", void 0);
  29189. __decorate([
  29190. BABYLON.serialize()
  29191. ], Material.prototype, "sideOrientation", void 0);
  29192. __decorate([
  29193. BABYLON.serialize()
  29194. ], Material.prototype, "alphaMode", void 0);
  29195. __decorate([
  29196. BABYLON.serialize()
  29197. ], Material.prototype, "disableDepthWrite", void 0);
  29198. __decorate([
  29199. BABYLON.serialize()
  29200. ], Material.prototype, "fogEnabled", void 0);
  29201. __decorate([
  29202. BABYLON.serialize()
  29203. ], Material.prototype, "pointSize", void 0);
  29204. __decorate([
  29205. BABYLON.serialize()
  29206. ], Material.prototype, "zOffset", void 0);
  29207. __decorate([
  29208. BABYLON.serialize()
  29209. ], Material.prototype, "wireframe", null);
  29210. __decorate([
  29211. BABYLON.serialize()
  29212. ], Material.prototype, "pointsCloud", null);
  29213. __decorate([
  29214. BABYLON.serialize()
  29215. ], Material.prototype, "fillMode", null);
  29216. BABYLON.Material = Material;
  29217. })(BABYLON || (BABYLON = {}));
  29218. //# sourceMappingURL=babylon.material.js.map
  29219. var BABYLON;
  29220. (function (BABYLON) {
  29221. var StandardMaterialDefines = (function (_super) {
  29222. __extends(StandardMaterialDefines, _super);
  29223. function StandardMaterialDefines() {
  29224. var _this = _super.call(this) || this;
  29225. _this.DIFFUSE = false;
  29226. _this.AMBIENT = false;
  29227. _this.OPACITY = false;
  29228. _this.OPACITYRGB = false;
  29229. _this.REFLECTION = false;
  29230. _this.EMISSIVE = false;
  29231. _this.SPECULAR = false;
  29232. _this.BUMP = false;
  29233. _this.PARALLAX = false;
  29234. _this.PARALLAXOCCLUSION = false;
  29235. _this.SPECULAROVERALPHA = false;
  29236. _this.CLIPPLANE = false;
  29237. _this.ALPHATEST = false;
  29238. _this.ALPHAFROMDIFFUSE = false;
  29239. _this.POINTSIZE = false;
  29240. _this.FOG = false;
  29241. _this.SPECULARTERM = false;
  29242. _this.DIFFUSEFRESNEL = false;
  29243. _this.OPACITYFRESNEL = false;
  29244. _this.REFLECTIONFRESNEL = false;
  29245. _this.REFRACTIONFRESNEL = false;
  29246. _this.EMISSIVEFRESNEL = false;
  29247. _this.FRESNEL = false;
  29248. _this.NORMAL = false;
  29249. _this.UV1 = false;
  29250. _this.UV2 = false;
  29251. _this.VERTEXCOLOR = false;
  29252. _this.VERTEXALPHA = false;
  29253. _this.NUM_BONE_INFLUENCERS = 0;
  29254. _this.BonesPerMesh = 0;
  29255. _this.INSTANCES = false;
  29256. _this.GLOSSINESS = false;
  29257. _this.ROUGHNESS = false;
  29258. _this.EMISSIVEASILLUMINATION = false;
  29259. _this.LINKEMISSIVEWITHDIFFUSE = false;
  29260. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  29261. _this.LIGHTMAP = false;
  29262. _this.USELIGHTMAPASSHADOWMAP = false;
  29263. _this.REFLECTIONMAP_3D = false;
  29264. _this.REFLECTIONMAP_SPHERICAL = false;
  29265. _this.REFLECTIONMAP_PLANAR = false;
  29266. _this.REFLECTIONMAP_CUBIC = false;
  29267. _this.REFLECTIONMAP_PROJECTION = false;
  29268. _this.REFLECTIONMAP_SKYBOX = false;
  29269. _this.REFLECTIONMAP_EXPLICIT = false;
  29270. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  29271. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  29272. _this.INVERTCUBICMAP = false;
  29273. _this.LOGARITHMICDEPTH = false;
  29274. _this.REFRACTION = false;
  29275. _this.REFRACTIONMAP_3D = false;
  29276. _this.REFLECTIONOVERALPHA = false;
  29277. _this.INVERTNORMALMAPX = false;
  29278. _this.INVERTNORMALMAPY = false;
  29279. _this.SHADOWFULLFLOAT = false;
  29280. _this.CAMERACOLORGRADING = false;
  29281. _this.CAMERACOLORCURVES = false;
  29282. _this.rebuild();
  29283. return _this;
  29284. }
  29285. return StandardMaterialDefines;
  29286. }(BABYLON.MaterialDefines));
  29287. var StandardMaterial = (function (_super) {
  29288. __extends(StandardMaterial, _super);
  29289. function StandardMaterial(name, scene) {
  29290. var _this = _super.call(this, name, scene) || this;
  29291. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  29292. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  29293. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  29294. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  29295. _this.specularPower = 64;
  29296. _this.useAlphaFromDiffuseTexture = false;
  29297. _this.useEmissiveAsIllumination = false;
  29298. _this.linkEmissiveWithDiffuse = false;
  29299. _this.useReflectionFresnelFromSpecular = false;
  29300. _this.useSpecularOverAlpha = false;
  29301. _this.useReflectionOverAlpha = false;
  29302. _this.disableLighting = false;
  29303. _this.useParallax = false;
  29304. _this.useParallaxOcclusion = false;
  29305. _this.parallaxScaleBias = 0.05;
  29306. _this.roughness = 0;
  29307. _this.indexOfRefraction = 0.98;
  29308. _this.invertRefractionY = true;
  29309. _this.useLightmapAsShadowmap = false;
  29310. _this.useGlossinessFromSpecularMapAlpha = false;
  29311. _this.maxSimultaneousLights = 4;
  29312. /**
  29313. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  29314. */
  29315. _this.invertNormalMapX = false;
  29316. /**
  29317. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  29318. */
  29319. _this.invertNormalMapY = false;
  29320. /**
  29321. * Color Grading 2D Lookup Texture.
  29322. * This allows special effects like sepia, black and white to sixties rendering style.
  29323. */
  29324. _this.cameraColorGradingTexture = null;
  29325. /**
  29326. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  29327. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  29328. * 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;
  29329. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  29330. */
  29331. _this.cameraColorCurves = null;
  29332. _this._renderTargets = new BABYLON.SmartArray(16);
  29333. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  29334. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  29335. _this._defines = new StandardMaterialDefines();
  29336. _this._cachedDefines = new StandardMaterialDefines();
  29337. _this._cachedDefines.BonesPerMesh = -1;
  29338. _this.getRenderTargetTextures = function () {
  29339. _this._renderTargets.reset();
  29340. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  29341. _this._renderTargets.push(_this.reflectionTexture);
  29342. }
  29343. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  29344. _this._renderTargets.push(_this.refractionTexture);
  29345. }
  29346. return _this._renderTargets;
  29347. };
  29348. return _this;
  29349. }
  29350. StandardMaterial.prototype.getClassName = function () {
  29351. return "StandardMaterial";
  29352. };
  29353. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  29354. get: function () {
  29355. return this._useLogarithmicDepth;
  29356. },
  29357. set: function (value) {
  29358. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  29359. },
  29360. enumerable: true,
  29361. configurable: true
  29362. });
  29363. StandardMaterial.prototype.needAlphaBlending = function () {
  29364. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  29365. };
  29366. StandardMaterial.prototype.needAlphaTesting = function () {
  29367. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  29368. };
  29369. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  29370. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  29371. };
  29372. StandardMaterial.prototype.getAlphaTestTexture = function () {
  29373. return this.diffuseTexture;
  29374. };
  29375. // Methods
  29376. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  29377. if (!mesh) {
  29378. return true;
  29379. }
  29380. if (this._defines.INSTANCES !== useInstances) {
  29381. return false;
  29382. }
  29383. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  29384. return true;
  29385. }
  29386. return false;
  29387. };
  29388. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  29389. if (this.isFrozen) {
  29390. if (this._wasPreviouslyReady) {
  29391. return true;
  29392. }
  29393. }
  29394. var scene = this.getScene();
  29395. var engine = scene.getEngine();
  29396. var needUVs = false;
  29397. var needNormals = false;
  29398. this._defines.reset();
  29399. // Lights
  29400. if (scene.lightsEnabled && !this.disableLighting) {
  29401. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  29402. }
  29403. if (!this.checkReadyOnEveryCall) {
  29404. if (this._renderId === scene.getRenderId()) {
  29405. if (this._checkCache(scene, mesh, useInstances)) {
  29406. return true;
  29407. }
  29408. }
  29409. }
  29410. // Textures
  29411. if (scene.texturesEnabled) {
  29412. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29413. if (!this.diffuseTexture.isReady()) {
  29414. return false;
  29415. }
  29416. else {
  29417. needUVs = true;
  29418. this._defines.DIFFUSE = true;
  29419. }
  29420. }
  29421. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29422. if (!this.ambientTexture.isReady()) {
  29423. return false;
  29424. }
  29425. else {
  29426. needUVs = true;
  29427. this._defines.AMBIENT = true;
  29428. }
  29429. }
  29430. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29431. if (!this.opacityTexture.isReady()) {
  29432. return false;
  29433. }
  29434. else {
  29435. needUVs = true;
  29436. this._defines.OPACITY = true;
  29437. if (this.opacityTexture.getAlphaFromRGB) {
  29438. this._defines.OPACITYRGB = true;
  29439. }
  29440. }
  29441. }
  29442. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  29443. if (!this.reflectionTexture.isReady()) {
  29444. return false;
  29445. }
  29446. else {
  29447. needNormals = true;
  29448. this._defines.REFLECTION = true;
  29449. if (this.roughness > 0) {
  29450. this._defines.ROUGHNESS = true;
  29451. }
  29452. if (this.useReflectionOverAlpha) {
  29453. this._defines.REFLECTIONOVERALPHA = true;
  29454. }
  29455. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  29456. this._defines.INVERTCUBICMAP = true;
  29457. }
  29458. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  29459. switch (this.reflectionTexture.coordinatesMode) {
  29460. case BABYLON.Texture.CUBIC_MODE:
  29461. case BABYLON.Texture.INVCUBIC_MODE:
  29462. this._defines.REFLECTIONMAP_CUBIC = true;
  29463. break;
  29464. case BABYLON.Texture.EXPLICIT_MODE:
  29465. this._defines.REFLECTIONMAP_EXPLICIT = true;
  29466. break;
  29467. case BABYLON.Texture.PLANAR_MODE:
  29468. this._defines.REFLECTIONMAP_PLANAR = true;
  29469. break;
  29470. case BABYLON.Texture.PROJECTION_MODE:
  29471. this._defines.REFLECTIONMAP_PROJECTION = true;
  29472. break;
  29473. case BABYLON.Texture.SKYBOX_MODE:
  29474. this._defines.REFLECTIONMAP_SKYBOX = true;
  29475. break;
  29476. case BABYLON.Texture.SPHERICAL_MODE:
  29477. this._defines.REFLECTIONMAP_SPHERICAL = true;
  29478. break;
  29479. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  29480. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  29481. break;
  29482. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  29483. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  29484. break;
  29485. }
  29486. }
  29487. }
  29488. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  29489. if (!this.emissiveTexture.isReady()) {
  29490. return false;
  29491. }
  29492. else {
  29493. needUVs = true;
  29494. this._defines.EMISSIVE = true;
  29495. }
  29496. }
  29497. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  29498. if (!this.lightmapTexture.isReady()) {
  29499. return false;
  29500. }
  29501. else {
  29502. needUVs = true;
  29503. this._defines.LIGHTMAP = true;
  29504. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  29505. }
  29506. }
  29507. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  29508. if (!this.specularTexture.isReady()) {
  29509. return false;
  29510. }
  29511. else {
  29512. needUVs = true;
  29513. this._defines.SPECULAR = true;
  29514. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  29515. }
  29516. }
  29517. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  29518. if (!this.bumpTexture.isReady()) {
  29519. return false;
  29520. }
  29521. else {
  29522. needUVs = true;
  29523. this._defines.BUMP = true;
  29524. if (this.useParallax) {
  29525. this._defines.PARALLAX = true;
  29526. if (this.useParallaxOcclusion) {
  29527. this._defines.PARALLAXOCCLUSION = true;
  29528. }
  29529. }
  29530. if (this.invertNormalMapX) {
  29531. this._defines.INVERTNORMALMAPX = true;
  29532. }
  29533. if (this.invertNormalMapY) {
  29534. this._defines.INVERTNORMALMAPY = true;
  29535. }
  29536. if (scene._mirroredCameraPosition) {
  29537. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  29538. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  29539. }
  29540. }
  29541. }
  29542. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  29543. if (!this.refractionTexture.isReady()) {
  29544. return false;
  29545. }
  29546. else {
  29547. needUVs = true;
  29548. this._defines.REFRACTION = true;
  29549. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  29550. }
  29551. }
  29552. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  29553. if (!this.cameraColorGradingTexture.isReady()) {
  29554. return false;
  29555. }
  29556. else {
  29557. this._defines.CAMERACOLORGRADING = true;
  29558. }
  29559. }
  29560. }
  29561. // Effect
  29562. if (scene.clipPlane) {
  29563. this._defines.CLIPPLANE = true;
  29564. }
  29565. if (engine.getAlphaTesting()) {
  29566. this._defines.ALPHATEST = true;
  29567. }
  29568. if (this._shouldUseAlphaFromDiffuseTexture()) {
  29569. this._defines.ALPHAFROMDIFFUSE = true;
  29570. }
  29571. if (this.useEmissiveAsIllumination) {
  29572. this._defines.EMISSIVEASILLUMINATION = true;
  29573. }
  29574. if (this.linkEmissiveWithDiffuse) {
  29575. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  29576. }
  29577. if (this.useLogarithmicDepth) {
  29578. this._defines.LOGARITHMICDEPTH = true;
  29579. }
  29580. if (this.cameraColorCurves) {
  29581. this._defines.CAMERACOLORCURVES = true;
  29582. }
  29583. // Point size
  29584. if (this.pointsCloud || scene.forcePointsCloud) {
  29585. this._defines.POINTSIZE = true;
  29586. }
  29587. // Fog
  29588. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  29589. this._defines.FOG = true;
  29590. }
  29591. if (StandardMaterial.FresnelEnabled) {
  29592. // Fresnel
  29593. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  29594. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  29595. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  29596. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  29597. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  29598. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  29599. this._defines.DIFFUSEFRESNEL = true;
  29600. }
  29601. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29602. this._defines.OPACITYFRESNEL = true;
  29603. }
  29604. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  29605. this._defines.REFLECTIONFRESNEL = true;
  29606. if (this.useReflectionFresnelFromSpecular) {
  29607. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  29608. }
  29609. }
  29610. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  29611. this._defines.REFRACTIONFRESNEL = true;
  29612. }
  29613. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29614. this._defines.EMISSIVEFRESNEL = true;
  29615. }
  29616. needNormals = true;
  29617. this._defines.FRESNEL = true;
  29618. }
  29619. }
  29620. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  29621. this._defines.SPECULAROVERALPHA = true;
  29622. }
  29623. // Attribs
  29624. if (mesh) {
  29625. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29626. this._defines.NORMAL = true;
  29627. }
  29628. if (needUVs) {
  29629. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29630. this._defines.UV1 = true;
  29631. }
  29632. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29633. this._defines.UV2 = true;
  29634. }
  29635. }
  29636. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29637. this._defines.VERTEXCOLOR = true;
  29638. if (mesh.hasVertexAlpha) {
  29639. this._defines.VERTEXALPHA = true;
  29640. }
  29641. }
  29642. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29643. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  29644. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  29645. }
  29646. // Instances
  29647. if (useInstances) {
  29648. this._defines.INSTANCES = true;
  29649. }
  29650. }
  29651. // Get correct effect
  29652. if (!this._defines.isEqual(this._cachedDefines)) {
  29653. this._defines.cloneTo(this._cachedDefines);
  29654. scene.resetCachedMaterial();
  29655. // Fallbacks
  29656. var fallbacks = new BABYLON.EffectFallbacks();
  29657. if (this._defines.REFLECTION) {
  29658. fallbacks.addFallback(0, "REFLECTION");
  29659. }
  29660. if (this._defines.SPECULAR) {
  29661. fallbacks.addFallback(0, "SPECULAR");
  29662. }
  29663. if (this._defines.BUMP) {
  29664. fallbacks.addFallback(0, "BUMP");
  29665. }
  29666. if (this._defines.PARALLAX) {
  29667. fallbacks.addFallback(1, "PARALLAX");
  29668. }
  29669. if (this._defines.PARALLAXOCCLUSION) {
  29670. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  29671. }
  29672. if (this._defines.SPECULAROVERALPHA) {
  29673. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  29674. }
  29675. if (this._defines.FOG) {
  29676. fallbacks.addFallback(1, "FOG");
  29677. }
  29678. if (this._defines.POINTSIZE) {
  29679. fallbacks.addFallback(0, "POINTSIZE");
  29680. }
  29681. if (this._defines.LOGARITHMICDEPTH) {
  29682. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  29683. }
  29684. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  29685. if (this._defines.SPECULARTERM) {
  29686. fallbacks.addFallback(0, "SPECULARTERM");
  29687. }
  29688. if (this._defines.DIFFUSEFRESNEL) {
  29689. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  29690. }
  29691. if (this._defines.OPACITYFRESNEL) {
  29692. fallbacks.addFallback(2, "OPACITYFRESNEL");
  29693. }
  29694. if (this._defines.REFLECTIONFRESNEL) {
  29695. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  29696. }
  29697. if (this._defines.EMISSIVEFRESNEL) {
  29698. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  29699. }
  29700. if (this._defines.FRESNEL) {
  29701. fallbacks.addFallback(4, "FRESNEL");
  29702. }
  29703. //Attributes
  29704. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29705. if (this._defines.NORMAL) {
  29706. attribs.push(BABYLON.VertexBuffer.NormalKind);
  29707. }
  29708. if (this._defines.UV1) {
  29709. attribs.push(BABYLON.VertexBuffer.UVKind);
  29710. }
  29711. if (this._defines.UV2) {
  29712. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29713. }
  29714. if (this._defines.VERTEXCOLOR) {
  29715. attribs.push(BABYLON.VertexBuffer.ColorKind);
  29716. }
  29717. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  29718. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  29719. var shaderName = "default";
  29720. var join = this._defines.toString();
  29721. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  29722. "vFogInfos", "vFogColor", "pointSize",
  29723. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  29724. "mBones",
  29725. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  29726. "depthValues",
  29727. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  29728. "logarithmicDepthConstant"
  29729. ];
  29730. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  29731. if (this._defines.CAMERACOLORCURVES) {
  29732. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  29733. }
  29734. if (this._defines.CAMERACOLORGRADING) {
  29735. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  29736. }
  29737. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  29738. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  29739. }
  29740. if (!this._effect.isReady()) {
  29741. return false;
  29742. }
  29743. this._renderId = scene.getRenderId();
  29744. this._wasPreviouslyReady = true;
  29745. if (mesh) {
  29746. if (!mesh._materialDefines) {
  29747. mesh._materialDefines = new StandardMaterialDefines();
  29748. }
  29749. this._defines.cloneTo(mesh._materialDefines);
  29750. }
  29751. return true;
  29752. };
  29753. StandardMaterial.prototype.unbind = function () {
  29754. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  29755. this._effect.setTexture("reflection2DSampler", null);
  29756. }
  29757. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  29758. this._effect.setTexture("refraction2DSampler", null);
  29759. }
  29760. _super.prototype.unbind.call(this);
  29761. };
  29762. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  29763. this._effect.setMatrix("world", world);
  29764. };
  29765. StandardMaterial.prototype.bind = function (world, mesh) {
  29766. var scene = this.getScene();
  29767. // Matrices
  29768. this.bindOnlyWorldMatrix(world);
  29769. // Bones
  29770. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  29771. if (scene.getCachedMaterial() !== this) {
  29772. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29773. if (StandardMaterial.FresnelEnabled) {
  29774. // Fresnel
  29775. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  29776. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  29777. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  29778. }
  29779. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29780. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  29781. }
  29782. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  29783. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  29784. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  29785. }
  29786. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  29787. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  29788. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  29789. }
  29790. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29791. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  29792. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  29793. }
  29794. }
  29795. // Textures
  29796. if (scene.texturesEnabled) {
  29797. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29798. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  29799. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  29800. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  29801. }
  29802. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29803. this._effect.setTexture("ambientSampler", this.ambientTexture);
  29804. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  29805. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  29806. }
  29807. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29808. this._effect.setTexture("opacitySampler", this.opacityTexture);
  29809. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  29810. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  29811. }
  29812. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  29813. if (this.reflectionTexture.isCube) {
  29814. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  29815. }
  29816. else {
  29817. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  29818. }
  29819. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  29820. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  29821. }
  29822. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  29823. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  29824. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  29825. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  29826. }
  29827. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  29828. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  29829. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  29830. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  29831. }
  29832. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  29833. this._effect.setTexture("specularSampler", this.specularTexture);
  29834. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  29835. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  29836. }
  29837. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  29838. this._effect.setTexture("bumpSampler", this.bumpTexture);
  29839. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  29840. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  29841. }
  29842. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  29843. var depth = 1.0;
  29844. if (this.refractionTexture.isCube) {
  29845. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  29846. }
  29847. else {
  29848. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  29849. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  29850. if (this.refractionTexture.depth) {
  29851. depth = this.refractionTexture.depth;
  29852. }
  29853. }
  29854. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  29855. }
  29856. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  29857. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  29858. }
  29859. }
  29860. // Clip plane
  29861. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  29862. // Point size
  29863. if (this.pointsCloud) {
  29864. this._effect.setFloat("pointSize", this.pointSize);
  29865. }
  29866. // Colors
  29867. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  29868. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  29869. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  29870. if (this._defines.SPECULARTERM) {
  29871. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  29872. }
  29873. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  29874. }
  29875. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  29876. // Diffuse
  29877. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  29878. // Lights
  29879. if (scene.lightsEnabled && !this.disableLighting) {
  29880. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  29881. }
  29882. // View
  29883. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  29884. this._effect.setMatrix("view", scene.getViewMatrix());
  29885. }
  29886. // Fog
  29887. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  29888. // Log. depth
  29889. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  29890. // Color Curves
  29891. if (this.cameraColorCurves) {
  29892. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  29893. }
  29894. }
  29895. _super.prototype.bind.call(this, world, mesh);
  29896. };
  29897. StandardMaterial.prototype.getAnimatables = function () {
  29898. var results = [];
  29899. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  29900. results.push(this.diffuseTexture);
  29901. }
  29902. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  29903. results.push(this.ambientTexture);
  29904. }
  29905. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  29906. results.push(this.opacityTexture);
  29907. }
  29908. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  29909. results.push(this.reflectionTexture);
  29910. }
  29911. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  29912. results.push(this.emissiveTexture);
  29913. }
  29914. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  29915. results.push(this.specularTexture);
  29916. }
  29917. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  29918. results.push(this.bumpTexture);
  29919. }
  29920. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  29921. results.push(this.lightmapTexture);
  29922. }
  29923. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  29924. results.push(this.refractionTexture);
  29925. }
  29926. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  29927. results.push(this.cameraColorGradingTexture);
  29928. }
  29929. return results;
  29930. };
  29931. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29932. if (forceDisposeTextures) {
  29933. if (this.diffuseTexture) {
  29934. this.diffuseTexture.dispose();
  29935. }
  29936. if (this.ambientTexture) {
  29937. this.ambientTexture.dispose();
  29938. }
  29939. if (this.opacityTexture) {
  29940. this.opacityTexture.dispose();
  29941. }
  29942. if (this.reflectionTexture) {
  29943. this.reflectionTexture.dispose();
  29944. }
  29945. if (this.emissiveTexture) {
  29946. this.emissiveTexture.dispose();
  29947. }
  29948. if (this.specularTexture) {
  29949. this.specularTexture.dispose();
  29950. }
  29951. if (this.bumpTexture) {
  29952. this.bumpTexture.dispose();
  29953. }
  29954. if (this.lightmapTexture) {
  29955. this.lightmapTexture.dispose();
  29956. }
  29957. if (this.refractionTexture) {
  29958. this.refractionTexture.dispose();
  29959. }
  29960. if (this.cameraColorGradingTexture) {
  29961. this.cameraColorGradingTexture.dispose();
  29962. }
  29963. }
  29964. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  29965. };
  29966. StandardMaterial.prototype.clone = function (name) {
  29967. var _this = this;
  29968. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  29969. };
  29970. StandardMaterial.prototype.serialize = function () {
  29971. return BABYLON.SerializationHelper.Serialize(this);
  29972. };
  29973. // Statics
  29974. StandardMaterial.Parse = function (source, scene, rootUrl) {
  29975. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  29976. };
  29977. return StandardMaterial;
  29978. }(BABYLON.Material));
  29979. // Flags used to enable or disable a type of texture for all Standard Materials
  29980. StandardMaterial.DiffuseTextureEnabled = true;
  29981. StandardMaterial.AmbientTextureEnabled = true;
  29982. StandardMaterial.OpacityTextureEnabled = true;
  29983. StandardMaterial.ReflectionTextureEnabled = true;
  29984. StandardMaterial.EmissiveTextureEnabled = true;
  29985. StandardMaterial.SpecularTextureEnabled = true;
  29986. StandardMaterial.BumpTextureEnabled = true;
  29987. StandardMaterial.FresnelEnabled = true;
  29988. StandardMaterial.LightmapTextureEnabled = true;
  29989. StandardMaterial.RefractionTextureEnabled = true;
  29990. StandardMaterial.ColorGradingTextureEnabled = true;
  29991. __decorate([
  29992. BABYLON.serializeAsTexture()
  29993. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  29994. __decorate([
  29995. BABYLON.serializeAsTexture()
  29996. ], StandardMaterial.prototype, "ambientTexture", void 0);
  29997. __decorate([
  29998. BABYLON.serializeAsTexture()
  29999. ], StandardMaterial.prototype, "opacityTexture", void 0);
  30000. __decorate([
  30001. BABYLON.serializeAsTexture()
  30002. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  30003. __decorate([
  30004. BABYLON.serializeAsTexture()
  30005. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  30006. __decorate([
  30007. BABYLON.serializeAsTexture()
  30008. ], StandardMaterial.prototype, "specularTexture", void 0);
  30009. __decorate([
  30010. BABYLON.serializeAsTexture()
  30011. ], StandardMaterial.prototype, "bumpTexture", void 0);
  30012. __decorate([
  30013. BABYLON.serializeAsTexture()
  30014. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  30015. __decorate([
  30016. BABYLON.serializeAsTexture()
  30017. ], StandardMaterial.prototype, "refractionTexture", void 0);
  30018. __decorate([
  30019. BABYLON.serializeAsColor3("ambient")
  30020. ], StandardMaterial.prototype, "ambientColor", void 0);
  30021. __decorate([
  30022. BABYLON.serializeAsColor3("diffuse")
  30023. ], StandardMaterial.prototype, "diffuseColor", void 0);
  30024. __decorate([
  30025. BABYLON.serializeAsColor3("specular")
  30026. ], StandardMaterial.prototype, "specularColor", void 0);
  30027. __decorate([
  30028. BABYLON.serializeAsColor3("emissive")
  30029. ], StandardMaterial.prototype, "emissiveColor", void 0);
  30030. __decorate([
  30031. BABYLON.serialize()
  30032. ], StandardMaterial.prototype, "specularPower", void 0);
  30033. __decorate([
  30034. BABYLON.serialize()
  30035. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  30036. __decorate([
  30037. BABYLON.serialize()
  30038. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  30039. __decorate([
  30040. BABYLON.serialize()
  30041. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  30042. __decorate([
  30043. BABYLON.serialize()
  30044. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  30045. __decorate([
  30046. BABYLON.serialize()
  30047. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  30048. __decorate([
  30049. BABYLON.serialize()
  30050. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  30051. __decorate([
  30052. BABYLON.serialize()
  30053. ], StandardMaterial.prototype, "disableLighting", void 0);
  30054. __decorate([
  30055. BABYLON.serialize()
  30056. ], StandardMaterial.prototype, "useParallax", void 0);
  30057. __decorate([
  30058. BABYLON.serialize()
  30059. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  30060. __decorate([
  30061. BABYLON.serialize()
  30062. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  30063. __decorate([
  30064. BABYLON.serialize()
  30065. ], StandardMaterial.prototype, "roughness", void 0);
  30066. __decorate([
  30067. BABYLON.serialize()
  30068. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  30069. __decorate([
  30070. BABYLON.serialize()
  30071. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  30072. __decorate([
  30073. BABYLON.serialize()
  30074. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  30075. __decorate([
  30076. BABYLON.serializeAsFresnelParameters()
  30077. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  30078. __decorate([
  30079. BABYLON.serializeAsFresnelParameters()
  30080. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  30081. __decorate([
  30082. BABYLON.serializeAsFresnelParameters()
  30083. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  30084. __decorate([
  30085. BABYLON.serializeAsFresnelParameters()
  30086. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  30087. __decorate([
  30088. BABYLON.serializeAsFresnelParameters()
  30089. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  30090. __decorate([
  30091. BABYLON.serialize()
  30092. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  30093. __decorate([
  30094. BABYLON.serialize()
  30095. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  30096. __decorate([
  30097. BABYLON.serialize()
  30098. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  30099. __decorate([
  30100. BABYLON.serialize()
  30101. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  30102. __decorate([
  30103. BABYLON.serializeAsTexture()
  30104. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  30105. __decorate([
  30106. BABYLON.serializeAsColorCurves()
  30107. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  30108. __decorate([
  30109. BABYLON.serialize()
  30110. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  30111. BABYLON.StandardMaterial = StandardMaterial;
  30112. })(BABYLON || (BABYLON = {}));
  30113. //# sourceMappingURL=babylon.standardMaterial.js.map
  30114. var BABYLON;
  30115. (function (BABYLON) {
  30116. var MultiMaterial = (function (_super) {
  30117. __extends(MultiMaterial, _super);
  30118. function MultiMaterial(name, scene) {
  30119. var _this = _super.call(this, name, scene, true) || this;
  30120. _this.subMaterials = new Array();
  30121. scene.multiMaterials.push(_this);
  30122. return _this;
  30123. }
  30124. // Properties
  30125. MultiMaterial.prototype.getSubMaterial = function (index) {
  30126. if (index < 0 || index >= this.subMaterials.length) {
  30127. return this.getScene().defaultMaterial;
  30128. }
  30129. return this.subMaterials[index];
  30130. };
  30131. // Methods
  30132. MultiMaterial.prototype.getClassName = function () {
  30133. return "MultiMaterial";
  30134. };
  30135. MultiMaterial.prototype.isReady = function (mesh) {
  30136. for (var index = 0; index < this.subMaterials.length; index++) {
  30137. var subMaterial = this.subMaterials[index];
  30138. if (subMaterial) {
  30139. if (!this.subMaterials[index].isReady(mesh)) {
  30140. return false;
  30141. }
  30142. }
  30143. }
  30144. return true;
  30145. };
  30146. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  30147. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  30148. for (var index = 0; index < this.subMaterials.length; index++) {
  30149. var subMaterial = null;
  30150. if (cloneChildren) {
  30151. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  30152. }
  30153. else {
  30154. subMaterial = this.subMaterials[index];
  30155. }
  30156. newMultiMaterial.subMaterials.push(subMaterial);
  30157. }
  30158. return newMultiMaterial;
  30159. };
  30160. MultiMaterial.prototype.serialize = function () {
  30161. var serializationObject = {};
  30162. serializationObject.name = this.name;
  30163. serializationObject.id = this.id;
  30164. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30165. serializationObject.materials = [];
  30166. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  30167. var subMat = this.subMaterials[matIndex];
  30168. if (subMat) {
  30169. serializationObject.materials.push(subMat.id);
  30170. }
  30171. else {
  30172. serializationObject.materials.push(null);
  30173. }
  30174. }
  30175. return serializationObject;
  30176. };
  30177. return MultiMaterial;
  30178. }(BABYLON.Material));
  30179. BABYLON.MultiMaterial = MultiMaterial;
  30180. })(BABYLON || (BABYLON = {}));
  30181. //# sourceMappingURL=babylon.multiMaterial.js.map
  30182. var BABYLON;
  30183. (function (BABYLON) {
  30184. var SceneLoader = (function () {
  30185. function SceneLoader() {
  30186. }
  30187. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  30188. get: function () {
  30189. return 0;
  30190. },
  30191. enumerable: true,
  30192. configurable: true
  30193. });
  30194. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  30195. get: function () {
  30196. return 1;
  30197. },
  30198. enumerable: true,
  30199. configurable: true
  30200. });
  30201. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  30202. get: function () {
  30203. return 2;
  30204. },
  30205. enumerable: true,
  30206. configurable: true
  30207. });
  30208. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  30209. get: function () {
  30210. return 3;
  30211. },
  30212. enumerable: true,
  30213. configurable: true
  30214. });
  30215. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  30216. get: function () {
  30217. return SceneLoader._ForceFullSceneLoadingForIncremental;
  30218. },
  30219. set: function (value) {
  30220. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  30221. },
  30222. enumerable: true,
  30223. configurable: true
  30224. });
  30225. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  30226. get: function () {
  30227. return SceneLoader._ShowLoadingScreen;
  30228. },
  30229. set: function (value) {
  30230. SceneLoader._ShowLoadingScreen = value;
  30231. },
  30232. enumerable: true,
  30233. configurable: true
  30234. });
  30235. Object.defineProperty(SceneLoader, "loggingLevel", {
  30236. get: function () {
  30237. return SceneLoader._loggingLevel;
  30238. },
  30239. set: function (value) {
  30240. SceneLoader._loggingLevel = value;
  30241. },
  30242. enumerable: true,
  30243. configurable: true
  30244. });
  30245. SceneLoader._getDefaultPlugin = function () {
  30246. return SceneLoader._registeredPlugins[".babylon"];
  30247. };
  30248. SceneLoader._getPluginForExtension = function (extension) {
  30249. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  30250. if (registeredPlugin) {
  30251. return registeredPlugin;
  30252. }
  30253. return SceneLoader._getDefaultPlugin();
  30254. };
  30255. SceneLoader._getPluginForFilename = function (sceneFilename) {
  30256. if (sceneFilename.name) {
  30257. sceneFilename = sceneFilename.name;
  30258. }
  30259. var dotPosition = sceneFilename.lastIndexOf(".");
  30260. var queryStringPosition = sceneFilename.indexOf("?");
  30261. if (queryStringPosition === -1) {
  30262. queryStringPosition = sceneFilename.length;
  30263. }
  30264. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  30265. return SceneLoader._getPluginForExtension(extension);
  30266. };
  30267. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  30268. SceneLoader._getDirectLoad = function (sceneFilename) {
  30269. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  30270. return sceneFilename.substr(5);
  30271. }
  30272. return null;
  30273. };
  30274. // Public functions
  30275. SceneLoader.GetPluginForExtension = function (extension) {
  30276. return SceneLoader._getPluginForExtension(extension).plugin;
  30277. };
  30278. SceneLoader.RegisterPlugin = function (plugin) {
  30279. if (typeof plugin.extensions === "string") {
  30280. var extension = plugin.extensions;
  30281. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  30282. plugin: plugin,
  30283. isBinary: false
  30284. };
  30285. }
  30286. else {
  30287. var extensions = plugin.extensions;
  30288. Object.keys(extensions).forEach(function (extension) {
  30289. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  30290. plugin: plugin,
  30291. isBinary: extensions[extension].isBinary
  30292. };
  30293. });
  30294. }
  30295. };
  30296. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  30297. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  30298. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  30299. return;
  30300. }
  30301. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  30302. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  30303. return;
  30304. }
  30305. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  30306. var loadingToken = {};
  30307. scene._addPendingData(loadingToken);
  30308. var manifestChecked = function (success) {
  30309. scene.database = database;
  30310. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  30311. var plugin = registeredPlugin.plugin;
  30312. var useArrayBuffer = registeredPlugin.isBinary;
  30313. var importMeshFromData = function (data) {
  30314. var meshes = [];
  30315. var particleSystems = [];
  30316. var skeletons = [];
  30317. try {
  30318. if (plugin.importMesh) {
  30319. var syncedPlugin = plugin;
  30320. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  30321. if (onerror) {
  30322. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  30323. }
  30324. scene._removePendingData(loadingToken);
  30325. return;
  30326. }
  30327. if (onsuccess) {
  30328. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  30329. onsuccess(meshes, particleSystems, skeletons);
  30330. scene._removePendingData(loadingToken);
  30331. }
  30332. }
  30333. else {
  30334. var asyncedPlugin = plugin;
  30335. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  30336. if (onsuccess) {
  30337. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  30338. onsuccess(meshes, particleSystems, skeletons);
  30339. scene._removePendingData(loadingToken);
  30340. }
  30341. }, function () {
  30342. if (onerror) {
  30343. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  30344. }
  30345. scene._removePendingData(loadingToken);
  30346. });
  30347. }
  30348. }
  30349. catch (e) {
  30350. if (onerror) {
  30351. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  30352. }
  30353. scene._removePendingData(loadingToken);
  30354. }
  30355. };
  30356. if (directLoad) {
  30357. importMeshFromData(directLoad);
  30358. return;
  30359. }
  30360. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  30361. importMeshFromData(data);
  30362. }, progressCallBack, database, useArrayBuffer);
  30363. };
  30364. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  30365. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  30366. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  30367. }
  30368. else {
  30369. // If the scene is a data stream or offline support is not enabled, it's a direct load
  30370. manifestChecked(true);
  30371. }
  30372. };
  30373. /**
  30374. * Load a scene
  30375. * @param rootUrl a string that defines the root url for scene and resources
  30376. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  30377. * @param engine is the instance of BABYLON.Engine to use to create the scene
  30378. */
  30379. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  30380. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  30381. };
  30382. /**
  30383. * Append a scene
  30384. * @param rootUrl a string that defines the root url for scene and resources
  30385. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  30386. * @param scene is the instance of BABYLON.Scene to append to
  30387. */
  30388. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  30389. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  30390. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  30391. return;
  30392. }
  30393. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  30394. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  30395. var plugin = registeredPlugin.plugin;
  30396. var useArrayBuffer = registeredPlugin.isBinary;
  30397. var database;
  30398. var loadingToken = {};
  30399. scene._addPendingData(loadingToken);
  30400. if (SceneLoader.ShowLoadingScreen) {
  30401. scene.getEngine().displayLoadingUI();
  30402. }
  30403. var loadSceneFromData = function (data) {
  30404. scene.database = database;
  30405. if (plugin.load) {
  30406. var syncedPlugin = plugin;
  30407. if (!syncedPlugin.load(scene, data, rootUrl)) {
  30408. if (onerror) {
  30409. onerror(scene);
  30410. }
  30411. scene._removePendingData(loadingToken);
  30412. scene.getEngine().hideLoadingUI();
  30413. return;
  30414. }
  30415. if (onsuccess) {
  30416. onsuccess(scene);
  30417. }
  30418. scene._removePendingData(loadingToken);
  30419. }
  30420. else {
  30421. var asyncedPlugin = plugin;
  30422. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  30423. if (onsuccess) {
  30424. onsuccess(scene);
  30425. }
  30426. scene._removePendingData(loadingToken);
  30427. }, function () {
  30428. if (onerror) {
  30429. onerror(scene);
  30430. }
  30431. scene._removePendingData(loadingToken);
  30432. scene.getEngine().hideLoadingUI();
  30433. });
  30434. }
  30435. if (SceneLoader.ShowLoadingScreen) {
  30436. scene.executeWhenReady(function () {
  30437. scene.getEngine().hideLoadingUI();
  30438. });
  30439. }
  30440. };
  30441. var manifestChecked = function (success) {
  30442. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  30443. };
  30444. if (directLoad) {
  30445. loadSceneFromData(directLoad);
  30446. return;
  30447. }
  30448. if (rootUrl.indexOf("file:") === -1) {
  30449. if (scene.getEngine().enableOfflineSupport) {
  30450. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  30451. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  30452. }
  30453. else {
  30454. manifestChecked(true);
  30455. }
  30456. }
  30457. else {
  30458. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  30459. }
  30460. };
  30461. return SceneLoader;
  30462. }());
  30463. // Flags
  30464. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  30465. SceneLoader._ShowLoadingScreen = true;
  30466. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  30467. // Members
  30468. SceneLoader._registeredPlugins = {};
  30469. BABYLON.SceneLoader = SceneLoader;
  30470. ;
  30471. })(BABYLON || (BABYLON = {}));
  30472. //# sourceMappingURL=babylon.sceneLoader.js.map
  30473. var BABYLON;
  30474. (function (BABYLON) {
  30475. var Internals;
  30476. (function (Internals) {
  30477. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  30478. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  30479. var parsedMaterial = parsedData.materials[index];
  30480. if (parsedMaterial.id === id) {
  30481. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  30482. }
  30483. }
  30484. return null;
  30485. };
  30486. var isDescendantOf = function (mesh, names, hierarchyIds) {
  30487. names = (names instanceof Array) ? names : [names];
  30488. for (var i in names) {
  30489. if (mesh.name === names[i]) {
  30490. hierarchyIds.push(mesh.id);
  30491. return true;
  30492. }
  30493. }
  30494. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  30495. hierarchyIds.push(mesh.id);
  30496. return true;
  30497. }
  30498. return false;
  30499. };
  30500. var logOperation = function (operation, producer) {
  30501. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  30502. };
  30503. BABYLON.SceneLoader.RegisterPlugin({
  30504. extensions: ".babylon",
  30505. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  30506. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  30507. // when SceneLoader.debugLogging = true (default), or exception encountered.
  30508. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  30509. // and avoid problems with multiple concurrent .babylon loads.
  30510. var log = "importMesh has failed JSON parse";
  30511. try {
  30512. var parsedData = JSON.parse(data);
  30513. log = "";
  30514. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  30515. var loadedSkeletonsIds = [];
  30516. var loadedMaterialsIds = [];
  30517. var hierarchyIds = [];
  30518. var index;
  30519. var cache;
  30520. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  30521. var parsedMesh = parsedData.meshes[index];
  30522. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  30523. if (meshesNames instanceof Array) {
  30524. // Remove found mesh name from list.
  30525. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  30526. }
  30527. //Geometry?
  30528. if (parsedMesh.geometryId) {
  30529. //does the file contain geometries?
  30530. if (parsedData.geometries) {
  30531. //find the correct geometry and add it to the scene
  30532. var found = false;
  30533. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  30534. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  30535. return;
  30536. }
  30537. else {
  30538. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  30539. if (parsedGeometryData.id === parsedMesh.geometryId) {
  30540. switch (geometryType) {
  30541. case "boxes":
  30542. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  30543. break;
  30544. case "spheres":
  30545. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  30546. break;
  30547. case "cylinders":
  30548. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  30549. break;
  30550. case "toruses":
  30551. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  30552. break;
  30553. case "grounds":
  30554. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  30555. break;
  30556. case "planes":
  30557. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  30558. break;
  30559. case "torusKnots":
  30560. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  30561. break;
  30562. case "vertexData":
  30563. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  30564. break;
  30565. }
  30566. found = true;
  30567. }
  30568. });
  30569. }
  30570. });
  30571. if (!found) {
  30572. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  30573. }
  30574. }
  30575. }
  30576. // Material ?
  30577. if (parsedMesh.materialId) {
  30578. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  30579. if (!materialFound && parsedData.multiMaterials) {
  30580. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  30581. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  30582. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  30583. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  30584. var subMatId = parsedMultiMaterial.materials[matIndex];
  30585. loadedMaterialsIds.push(subMatId);
  30586. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  30587. log += "\n\tMaterial " + mat.toString(fullDetails);
  30588. }
  30589. loadedMaterialsIds.push(parsedMultiMaterial.id);
  30590. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  30591. materialFound = true;
  30592. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  30593. break;
  30594. }
  30595. }
  30596. }
  30597. if (!materialFound) {
  30598. loadedMaterialsIds.push(parsedMesh.materialId);
  30599. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  30600. if (!mat) {
  30601. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  30602. }
  30603. else {
  30604. log += "\n\tMaterial " + mat.toString(fullDetails);
  30605. }
  30606. }
  30607. }
  30608. // Skeleton ?
  30609. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  30610. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  30611. if (!skeletonAlreadyLoaded) {
  30612. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  30613. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  30614. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  30615. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  30616. skeletons.push(skeleton);
  30617. loadedSkeletonsIds.push(parsedSkeleton.id);
  30618. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  30619. }
  30620. }
  30621. }
  30622. }
  30623. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  30624. meshes.push(mesh);
  30625. log += "\n\tMesh " + mesh.toString(fullDetails);
  30626. }
  30627. }
  30628. // Connecting parents
  30629. var currentMesh;
  30630. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  30631. currentMesh = scene.meshes[index];
  30632. if (currentMesh._waitingParentId) {
  30633. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  30634. currentMesh._waitingParentId = undefined;
  30635. }
  30636. }
  30637. // freeze and compute world matrix application
  30638. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  30639. currentMesh = scene.meshes[index];
  30640. if (currentMesh._waitingFreezeWorldMatrix) {
  30641. currentMesh.freezeWorldMatrix();
  30642. currentMesh._waitingFreezeWorldMatrix = undefined;
  30643. }
  30644. else {
  30645. currentMesh.computeWorldMatrix(true);
  30646. }
  30647. }
  30648. // Particles
  30649. if (parsedData.particleSystems) {
  30650. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  30651. var parsedParticleSystem = parsedData.particleSystems[index];
  30652. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  30653. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  30654. }
  30655. }
  30656. }
  30657. return true;
  30658. }
  30659. catch (err) {
  30660. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  30661. log = null;
  30662. throw err;
  30663. }
  30664. finally {
  30665. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  30666. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  30667. }
  30668. }
  30669. },
  30670. load: function (scene, data, rootUrl) {
  30671. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  30672. // when SceneLoader.debugLogging = true (default), or exception encountered.
  30673. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  30674. // and avoid problems with multiple concurrent .babylon loads.
  30675. var log = "importScene has failed JSON parse";
  30676. try {
  30677. var parsedData = JSON.parse(data);
  30678. log = "";
  30679. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  30680. // Scene
  30681. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  30682. scene.autoClear = parsedData.autoClear;
  30683. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  30684. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  30685. if (parsedData.gravity) {
  30686. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  30687. }
  30688. // Fog
  30689. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  30690. scene.fogMode = parsedData.fogMode;
  30691. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  30692. scene.fogStart = parsedData.fogStart;
  30693. scene.fogEnd = parsedData.fogEnd;
  30694. scene.fogDensity = parsedData.fogDensity;
  30695. log += "\tFog mode for scene: ";
  30696. switch (scene.fogMode) {
  30697. // getters not compiling, so using hardcoded
  30698. case 1:
  30699. log += "exp\n";
  30700. break;
  30701. case 2:
  30702. log += "exp2\n";
  30703. break;
  30704. case 3:
  30705. log += "linear\n";
  30706. break;
  30707. }
  30708. }
  30709. //Physics
  30710. if (parsedData.physicsEnabled) {
  30711. var physicsPlugin;
  30712. if (parsedData.physicsEngine === "cannon") {
  30713. physicsPlugin = new BABYLON.CannonJSPlugin();
  30714. }
  30715. else if (parsedData.physicsEngine === "oimo") {
  30716. physicsPlugin = new BABYLON.OimoJSPlugin();
  30717. }
  30718. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  30719. //else - default engine, which is currently oimo
  30720. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  30721. scene.enablePhysics(physicsGravity, physicsPlugin);
  30722. }
  30723. // Metadata
  30724. if (parsedData.metadata !== undefined) {
  30725. scene.metadata = parsedData.metadata;
  30726. }
  30727. //collisions, if defined. otherwise, default is true
  30728. if (parsedData.collisionsEnabled != undefined) {
  30729. scene.collisionsEnabled = parsedData.collisionsEnabled;
  30730. }
  30731. scene.workerCollisions = !!parsedData.workerCollisions;
  30732. var index;
  30733. var cache;
  30734. // Lights
  30735. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  30736. var parsedLight = parsedData.lights[index];
  30737. var light = BABYLON.Light.Parse(parsedLight, scene);
  30738. log += (index === 0 ? "\n\tLights:" : "");
  30739. log += "\n\t\t" + light.toString(fullDetails);
  30740. }
  30741. // Animations
  30742. if (parsedData.animations) {
  30743. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  30744. var parsedAnimation = parsedData.animations[index];
  30745. var animation = BABYLON.Animation.Parse(parsedAnimation);
  30746. scene.animations.push(animation);
  30747. log += (index === 0 ? "\n\tAnimations:" : "");
  30748. log += "\n\t\t" + animation.toString(fullDetails);
  30749. }
  30750. }
  30751. if (parsedData.autoAnimate) {
  30752. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  30753. }
  30754. // Materials
  30755. if (parsedData.materials) {
  30756. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  30757. var parsedMaterial = parsedData.materials[index];
  30758. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  30759. log += (index === 0 ? "\n\tMaterials:" : "");
  30760. log += "\n\t\t" + mat.toString(fullDetails);
  30761. }
  30762. }
  30763. if (parsedData.multiMaterials) {
  30764. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  30765. var parsedMultiMaterial = parsedData.multiMaterials[index];
  30766. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  30767. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  30768. log += "\n\t\t" + mmat.toString(fullDetails);
  30769. }
  30770. }
  30771. // Skeletons
  30772. if (parsedData.skeletons) {
  30773. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  30774. var parsedSkeleton = parsedData.skeletons[index];
  30775. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  30776. log += (index === 0 ? "\n\tSkeletons:" : "");
  30777. log += "\n\t\t" + skeleton.toString(fullDetails);
  30778. }
  30779. }
  30780. // Geometries
  30781. var geometries = parsedData.geometries;
  30782. if (geometries) {
  30783. // Boxes
  30784. var boxes = geometries.boxes;
  30785. if (boxes) {
  30786. for (index = 0, cache = boxes.length; index < cache; index++) {
  30787. var parsedBox = boxes[index];
  30788. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  30789. }
  30790. }
  30791. // Spheres
  30792. var spheres = geometries.spheres;
  30793. if (spheres) {
  30794. for (index = 0, cache = spheres.length; index < cache; index++) {
  30795. var parsedSphere = spheres[index];
  30796. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  30797. }
  30798. }
  30799. // Cylinders
  30800. var cylinders = geometries.cylinders;
  30801. if (cylinders) {
  30802. for (index = 0, cache = cylinders.length; index < cache; index++) {
  30803. var parsedCylinder = cylinders[index];
  30804. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  30805. }
  30806. }
  30807. // Toruses
  30808. var toruses = geometries.toruses;
  30809. if (toruses) {
  30810. for (index = 0, cache = toruses.length; index < cache; index++) {
  30811. var parsedTorus = toruses[index];
  30812. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  30813. }
  30814. }
  30815. // Grounds
  30816. var grounds = geometries.grounds;
  30817. if (grounds) {
  30818. for (index = 0, cache = grounds.length; index < cache; index++) {
  30819. var parsedGround = grounds[index];
  30820. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  30821. }
  30822. }
  30823. // Planes
  30824. var planes = geometries.planes;
  30825. if (planes) {
  30826. for (index = 0, cache = planes.length; index < cache; index++) {
  30827. var parsedPlane = planes[index];
  30828. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  30829. }
  30830. }
  30831. // TorusKnots
  30832. var torusKnots = geometries.torusKnots;
  30833. if (torusKnots) {
  30834. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  30835. var parsedTorusKnot = torusKnots[index];
  30836. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  30837. }
  30838. }
  30839. // VertexData
  30840. var vertexData = geometries.vertexData;
  30841. if (vertexData) {
  30842. for (index = 0, cache = vertexData.length; index < cache; index++) {
  30843. var parsedVertexData = vertexData[index];
  30844. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  30845. }
  30846. }
  30847. }
  30848. // Meshes
  30849. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  30850. var parsedMesh = parsedData.meshes[index];
  30851. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  30852. log += (index === 0 ? "\n\tMeshes:" : "");
  30853. log += "\n\t\t" + mesh.toString(fullDetails);
  30854. }
  30855. // Cameras
  30856. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  30857. var parsedCamera = parsedData.cameras[index];
  30858. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  30859. log += (index === 0 ? "\n\tCameras:" : "");
  30860. log += "\n\t\t" + camera.toString(fullDetails);
  30861. }
  30862. if (parsedData.activeCameraID) {
  30863. scene.setActiveCameraByID(parsedData.activeCameraID);
  30864. }
  30865. // Browsing all the graph to connect the dots
  30866. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  30867. var camera = scene.cameras[index];
  30868. if (camera._waitingParentId) {
  30869. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  30870. camera._waitingParentId = undefined;
  30871. }
  30872. }
  30873. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  30874. var light = scene.lights[index];
  30875. if (light._waitingParentId) {
  30876. light.parent = scene.getLastEntryByID(light._waitingParentId);
  30877. light._waitingParentId = undefined;
  30878. }
  30879. }
  30880. // Sounds
  30881. var loadedSounds = [];
  30882. var loadedSound;
  30883. if (BABYLON.AudioEngine && parsedData.sounds) {
  30884. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  30885. var parsedSound = parsedData.sounds[index];
  30886. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30887. if (!parsedSound.url)
  30888. parsedSound.url = parsedSound.name;
  30889. if (!loadedSounds[parsedSound.url]) {
  30890. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  30891. loadedSounds[parsedSound.url] = loadedSound;
  30892. }
  30893. else {
  30894. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  30895. }
  30896. }
  30897. else {
  30898. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  30899. }
  30900. }
  30901. }
  30902. loadedSounds = [];
  30903. // Connect parents & children and parse actions
  30904. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  30905. var mesh = scene.meshes[index];
  30906. if (mesh._waitingParentId) {
  30907. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  30908. mesh._waitingParentId = undefined;
  30909. }
  30910. if (mesh._waitingActions) {
  30911. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  30912. mesh._waitingActions = undefined;
  30913. }
  30914. }
  30915. // freeze world matrix application
  30916. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  30917. var currentMesh = scene.meshes[index];
  30918. if (currentMesh._waitingFreezeWorldMatrix) {
  30919. currentMesh.freezeWorldMatrix();
  30920. currentMesh._waitingFreezeWorldMatrix = undefined;
  30921. }
  30922. else {
  30923. currentMesh.computeWorldMatrix(true);
  30924. }
  30925. }
  30926. // Particles Systems
  30927. if (parsedData.particleSystems) {
  30928. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  30929. var parsedParticleSystem = parsedData.particleSystems[index];
  30930. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  30931. }
  30932. }
  30933. // Lens flares
  30934. if (parsedData.lensFlareSystems) {
  30935. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  30936. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  30937. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  30938. }
  30939. }
  30940. // Shadows
  30941. if (parsedData.shadowGenerators) {
  30942. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  30943. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  30944. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  30945. }
  30946. }
  30947. // Actions (scene)
  30948. if (parsedData.actions) {
  30949. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  30950. }
  30951. // Finish
  30952. return true;
  30953. }
  30954. catch (err) {
  30955. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  30956. log = null;
  30957. throw err;
  30958. }
  30959. finally {
  30960. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  30961. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  30962. }
  30963. }
  30964. }
  30965. });
  30966. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30967. })(BABYLON || (BABYLON = {}));
  30968. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  30969. var BABYLON;
  30970. (function (BABYLON) {
  30971. var SpriteManager = (function () {
  30972. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  30973. if (epsilon === void 0) { epsilon = 0.01; }
  30974. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30975. this.name = name;
  30976. this.sprites = new Array();
  30977. this.renderingGroupId = 0;
  30978. this.layerMask = 0x0FFFFFFF;
  30979. this.fogEnabled = true;
  30980. this.isPickable = false;
  30981. /**
  30982. * An event triggered when the manager is disposed.
  30983. * @type {BABYLON.Observable}
  30984. */
  30985. this.onDisposeObservable = new BABYLON.Observable();
  30986. this._vertexBuffers = {};
  30987. this._capacity = capacity;
  30988. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  30989. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30990. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30991. if (cellSize.width && cellSize.height) {
  30992. this.cellWidth = cellSize.width;
  30993. this.cellHeight = cellSize.height;
  30994. }
  30995. else if (cellSize !== undefined) {
  30996. this.cellWidth = cellSize;
  30997. this.cellHeight = cellSize;
  30998. }
  30999. else {
  31000. return;
  31001. }
  31002. this._epsilon = epsilon;
  31003. this._scene = scene;
  31004. this._scene.spriteManagers.push(this);
  31005. var indices = [];
  31006. var index = 0;
  31007. for (var count = 0; count < capacity; count++) {
  31008. indices.push(index);
  31009. indices.push(index + 1);
  31010. indices.push(index + 2);
  31011. indices.push(index);
  31012. indices.push(index + 2);
  31013. indices.push(index + 3);
  31014. index += 4;
  31015. }
  31016. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  31017. // VBO
  31018. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  31019. this._vertexData = new Float32Array(capacity * 16 * 4);
  31020. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  31021. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  31022. var options = this._buffer.createVertexBuffer("options", 4, 4);
  31023. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  31024. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  31025. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  31026. this._vertexBuffers["options"] = options;
  31027. this._vertexBuffers["cellInfo"] = cellInfo;
  31028. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  31029. // Effects
  31030. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  31031. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  31032. }
  31033. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  31034. set: function (callback) {
  31035. if (this._onDisposeObserver) {
  31036. this.onDisposeObservable.remove(this._onDisposeObserver);
  31037. }
  31038. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31039. },
  31040. enumerable: true,
  31041. configurable: true
  31042. });
  31043. Object.defineProperty(SpriteManager.prototype, "texture", {
  31044. get: function () {
  31045. return this._spriteTexture;
  31046. },
  31047. set: function (value) {
  31048. this._spriteTexture = value;
  31049. },
  31050. enumerable: true,
  31051. configurable: true
  31052. });
  31053. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  31054. var arrayOffset = index * 16;
  31055. if (offsetX === 0)
  31056. offsetX = this._epsilon;
  31057. else if (offsetX === 1)
  31058. offsetX = 1 - this._epsilon;
  31059. if (offsetY === 0)
  31060. offsetY = this._epsilon;
  31061. else if (offsetY === 1)
  31062. offsetY = 1 - this._epsilon;
  31063. this._vertexData[arrayOffset] = sprite.position.x;
  31064. this._vertexData[arrayOffset + 1] = sprite.position.y;
  31065. this._vertexData[arrayOffset + 2] = sprite.position.z;
  31066. this._vertexData[arrayOffset + 3] = sprite.angle;
  31067. this._vertexData[arrayOffset + 4] = sprite.width;
  31068. this._vertexData[arrayOffset + 5] = sprite.height;
  31069. this._vertexData[arrayOffset + 6] = offsetX;
  31070. this._vertexData[arrayOffset + 7] = offsetY;
  31071. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  31072. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  31073. var offset = (sprite.cellIndex / rowSize) >> 0;
  31074. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  31075. this._vertexData[arrayOffset + 11] = offset;
  31076. // Color
  31077. this._vertexData[arrayOffset + 12] = sprite.color.r;
  31078. this._vertexData[arrayOffset + 13] = sprite.color.g;
  31079. this._vertexData[arrayOffset + 14] = sprite.color.b;
  31080. this._vertexData[arrayOffset + 15] = sprite.color.a;
  31081. };
  31082. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  31083. var count = Math.min(this._capacity, this.sprites.length);
  31084. var min = BABYLON.Vector3.Zero();
  31085. var max = BABYLON.Vector3.Zero();
  31086. var distance = Number.MAX_VALUE;
  31087. var currentSprite;
  31088. var cameraSpacePosition = BABYLON.Vector3.Zero();
  31089. var cameraView = camera.getViewMatrix();
  31090. for (var index = 0; index < count; index++) {
  31091. var sprite = this.sprites[index];
  31092. if (!sprite) {
  31093. continue;
  31094. }
  31095. if (predicate) {
  31096. if (!predicate(sprite)) {
  31097. continue;
  31098. }
  31099. }
  31100. else if (!sprite.isPickable) {
  31101. continue;
  31102. }
  31103. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  31104. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  31105. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  31106. if (ray.intersectsBoxMinMax(min, max)) {
  31107. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  31108. if (distance > currentDistance) {
  31109. distance = currentDistance;
  31110. currentSprite = sprite;
  31111. if (fastCheck) {
  31112. break;
  31113. }
  31114. }
  31115. }
  31116. }
  31117. if (currentSprite) {
  31118. var result = new BABYLON.PickingInfo();
  31119. result.hit = true;
  31120. result.pickedSprite = currentSprite;
  31121. result.distance = distance;
  31122. return result;
  31123. }
  31124. return null;
  31125. };
  31126. SpriteManager.prototype.render = function () {
  31127. // Check
  31128. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  31129. return;
  31130. var engine = this._scene.getEngine();
  31131. var baseSize = this._spriteTexture.getBaseSize();
  31132. // Sprites
  31133. var deltaTime = engine.getDeltaTime();
  31134. var max = Math.min(this._capacity, this.sprites.length);
  31135. var rowSize = baseSize.width / this.cellWidth;
  31136. var offset = 0;
  31137. for (var index = 0; index < max; index++) {
  31138. var sprite = this.sprites[index];
  31139. if (!sprite) {
  31140. continue;
  31141. }
  31142. sprite._animate(deltaTime);
  31143. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  31144. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  31145. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  31146. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  31147. }
  31148. this._buffer.update(this._vertexData);
  31149. // Render
  31150. var effect = this._effectBase;
  31151. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  31152. effect = this._effectFog;
  31153. }
  31154. engine.enableEffect(effect);
  31155. var viewMatrix = this._scene.getViewMatrix();
  31156. effect.setTexture("diffuseSampler", this._spriteTexture);
  31157. effect.setMatrix("view", viewMatrix);
  31158. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  31159. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  31160. // Fog
  31161. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  31162. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  31163. effect.setColor3("vFogColor", this._scene.fogColor);
  31164. }
  31165. // VBOs
  31166. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31167. // Draw order
  31168. engine.setDepthFunctionToLessOrEqual();
  31169. effect.setBool("alphaTest", true);
  31170. engine.setColorWrite(false);
  31171. engine.draw(true, 0, max * 6);
  31172. engine.setColorWrite(true);
  31173. effect.setBool("alphaTest", false);
  31174. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31175. engine.draw(true, 0, max * 6);
  31176. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31177. };
  31178. SpriteManager.prototype.dispose = function () {
  31179. if (this._buffer) {
  31180. this._buffer.dispose();
  31181. this._buffer = null;
  31182. }
  31183. if (this._indexBuffer) {
  31184. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31185. this._indexBuffer = null;
  31186. }
  31187. if (this._spriteTexture) {
  31188. this._spriteTexture.dispose();
  31189. this._spriteTexture = null;
  31190. }
  31191. // Remove from scene
  31192. var index = this._scene.spriteManagers.indexOf(this);
  31193. this._scene.spriteManagers.splice(index, 1);
  31194. // Callback
  31195. this.onDisposeObservable.notifyObservers(this);
  31196. this.onDisposeObservable.clear();
  31197. };
  31198. return SpriteManager;
  31199. }());
  31200. BABYLON.SpriteManager = SpriteManager;
  31201. })(BABYLON || (BABYLON = {}));
  31202. //# sourceMappingURL=babylon.spriteManager.js.map
  31203. var BABYLON;
  31204. (function (BABYLON) {
  31205. var Sprite = (function () {
  31206. function Sprite(name, manager) {
  31207. this.name = name;
  31208. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31209. this.width = 1.0;
  31210. this.height = 1.0;
  31211. this.angle = 0;
  31212. this.cellIndex = 0;
  31213. this.invertU = 0;
  31214. this.invertV = 0;
  31215. this.animations = new Array();
  31216. this.isPickable = false;
  31217. this._animationStarted = false;
  31218. this._loopAnimation = false;
  31219. this._fromIndex = 0;
  31220. this._toIndex = 0;
  31221. this._delay = 0;
  31222. this._direction = 1;
  31223. this._frameCount = 0;
  31224. this._time = 0;
  31225. this._manager = manager;
  31226. this._manager.sprites.push(this);
  31227. this.position = BABYLON.Vector3.Zero();
  31228. }
  31229. Object.defineProperty(Sprite.prototype, "size", {
  31230. get: function () {
  31231. return this.width;
  31232. },
  31233. set: function (value) {
  31234. this.width = value;
  31235. this.height = value;
  31236. },
  31237. enumerable: true,
  31238. configurable: true
  31239. });
  31240. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  31241. this._fromIndex = from;
  31242. this._toIndex = to;
  31243. this._loopAnimation = loop;
  31244. this._delay = delay;
  31245. this._animationStarted = true;
  31246. this._direction = from < to ? 1 : -1;
  31247. this.cellIndex = from;
  31248. this._time = 0;
  31249. this._onAnimationEnd = onAnimationEnd;
  31250. };
  31251. Sprite.prototype.stopAnimation = function () {
  31252. this._animationStarted = false;
  31253. };
  31254. Sprite.prototype._animate = function (deltaTime) {
  31255. if (!this._animationStarted)
  31256. return;
  31257. this._time += deltaTime;
  31258. if (this._time > this._delay) {
  31259. this._time = this._time % this._delay;
  31260. this.cellIndex += this._direction;
  31261. if (this.cellIndex === this._toIndex) {
  31262. if (this._loopAnimation) {
  31263. this.cellIndex = this._fromIndex;
  31264. }
  31265. else {
  31266. this._animationStarted = false;
  31267. if (this._onAnimationEnd) {
  31268. this._onAnimationEnd();
  31269. }
  31270. if (this.disposeWhenFinishedAnimating) {
  31271. this.dispose();
  31272. }
  31273. }
  31274. }
  31275. }
  31276. };
  31277. Sprite.prototype.dispose = function () {
  31278. for (var i = 0; i < this._manager.sprites.length; i++) {
  31279. if (this._manager.sprites[i] == this) {
  31280. this._manager.sprites.splice(i, 1);
  31281. }
  31282. }
  31283. };
  31284. return Sprite;
  31285. }());
  31286. BABYLON.Sprite = Sprite;
  31287. })(BABYLON || (BABYLON = {}));
  31288. //# sourceMappingURL=babylon.sprite.js.map
  31289. var BABYLON;
  31290. (function (BABYLON) {
  31291. var Layer = (function () {
  31292. function Layer(name, imgUrl, scene, isBackground, color) {
  31293. this.name = name;
  31294. this.scale = new BABYLON.Vector2(1, 1);
  31295. this.offset = new BABYLON.Vector2(0, 0);
  31296. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  31297. this._vertexBuffers = {};
  31298. // Events
  31299. /**
  31300. * An event triggered when the layer is disposed.
  31301. * @type {BABYLON.Observable}
  31302. */
  31303. this.onDisposeObservable = new BABYLON.Observable();
  31304. /**
  31305. * An event triggered before rendering the scene
  31306. * @type {BABYLON.Observable}
  31307. */
  31308. this.onBeforeRenderObservable = new BABYLON.Observable();
  31309. /**
  31310. * An event triggered after rendering the scene
  31311. * @type {BABYLON.Observable}
  31312. */
  31313. this.onAfterRenderObservable = new BABYLON.Observable();
  31314. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  31315. this.isBackground = isBackground === undefined ? true : isBackground;
  31316. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  31317. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31318. this._scene.layers.push(this);
  31319. var engine = scene.getEngine();
  31320. // VBO
  31321. var vertices = [];
  31322. vertices.push(1, 1);
  31323. vertices.push(-1, 1);
  31324. vertices.push(-1, -1);
  31325. vertices.push(1, -1);
  31326. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31327. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  31328. // Indices
  31329. var indices = [];
  31330. indices.push(0);
  31331. indices.push(1);
  31332. indices.push(2);
  31333. indices.push(0);
  31334. indices.push(2);
  31335. indices.push(3);
  31336. this._indexBuffer = engine.createIndexBuffer(indices);
  31337. // Effects
  31338. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  31339. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  31340. }
  31341. Object.defineProperty(Layer.prototype, "onDispose", {
  31342. set: function (callback) {
  31343. if (this._onDisposeObserver) {
  31344. this.onDisposeObservable.remove(this._onDisposeObserver);
  31345. }
  31346. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31347. },
  31348. enumerable: true,
  31349. configurable: true
  31350. });
  31351. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  31352. set: function (callback) {
  31353. if (this._onBeforeRenderObserver) {
  31354. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  31355. }
  31356. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  31357. },
  31358. enumerable: true,
  31359. configurable: true
  31360. });
  31361. Object.defineProperty(Layer.prototype, "onAfterRender", {
  31362. set: function (callback) {
  31363. if (this._onAfterRenderObserver) {
  31364. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  31365. }
  31366. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31367. },
  31368. enumerable: true,
  31369. configurable: true
  31370. });
  31371. Layer.prototype.render = function () {
  31372. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  31373. // Check
  31374. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  31375. return;
  31376. var engine = this._scene.getEngine();
  31377. this.onBeforeRenderObservable.notifyObservers(this);
  31378. // Render
  31379. engine.enableEffect(currentEffect);
  31380. engine.setState(false);
  31381. // Texture
  31382. currentEffect.setTexture("textureSampler", this.texture);
  31383. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  31384. // Color
  31385. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  31386. // Scale / offset
  31387. currentEffect.setVector2("offset", this.offset);
  31388. currentEffect.setVector2("scale", this.scale);
  31389. // VBOs
  31390. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  31391. // Draw order
  31392. if (!this.alphaTest) {
  31393. engine.setAlphaMode(this.alphaBlendingMode);
  31394. engine.draw(true, 0, 6);
  31395. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31396. }
  31397. else {
  31398. engine.draw(true, 0, 6);
  31399. }
  31400. this.onAfterRenderObservable.notifyObservers(this);
  31401. };
  31402. Layer.prototype.dispose = function () {
  31403. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31404. if (vertexBuffer) {
  31405. vertexBuffer.dispose();
  31406. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31407. }
  31408. if (this._indexBuffer) {
  31409. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31410. this._indexBuffer = null;
  31411. }
  31412. if (this.texture) {
  31413. this.texture.dispose();
  31414. this.texture = null;
  31415. }
  31416. // Remove from scene
  31417. var index = this._scene.layers.indexOf(this);
  31418. this._scene.layers.splice(index, 1);
  31419. // Callback
  31420. this.onDisposeObservable.notifyObservers(this);
  31421. this.onDisposeObservable.clear();
  31422. this.onAfterRenderObservable.clear();
  31423. this.onBeforeRenderObservable.clear();
  31424. };
  31425. return Layer;
  31426. }());
  31427. BABYLON.Layer = Layer;
  31428. })(BABYLON || (BABYLON = {}));
  31429. //# sourceMappingURL=babylon.layer.js.map
  31430. var BABYLON;
  31431. (function (BABYLON) {
  31432. var Particle = (function () {
  31433. function Particle() {
  31434. this.position = BABYLON.Vector3.Zero();
  31435. this.direction = BABYLON.Vector3.Zero();
  31436. this.color = new BABYLON.Color4(0, 0, 0, 0);
  31437. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  31438. this.lifeTime = 1.0;
  31439. this.age = 0;
  31440. this.size = 0;
  31441. this.angle = 0;
  31442. this.angularSpeed = 0;
  31443. }
  31444. Particle.prototype.copyTo = function (other) {
  31445. other.position.copyFrom(this.position);
  31446. other.direction.copyFrom(this.direction);
  31447. other.color.copyFrom(this.color);
  31448. other.colorStep.copyFrom(this.colorStep);
  31449. other.lifeTime = this.lifeTime;
  31450. other.age = this.age;
  31451. other.size = this.size;
  31452. other.angle = this.angle;
  31453. other.angularSpeed = this.angularSpeed;
  31454. };
  31455. return Particle;
  31456. }());
  31457. BABYLON.Particle = Particle;
  31458. })(BABYLON || (BABYLON = {}));
  31459. //# sourceMappingURL=babylon.particle.js.map
  31460. var BABYLON;
  31461. (function (BABYLON) {
  31462. var randomNumber = function (min, max) {
  31463. if (min === max) {
  31464. return (min);
  31465. }
  31466. var random = Math.random();
  31467. return ((random * (max - min)) + min);
  31468. };
  31469. var ParticleSystem = (function () {
  31470. function ParticleSystem(name, capacity, scene, customEffect) {
  31471. var _this = this;
  31472. this.name = name;
  31473. // Members
  31474. this.animations = [];
  31475. this.renderingGroupId = 0;
  31476. this.emitter = null;
  31477. this.emitRate = 10;
  31478. this.manualEmitCount = -1;
  31479. this.updateSpeed = 0.01;
  31480. this.targetStopDuration = 0;
  31481. this.disposeOnStop = false;
  31482. this.minEmitPower = 1;
  31483. this.maxEmitPower = 1;
  31484. this.minLifeTime = 1;
  31485. this.maxLifeTime = 1;
  31486. this.minSize = 1;
  31487. this.maxSize = 1;
  31488. this.minAngularSpeed = 0;
  31489. this.maxAngularSpeed = 0;
  31490. this.layerMask = 0x0FFFFFFF;
  31491. this.customShader = null;
  31492. this.preventAutoStart = false;
  31493. /**
  31494. * An event triggered when the system is disposed.
  31495. * @type {BABYLON.Observable}
  31496. */
  31497. this.onDisposeObservable = new BABYLON.Observable();
  31498. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  31499. this.forceDepthWrite = false;
  31500. this.gravity = BABYLON.Vector3.Zero();
  31501. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  31502. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  31503. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  31504. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  31505. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31506. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31507. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  31508. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31509. this.particles = new Array();
  31510. this._stockParticles = new Array();
  31511. this._newPartsExcess = 0;
  31512. this._vertexBuffers = {};
  31513. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  31514. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  31515. this._scaledDirection = BABYLON.Vector3.Zero();
  31516. this._scaledGravity = BABYLON.Vector3.Zero();
  31517. this._currentRenderId = -1;
  31518. this._started = false;
  31519. this._stopped = false;
  31520. this._actualFrame = 0;
  31521. this.id = name;
  31522. this._capacity = capacity;
  31523. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31524. this._customEffect = customEffect;
  31525. scene.particleSystems.push(this);
  31526. var indices = [];
  31527. var index = 0;
  31528. for (var count = 0; count < capacity; count++) {
  31529. indices.push(index);
  31530. indices.push(index + 1);
  31531. indices.push(index + 2);
  31532. indices.push(index);
  31533. indices.push(index + 2);
  31534. indices.push(index + 3);
  31535. index += 4;
  31536. }
  31537. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  31538. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  31539. this._vertexData = new Float32Array(capacity * 11 * 4);
  31540. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  31541. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  31542. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  31543. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  31544. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  31545. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  31546. this._vertexBuffers["options"] = options;
  31547. // Default behaviors
  31548. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  31549. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  31550. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  31551. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  31552. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  31553. };
  31554. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  31555. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  31556. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  31557. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  31558. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  31559. };
  31560. this.updateFunction = function (particles) {
  31561. for (var index = 0; index < particles.length; index++) {
  31562. var particle = particles[index];
  31563. particle.age += _this._scaledUpdateSpeed;
  31564. if (particle.age >= particle.lifeTime) {
  31565. _this.recycleParticle(particle);
  31566. index--;
  31567. continue;
  31568. }
  31569. else {
  31570. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  31571. particle.color.addInPlace(_this._scaledColorStep);
  31572. if (particle.color.a < 0)
  31573. particle.color.a = 0;
  31574. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  31575. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  31576. particle.position.addInPlace(_this._scaledDirection);
  31577. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  31578. particle.direction.addInPlace(_this._scaledGravity);
  31579. }
  31580. }
  31581. };
  31582. }
  31583. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  31584. set: function (callback) {
  31585. if (this._onDisposeObserver) {
  31586. this.onDisposeObservable.remove(this._onDisposeObserver);
  31587. }
  31588. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31589. },
  31590. enumerable: true,
  31591. configurable: true
  31592. });
  31593. ParticleSystem.prototype.recycleParticle = function (particle) {
  31594. var lastParticle = this.particles.pop();
  31595. if (lastParticle !== particle) {
  31596. lastParticle.copyTo(particle);
  31597. this._stockParticles.push(lastParticle);
  31598. }
  31599. };
  31600. ParticleSystem.prototype.getCapacity = function () {
  31601. return this._capacity;
  31602. };
  31603. ParticleSystem.prototype.isAlive = function () {
  31604. return this._alive;
  31605. };
  31606. ParticleSystem.prototype.isStarted = function () {
  31607. return this._started;
  31608. };
  31609. ParticleSystem.prototype.start = function () {
  31610. this._started = true;
  31611. this._stopped = false;
  31612. this._actualFrame = 0;
  31613. };
  31614. ParticleSystem.prototype.stop = function () {
  31615. this._stopped = true;
  31616. };
  31617. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  31618. var offset = index * 11;
  31619. this._vertexData[offset] = particle.position.x;
  31620. this._vertexData[offset + 1] = particle.position.y;
  31621. this._vertexData[offset + 2] = particle.position.z;
  31622. this._vertexData[offset + 3] = particle.color.r;
  31623. this._vertexData[offset + 4] = particle.color.g;
  31624. this._vertexData[offset + 5] = particle.color.b;
  31625. this._vertexData[offset + 6] = particle.color.a;
  31626. this._vertexData[offset + 7] = particle.angle;
  31627. this._vertexData[offset + 8] = particle.size;
  31628. this._vertexData[offset + 9] = offsetX;
  31629. this._vertexData[offset + 10] = offsetY;
  31630. };
  31631. ParticleSystem.prototype._update = function (newParticles) {
  31632. // Update current
  31633. this._alive = this.particles.length > 0;
  31634. this.updateFunction(this.particles);
  31635. // Add new ones
  31636. var worldMatrix;
  31637. if (this.emitter.position) {
  31638. worldMatrix = this.emitter.getWorldMatrix();
  31639. }
  31640. else {
  31641. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  31642. }
  31643. var particle;
  31644. for (var index = 0; index < newParticles; index++) {
  31645. if (this.particles.length === this._capacity) {
  31646. break;
  31647. }
  31648. if (this._stockParticles.length !== 0) {
  31649. particle = this._stockParticles.pop();
  31650. particle.age = 0;
  31651. }
  31652. else {
  31653. particle = new BABYLON.Particle();
  31654. }
  31655. this.particles.push(particle);
  31656. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  31657. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  31658. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  31659. particle.size = randomNumber(this.minSize, this.maxSize);
  31660. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  31661. this.startPositionFunction(worldMatrix, particle.position, particle);
  31662. var step = randomNumber(0, 1.0);
  31663. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  31664. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  31665. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  31666. }
  31667. };
  31668. ParticleSystem.prototype._getEffect = function () {
  31669. if (this._customEffect) {
  31670. return this._customEffect;
  31671. }
  31672. ;
  31673. var defines = [];
  31674. if (this._scene.clipPlane) {
  31675. defines.push("#define CLIPPLANE");
  31676. }
  31677. // Effect
  31678. var join = defines.join("\n");
  31679. if (this._cachedDefines !== join) {
  31680. this._cachedDefines = join;
  31681. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  31682. }
  31683. return this._effect;
  31684. };
  31685. ParticleSystem.prototype.animate = function () {
  31686. if (!this._started)
  31687. return;
  31688. var effect = this._getEffect();
  31689. // Check
  31690. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  31691. return;
  31692. if (this._currentRenderId === this._scene.getRenderId()) {
  31693. return;
  31694. }
  31695. this._currentRenderId = this._scene.getRenderId();
  31696. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  31697. // determine the number of particles we need to create
  31698. var newParticles;
  31699. if (this.manualEmitCount > -1) {
  31700. newParticles = this.manualEmitCount;
  31701. this._newPartsExcess = 0;
  31702. this.manualEmitCount = 0;
  31703. }
  31704. else {
  31705. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  31706. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  31707. }
  31708. if (this._newPartsExcess > 1.0) {
  31709. newParticles += this._newPartsExcess >> 0;
  31710. this._newPartsExcess -= this._newPartsExcess >> 0;
  31711. }
  31712. this._alive = false;
  31713. if (!this._stopped) {
  31714. this._actualFrame += this._scaledUpdateSpeed;
  31715. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  31716. this.stop();
  31717. }
  31718. else {
  31719. newParticles = 0;
  31720. }
  31721. this._update(newParticles);
  31722. // Stopped?
  31723. if (this._stopped) {
  31724. if (!this._alive) {
  31725. this._started = false;
  31726. if (this.disposeOnStop) {
  31727. this._scene._toBeDisposed.push(this);
  31728. }
  31729. }
  31730. }
  31731. // Update VBO
  31732. var offset = 0;
  31733. for (var index = 0; index < this.particles.length; index++) {
  31734. var particle = this.particles[index];
  31735. this._appendParticleVertex(offset++, particle, 0, 0);
  31736. this._appendParticleVertex(offset++, particle, 1, 0);
  31737. this._appendParticleVertex(offset++, particle, 1, 1);
  31738. this._appendParticleVertex(offset++, particle, 0, 1);
  31739. }
  31740. this._vertexBuffer.update(this._vertexData);
  31741. };
  31742. ParticleSystem.prototype.render = function () {
  31743. var effect = this._getEffect();
  31744. // Check
  31745. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  31746. return 0;
  31747. var engine = this._scene.getEngine();
  31748. // Render
  31749. engine.enableEffect(effect);
  31750. engine.setState(false);
  31751. var viewMatrix = this._scene.getViewMatrix();
  31752. effect.setTexture("diffuseSampler", this.particleTexture);
  31753. effect.setMatrix("view", viewMatrix);
  31754. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  31755. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  31756. if (this._scene.clipPlane) {
  31757. var clipPlane = this._scene.clipPlane;
  31758. var invView = viewMatrix.clone();
  31759. invView.invert();
  31760. effect.setMatrix("invView", invView);
  31761. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  31762. }
  31763. // VBOs
  31764. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31765. // Draw order
  31766. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  31767. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  31768. }
  31769. else {
  31770. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31771. }
  31772. if (this.forceDepthWrite) {
  31773. engine.setDepthWrite(true);
  31774. }
  31775. engine.draw(true, 0, this.particles.length * 6);
  31776. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31777. return this.particles.length;
  31778. };
  31779. ParticleSystem.prototype.dispose = function () {
  31780. if (this._vertexBuffer) {
  31781. this._vertexBuffer.dispose();
  31782. this._vertexBuffer = null;
  31783. }
  31784. if (this._indexBuffer) {
  31785. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31786. this._indexBuffer = null;
  31787. }
  31788. if (this.particleTexture) {
  31789. this.particleTexture.dispose();
  31790. this.particleTexture = null;
  31791. }
  31792. // Remove from scene
  31793. var index = this._scene.particleSystems.indexOf(this);
  31794. this._scene.particleSystems.splice(index, 1);
  31795. // Callback
  31796. this.onDisposeObservable.notifyObservers(this);
  31797. this.onDisposeObservable.clear();
  31798. };
  31799. // Clone
  31800. ParticleSystem.prototype.clone = function (name, newEmitter) {
  31801. var custom = null;
  31802. var program = null;
  31803. if (this.customShader != null) {
  31804. program = this.customShader;
  31805. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  31806. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  31807. }
  31808. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  31809. result.customShader = program;
  31810. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  31811. if (newEmitter === undefined) {
  31812. newEmitter = this.emitter;
  31813. }
  31814. result.emitter = newEmitter;
  31815. if (this.particleTexture) {
  31816. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  31817. }
  31818. if (!this.preventAutoStart) {
  31819. result.start();
  31820. }
  31821. return result;
  31822. };
  31823. ParticleSystem.prototype.serialize = function () {
  31824. var serializationObject = {};
  31825. serializationObject.name = this.name;
  31826. serializationObject.id = this.id;
  31827. // Emitter
  31828. if (this.emitter.position) {
  31829. serializationObject.emitterId = this.emitter.id;
  31830. }
  31831. else {
  31832. serializationObject.emitter = this.emitter.asArray();
  31833. }
  31834. serializationObject.capacity = this.getCapacity();
  31835. if (this.particleTexture) {
  31836. serializationObject.textureName = this.particleTexture.name;
  31837. }
  31838. // Animations
  31839. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31840. // Particle system
  31841. serializationObject.minAngularSpeed = this.minAngularSpeed;
  31842. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  31843. serializationObject.minSize = this.minSize;
  31844. serializationObject.maxSize = this.maxSize;
  31845. serializationObject.minEmitPower = this.minEmitPower;
  31846. serializationObject.maxEmitPower = this.maxEmitPower;
  31847. serializationObject.minLifeTime = this.minLifeTime;
  31848. serializationObject.maxLifeTime = this.maxLifeTime;
  31849. serializationObject.emitRate = this.emitRate;
  31850. serializationObject.minEmitBox = this.minEmitBox.asArray();
  31851. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  31852. serializationObject.gravity = this.gravity.asArray();
  31853. serializationObject.direction1 = this.direction1.asArray();
  31854. serializationObject.direction2 = this.direction2.asArray();
  31855. serializationObject.color1 = this.color1.asArray();
  31856. serializationObject.color2 = this.color2.asArray();
  31857. serializationObject.colorDead = this.colorDead.asArray();
  31858. serializationObject.updateSpeed = this.updateSpeed;
  31859. serializationObject.targetStopDuration = this.targetStopDuration;
  31860. serializationObject.textureMask = this.textureMask.asArray();
  31861. serializationObject.blendMode = this.blendMode;
  31862. serializationObject.customShader = this.customShader;
  31863. serializationObject.preventAutoStart = this.preventAutoStart;
  31864. return serializationObject;
  31865. };
  31866. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  31867. var name = parsedParticleSystem.name;
  31868. var custom = null;
  31869. var program = null;
  31870. if (parsedParticleSystem.customShader) {
  31871. program = parsedParticleSystem.customShader;
  31872. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  31873. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  31874. }
  31875. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  31876. particleSystem.customShader = program;
  31877. if (parsedParticleSystem.id) {
  31878. particleSystem.id = parsedParticleSystem.id;
  31879. }
  31880. // Auto start
  31881. if (parsedParticleSystem.preventAutoStart) {
  31882. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  31883. }
  31884. // Texture
  31885. if (parsedParticleSystem.textureName) {
  31886. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  31887. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  31888. }
  31889. // Emitter
  31890. if (parsedParticleSystem.emitterId) {
  31891. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  31892. }
  31893. else {
  31894. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  31895. }
  31896. // Animations
  31897. if (parsedParticleSystem.animations) {
  31898. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  31899. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  31900. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31901. }
  31902. }
  31903. if (parsedParticleSystem.autoAnimate) {
  31904. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  31905. }
  31906. // Particle system
  31907. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  31908. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  31909. particleSystem.minSize = parsedParticleSystem.minSize;
  31910. particleSystem.maxSize = parsedParticleSystem.maxSize;
  31911. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  31912. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  31913. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  31914. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  31915. particleSystem.emitRate = parsedParticleSystem.emitRate;
  31916. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  31917. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  31918. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  31919. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  31920. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  31921. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  31922. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  31923. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  31924. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  31925. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  31926. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  31927. particleSystem.blendMode = parsedParticleSystem.blendMode;
  31928. if (!particleSystem.preventAutoStart) {
  31929. particleSystem.start();
  31930. }
  31931. return particleSystem;
  31932. };
  31933. return ParticleSystem;
  31934. }());
  31935. // Statics
  31936. ParticleSystem.BLENDMODE_ONEONE = 0;
  31937. ParticleSystem.BLENDMODE_STANDARD = 1;
  31938. BABYLON.ParticleSystem = ParticleSystem;
  31939. })(BABYLON || (BABYLON = {}));
  31940. //# sourceMappingURL=babylon.particleSystem.js.map
  31941. var BABYLON;
  31942. (function (BABYLON) {
  31943. var AnimationRange = (function () {
  31944. function AnimationRange(name, from, to) {
  31945. this.name = name;
  31946. this.from = from;
  31947. this.to = to;
  31948. }
  31949. AnimationRange.prototype.clone = function () {
  31950. return new AnimationRange(this.name, this.from, this.to);
  31951. };
  31952. return AnimationRange;
  31953. }());
  31954. BABYLON.AnimationRange = AnimationRange;
  31955. /**
  31956. * Composed of a frame, and an action function
  31957. */
  31958. var AnimationEvent = (function () {
  31959. function AnimationEvent(frame, action, onlyOnce) {
  31960. this.frame = frame;
  31961. this.action = action;
  31962. this.onlyOnce = onlyOnce;
  31963. this.isDone = false;
  31964. }
  31965. return AnimationEvent;
  31966. }());
  31967. BABYLON.AnimationEvent = AnimationEvent;
  31968. var PathCursor = (function () {
  31969. function PathCursor(path) {
  31970. this.path = path;
  31971. this._onchange = new Array();
  31972. this.value = 0;
  31973. this.animations = new Array();
  31974. }
  31975. PathCursor.prototype.getPoint = function () {
  31976. var point = this.path.getPointAtLengthPosition(this.value);
  31977. return new BABYLON.Vector3(point.x, 0, point.y);
  31978. };
  31979. PathCursor.prototype.moveAhead = function (step) {
  31980. if (step === void 0) { step = 0.002; }
  31981. this.move(step);
  31982. return this;
  31983. };
  31984. PathCursor.prototype.moveBack = function (step) {
  31985. if (step === void 0) { step = 0.002; }
  31986. this.move(-step);
  31987. return this;
  31988. };
  31989. PathCursor.prototype.move = function (step) {
  31990. if (Math.abs(step) > 1) {
  31991. throw "step size should be less than 1.";
  31992. }
  31993. this.value += step;
  31994. this.ensureLimits();
  31995. this.raiseOnChange();
  31996. return this;
  31997. };
  31998. PathCursor.prototype.ensureLimits = function () {
  31999. while (this.value > 1) {
  32000. this.value -= 1;
  32001. }
  32002. while (this.value < 0) {
  32003. this.value += 1;
  32004. }
  32005. return this;
  32006. };
  32007. // used by animation engine
  32008. PathCursor.prototype.markAsDirty = function (propertyName) {
  32009. this.ensureLimits();
  32010. this.raiseOnChange();
  32011. return this;
  32012. };
  32013. PathCursor.prototype.raiseOnChange = function () {
  32014. var _this = this;
  32015. this._onchange.forEach(function (f) { return f(_this); });
  32016. return this;
  32017. };
  32018. PathCursor.prototype.onchange = function (f) {
  32019. this._onchange.push(f);
  32020. return this;
  32021. };
  32022. return PathCursor;
  32023. }());
  32024. BABYLON.PathCursor = PathCursor;
  32025. var Animation = (function () {
  32026. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  32027. this.name = name;
  32028. this.targetProperty = targetProperty;
  32029. this.framePerSecond = framePerSecond;
  32030. this.dataType = dataType;
  32031. this.loopMode = loopMode;
  32032. this.enableBlending = enableBlending;
  32033. this._offsetsCache = {};
  32034. this._highLimitsCache = {};
  32035. this._stopped = false;
  32036. this._blendingFactor = 0;
  32037. // The set of event that will be linked to this animation
  32038. this._events = new Array();
  32039. this.allowMatricesInterpolation = false;
  32040. this.blendingSpeed = 0.01;
  32041. this._ranges = {};
  32042. this.targetPropertyPath = targetProperty.split(".");
  32043. this.dataType = dataType;
  32044. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  32045. }
  32046. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  32047. var dataType = undefined;
  32048. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  32049. dataType = Animation.ANIMATIONTYPE_FLOAT;
  32050. }
  32051. else if (from instanceof BABYLON.Quaternion) {
  32052. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  32053. }
  32054. else if (from instanceof BABYLON.Vector3) {
  32055. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  32056. }
  32057. else if (from instanceof BABYLON.Vector2) {
  32058. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  32059. }
  32060. else if (from instanceof BABYLON.Color3) {
  32061. dataType = Animation.ANIMATIONTYPE_COLOR3;
  32062. }
  32063. else if (from instanceof BABYLON.Size) {
  32064. dataType = Animation.ANIMATIONTYPE_SIZE;
  32065. }
  32066. if (dataType == undefined) {
  32067. return null;
  32068. }
  32069. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  32070. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  32071. animation.setKeys(keys);
  32072. if (easingFunction !== undefined) {
  32073. animation.setEasingFunction(easingFunction);
  32074. }
  32075. return animation;
  32076. };
  32077. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32078. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32079. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32080. };
  32081. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32082. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32083. node.animations.push(animation);
  32084. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32085. };
  32086. // Methods
  32087. /**
  32088. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  32089. */
  32090. Animation.prototype.toString = function (fullDetails) {
  32091. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  32092. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  32093. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  32094. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  32095. if (fullDetails) {
  32096. ret += ", Ranges: {";
  32097. var first = true;
  32098. for (var name in this._ranges) {
  32099. if (first) {
  32100. ret += ", ";
  32101. first = false;
  32102. }
  32103. ret += name;
  32104. }
  32105. ret += "}";
  32106. }
  32107. return ret;
  32108. };
  32109. /**
  32110. * Add an event to this animation.
  32111. */
  32112. Animation.prototype.addEvent = function (event) {
  32113. this._events.push(event);
  32114. };
  32115. /**
  32116. * Remove all events found at the given frame
  32117. * @param frame
  32118. */
  32119. Animation.prototype.removeEvents = function (frame) {
  32120. for (var index = 0; index < this._events.length; index++) {
  32121. if (this._events[index].frame === frame) {
  32122. this._events.splice(index, 1);
  32123. index--;
  32124. }
  32125. }
  32126. };
  32127. Animation.prototype.createRange = function (name, from, to) {
  32128. // check name not already in use; could happen for bones after serialized
  32129. if (!this._ranges[name]) {
  32130. this._ranges[name] = new AnimationRange(name, from, to);
  32131. }
  32132. };
  32133. Animation.prototype.deleteRange = function (name, deleteFrames) {
  32134. if (deleteFrames === void 0) { deleteFrames = true; }
  32135. if (this._ranges[name]) {
  32136. if (deleteFrames) {
  32137. var from = this._ranges[name].from;
  32138. var to = this._ranges[name].to;
  32139. // this loop MUST go high to low for multiple splices to work
  32140. for (var key = this._keys.length - 1; key >= 0; key--) {
  32141. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  32142. this._keys.splice(key, 1);
  32143. }
  32144. }
  32145. }
  32146. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  32147. }
  32148. };
  32149. Animation.prototype.getRange = function (name) {
  32150. return this._ranges[name];
  32151. };
  32152. Animation.prototype.reset = function () {
  32153. this._offsetsCache = {};
  32154. this._highLimitsCache = {};
  32155. this.currentFrame = 0;
  32156. this._blendingFactor = 0;
  32157. this._originalBlendValue = null;
  32158. };
  32159. Animation.prototype.isStopped = function () {
  32160. return this._stopped;
  32161. };
  32162. Animation.prototype.getKeys = function () {
  32163. return this._keys;
  32164. };
  32165. Animation.prototype.getHighestFrame = function () {
  32166. var ret = 0;
  32167. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  32168. if (ret < this._keys[key].frame) {
  32169. ret = this._keys[key].frame;
  32170. }
  32171. }
  32172. return ret;
  32173. };
  32174. Animation.prototype.getEasingFunction = function () {
  32175. return this._easingFunction;
  32176. };
  32177. Animation.prototype.setEasingFunction = function (easingFunction) {
  32178. this._easingFunction = easingFunction;
  32179. };
  32180. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  32181. return startValue + (endValue - startValue) * gradient;
  32182. };
  32183. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  32184. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  32185. };
  32186. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  32187. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  32188. };
  32189. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  32190. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  32191. };
  32192. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  32193. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  32194. };
  32195. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  32196. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  32197. };
  32198. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  32199. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  32200. };
  32201. Animation.prototype.clone = function () {
  32202. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  32203. clone.enableBlending = this.enableBlending;
  32204. clone.blendingSpeed = this.blendingSpeed;
  32205. if (this._keys) {
  32206. clone.setKeys(this._keys);
  32207. }
  32208. if (this._ranges) {
  32209. clone._ranges = {};
  32210. for (var name in this._ranges) {
  32211. clone._ranges[name] = this._ranges[name].clone();
  32212. }
  32213. }
  32214. return clone;
  32215. };
  32216. Animation.prototype.setKeys = function (values) {
  32217. this._keys = values.slice(0);
  32218. this._offsetsCache = {};
  32219. this._highLimitsCache = {};
  32220. };
  32221. Animation.prototype._getKeyValue = function (value) {
  32222. if (typeof value === "function") {
  32223. return value();
  32224. }
  32225. return value;
  32226. };
  32227. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  32228. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  32229. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  32230. }
  32231. this.currentFrame = currentFrame;
  32232. // Try to get a hash to find the right key
  32233. 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));
  32234. if (this._keys[startKey].frame >= currentFrame) {
  32235. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  32236. startKey--;
  32237. }
  32238. }
  32239. for (var key = startKey; key < this._keys.length; key++) {
  32240. if (this._keys[key + 1].frame >= currentFrame) {
  32241. var startValue = this._getKeyValue(this._keys[key].value);
  32242. var endValue = this._getKeyValue(this._keys[key + 1].value);
  32243. // gradient : percent of currentFrame between the frame inf and the frame sup
  32244. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  32245. // check for easingFunction and correction of gradient
  32246. if (this._easingFunction != null) {
  32247. gradient = this._easingFunction.ease(gradient);
  32248. }
  32249. switch (this.dataType) {
  32250. // Float
  32251. case Animation.ANIMATIONTYPE_FLOAT:
  32252. switch (loopMode) {
  32253. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32254. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32255. return this.floatInterpolateFunction(startValue, endValue, gradient);
  32256. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32257. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  32258. }
  32259. break;
  32260. // Quaternion
  32261. case Animation.ANIMATIONTYPE_QUATERNION:
  32262. var quaternion = null;
  32263. switch (loopMode) {
  32264. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32265. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32266. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  32267. break;
  32268. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32269. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32270. break;
  32271. }
  32272. return quaternion;
  32273. // Vector3
  32274. case Animation.ANIMATIONTYPE_VECTOR3:
  32275. switch (loopMode) {
  32276. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32277. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32278. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  32279. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32280. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32281. }
  32282. // Vector2
  32283. case Animation.ANIMATIONTYPE_VECTOR2:
  32284. switch (loopMode) {
  32285. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32286. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32287. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  32288. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32289. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32290. }
  32291. // Size
  32292. case Animation.ANIMATIONTYPE_SIZE:
  32293. switch (loopMode) {
  32294. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32295. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32296. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  32297. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32298. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32299. }
  32300. // Color3
  32301. case Animation.ANIMATIONTYPE_COLOR3:
  32302. switch (loopMode) {
  32303. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32304. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32305. return this.color3InterpolateFunction(startValue, endValue, gradient);
  32306. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32307. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32308. }
  32309. // Matrix
  32310. case Animation.ANIMATIONTYPE_MATRIX:
  32311. switch (loopMode) {
  32312. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32313. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32314. if (this.allowMatricesInterpolation) {
  32315. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  32316. }
  32317. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32318. return startValue;
  32319. }
  32320. default:
  32321. break;
  32322. }
  32323. break;
  32324. }
  32325. }
  32326. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  32327. };
  32328. Animation.prototype.setValue = function (currentValue, blend) {
  32329. if (blend === void 0) { blend = false; }
  32330. // Set value
  32331. var path;
  32332. var destination;
  32333. if (this.targetPropertyPath.length > 1) {
  32334. var property = this._target[this.targetPropertyPath[0]];
  32335. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  32336. property = property[this.targetPropertyPath[index]];
  32337. }
  32338. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  32339. destination = property;
  32340. }
  32341. else {
  32342. path = this.targetPropertyPath[0];
  32343. destination = this._target;
  32344. }
  32345. // Blending
  32346. if (this.enableBlending && this._blendingFactor <= 1.0) {
  32347. if (!this._originalBlendValue) {
  32348. if (destination[path].clone) {
  32349. this._originalBlendValue = destination[path].clone();
  32350. }
  32351. else {
  32352. this._originalBlendValue = destination[path];
  32353. }
  32354. }
  32355. if (this._originalBlendValue.prototype) {
  32356. if (this._originalBlendValue.prototype.Lerp) {
  32357. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  32358. }
  32359. else {
  32360. destination[path] = currentValue;
  32361. }
  32362. }
  32363. else if (this._originalBlendValue.m) {
  32364. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  32365. }
  32366. else {
  32367. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  32368. }
  32369. this._blendingFactor += this.blendingSpeed;
  32370. }
  32371. else {
  32372. destination[path] = currentValue;
  32373. }
  32374. if (this._target.markAsDirty) {
  32375. this._target.markAsDirty(this.targetProperty);
  32376. }
  32377. };
  32378. Animation.prototype.goToFrame = function (frame) {
  32379. if (frame < this._keys[0].frame) {
  32380. frame = this._keys[0].frame;
  32381. }
  32382. else if (frame > this._keys[this._keys.length - 1].frame) {
  32383. frame = this._keys[this._keys.length - 1].frame;
  32384. }
  32385. var currentValue = this._interpolate(frame, 0, this.loopMode);
  32386. this.setValue(currentValue);
  32387. };
  32388. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  32389. if (blend === void 0) { blend = false; }
  32390. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  32391. this._stopped = true;
  32392. return false;
  32393. }
  32394. var returnValue = true;
  32395. // Adding a start key at frame 0 if missing
  32396. if (this._keys[0].frame !== 0) {
  32397. var newKey = { frame: 0, value: this._keys[0].value };
  32398. this._keys.splice(0, 0, newKey);
  32399. }
  32400. // Check limits
  32401. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  32402. from = this._keys[0].frame;
  32403. }
  32404. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  32405. to = this._keys[this._keys.length - 1].frame;
  32406. }
  32407. //to and from cannot be the same key
  32408. if (from === to) {
  32409. from++;
  32410. }
  32411. // Compute ratio
  32412. var range = to - from;
  32413. var offsetValue;
  32414. // ratio represents the frame delta between from and to
  32415. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  32416. var highLimitValue = 0;
  32417. if (ratio > range && !loop) {
  32418. returnValue = false;
  32419. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  32420. }
  32421. else {
  32422. // Get max value if required
  32423. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  32424. var keyOffset = to.toString() + from.toString();
  32425. if (!this._offsetsCache[keyOffset]) {
  32426. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  32427. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  32428. switch (this.dataType) {
  32429. // Float
  32430. case Animation.ANIMATIONTYPE_FLOAT:
  32431. this._offsetsCache[keyOffset] = toValue - fromValue;
  32432. break;
  32433. // Quaternion
  32434. case Animation.ANIMATIONTYPE_QUATERNION:
  32435. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32436. break;
  32437. // Vector3
  32438. case Animation.ANIMATIONTYPE_VECTOR3:
  32439. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32440. // Vector2
  32441. case Animation.ANIMATIONTYPE_VECTOR2:
  32442. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32443. // Size
  32444. case Animation.ANIMATIONTYPE_SIZE:
  32445. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32446. // Color3
  32447. case Animation.ANIMATIONTYPE_COLOR3:
  32448. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32449. default:
  32450. break;
  32451. }
  32452. this._highLimitsCache[keyOffset] = toValue;
  32453. }
  32454. highLimitValue = this._highLimitsCache[keyOffset];
  32455. offsetValue = this._offsetsCache[keyOffset];
  32456. }
  32457. }
  32458. if (offsetValue === undefined) {
  32459. switch (this.dataType) {
  32460. // Float
  32461. case Animation.ANIMATIONTYPE_FLOAT:
  32462. offsetValue = 0;
  32463. break;
  32464. // Quaternion
  32465. case Animation.ANIMATIONTYPE_QUATERNION:
  32466. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  32467. break;
  32468. // Vector3
  32469. case Animation.ANIMATIONTYPE_VECTOR3:
  32470. offsetValue = BABYLON.Vector3.Zero();
  32471. break;
  32472. // Vector2
  32473. case Animation.ANIMATIONTYPE_VECTOR2:
  32474. offsetValue = BABYLON.Vector2.Zero();
  32475. break;
  32476. // Size
  32477. case Animation.ANIMATIONTYPE_SIZE:
  32478. offsetValue = BABYLON.Size.Zero();
  32479. break;
  32480. // Color3
  32481. case Animation.ANIMATIONTYPE_COLOR3:
  32482. offsetValue = BABYLON.Color3.Black();
  32483. }
  32484. }
  32485. // Compute value
  32486. var repeatCount = (ratio / range) >> 0;
  32487. var currentFrame = returnValue ? from + ratio % range : to;
  32488. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  32489. // Set value
  32490. this.setValue(currentValue);
  32491. // Check events
  32492. for (var index = 0; index < this._events.length; index++) {
  32493. if (currentFrame >= this._events[index].frame) {
  32494. var event = this._events[index];
  32495. if (!event.isDone) {
  32496. // If event should be done only once, remove it.
  32497. if (event.onlyOnce) {
  32498. this._events.splice(index, 1);
  32499. index--;
  32500. }
  32501. event.isDone = true;
  32502. event.action();
  32503. } // Don't do anything if the event has already be done.
  32504. }
  32505. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  32506. // reset event, the animation is looping
  32507. this._events[index].isDone = false;
  32508. }
  32509. }
  32510. if (!returnValue) {
  32511. this._stopped = true;
  32512. }
  32513. return returnValue;
  32514. };
  32515. Animation.prototype.serialize = function () {
  32516. var serializationObject = {};
  32517. serializationObject.name = this.name;
  32518. serializationObject.property = this.targetProperty;
  32519. serializationObject.framePerSecond = this.framePerSecond;
  32520. serializationObject.dataType = this.dataType;
  32521. serializationObject.loopBehavior = this.loopMode;
  32522. serializationObject.enableBlending = this.enableBlending;
  32523. serializationObject.blendingSpeed = this.blendingSpeed;
  32524. var dataType = this.dataType;
  32525. serializationObject.keys = [];
  32526. var keys = this.getKeys();
  32527. for (var index = 0; index < keys.length; index++) {
  32528. var animationKey = keys[index];
  32529. var key = {};
  32530. key.frame = animationKey.frame;
  32531. switch (dataType) {
  32532. case Animation.ANIMATIONTYPE_FLOAT:
  32533. key.values = [animationKey.value];
  32534. break;
  32535. case Animation.ANIMATIONTYPE_QUATERNION:
  32536. case Animation.ANIMATIONTYPE_MATRIX:
  32537. case Animation.ANIMATIONTYPE_VECTOR3:
  32538. case Animation.ANIMATIONTYPE_COLOR3:
  32539. key.values = animationKey.value.asArray();
  32540. break;
  32541. }
  32542. serializationObject.keys.push(key);
  32543. }
  32544. serializationObject.ranges = [];
  32545. for (var name in this._ranges) {
  32546. var range = {};
  32547. range.name = name;
  32548. range.from = this._ranges[name].from;
  32549. range.to = this._ranges[name].to;
  32550. serializationObject.ranges.push(range);
  32551. }
  32552. return serializationObject;
  32553. };
  32554. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  32555. get: function () {
  32556. return Animation._ANIMATIONTYPE_FLOAT;
  32557. },
  32558. enumerable: true,
  32559. configurable: true
  32560. });
  32561. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  32562. get: function () {
  32563. return Animation._ANIMATIONTYPE_VECTOR3;
  32564. },
  32565. enumerable: true,
  32566. configurable: true
  32567. });
  32568. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  32569. get: function () {
  32570. return Animation._ANIMATIONTYPE_VECTOR2;
  32571. },
  32572. enumerable: true,
  32573. configurable: true
  32574. });
  32575. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  32576. get: function () {
  32577. return Animation._ANIMATIONTYPE_SIZE;
  32578. },
  32579. enumerable: true,
  32580. configurable: true
  32581. });
  32582. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  32583. get: function () {
  32584. return Animation._ANIMATIONTYPE_QUATERNION;
  32585. },
  32586. enumerable: true,
  32587. configurable: true
  32588. });
  32589. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  32590. get: function () {
  32591. return Animation._ANIMATIONTYPE_MATRIX;
  32592. },
  32593. enumerable: true,
  32594. configurable: true
  32595. });
  32596. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  32597. get: function () {
  32598. return Animation._ANIMATIONTYPE_COLOR3;
  32599. },
  32600. enumerable: true,
  32601. configurable: true
  32602. });
  32603. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  32604. get: function () {
  32605. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  32606. },
  32607. enumerable: true,
  32608. configurable: true
  32609. });
  32610. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  32611. get: function () {
  32612. return Animation._ANIMATIONLOOPMODE_CYCLE;
  32613. },
  32614. enumerable: true,
  32615. configurable: true
  32616. });
  32617. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  32618. get: function () {
  32619. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  32620. },
  32621. enumerable: true,
  32622. configurable: true
  32623. });
  32624. Animation.Parse = function (parsedAnimation) {
  32625. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  32626. var dataType = parsedAnimation.dataType;
  32627. var keys = [];
  32628. var data;
  32629. var index;
  32630. if (parsedAnimation.enableBlending) {
  32631. animation.enableBlending = parsedAnimation.enableBlending;
  32632. }
  32633. if (parsedAnimation.blendingSpeed) {
  32634. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  32635. }
  32636. for (index = 0; index < parsedAnimation.keys.length; index++) {
  32637. var key = parsedAnimation.keys[index];
  32638. switch (dataType) {
  32639. case Animation.ANIMATIONTYPE_FLOAT:
  32640. data = key.values[0];
  32641. break;
  32642. case Animation.ANIMATIONTYPE_QUATERNION:
  32643. data = BABYLON.Quaternion.FromArray(key.values);
  32644. break;
  32645. case Animation.ANIMATIONTYPE_MATRIX:
  32646. data = BABYLON.Matrix.FromArray(key.values);
  32647. break;
  32648. case Animation.ANIMATIONTYPE_COLOR3:
  32649. data = BABYLON.Color3.FromArray(key.values);
  32650. break;
  32651. case Animation.ANIMATIONTYPE_VECTOR3:
  32652. default:
  32653. data = BABYLON.Vector3.FromArray(key.values);
  32654. break;
  32655. }
  32656. keys.push({
  32657. frame: key.frame,
  32658. value: data
  32659. });
  32660. }
  32661. animation.setKeys(keys);
  32662. if (parsedAnimation.ranges) {
  32663. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  32664. data = parsedAnimation.ranges[index];
  32665. animation.createRange(data.name, data.from, data.to);
  32666. }
  32667. }
  32668. return animation;
  32669. };
  32670. Animation.AppendSerializedAnimations = function (source, destination) {
  32671. if (source.animations) {
  32672. destination.animations = [];
  32673. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  32674. var animation = source.animations[animationIndex];
  32675. destination.animations.push(animation.serialize());
  32676. }
  32677. }
  32678. };
  32679. return Animation;
  32680. }());
  32681. // Statics
  32682. Animation._ANIMATIONTYPE_FLOAT = 0;
  32683. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  32684. Animation._ANIMATIONTYPE_QUATERNION = 2;
  32685. Animation._ANIMATIONTYPE_MATRIX = 3;
  32686. Animation._ANIMATIONTYPE_COLOR3 = 4;
  32687. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  32688. Animation._ANIMATIONTYPE_SIZE = 6;
  32689. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  32690. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  32691. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  32692. BABYLON.Animation = Animation;
  32693. })(BABYLON || (BABYLON = {}));
  32694. //# sourceMappingURL=babylon.animation.js.map
  32695. var BABYLON;
  32696. (function (BABYLON) {
  32697. var Animatable = (function () {
  32698. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  32699. if (fromFrame === void 0) { fromFrame = 0; }
  32700. if (toFrame === void 0) { toFrame = 100; }
  32701. if (loopAnimation === void 0) { loopAnimation = false; }
  32702. if (speedRatio === void 0) { speedRatio = 1.0; }
  32703. this.target = target;
  32704. this.fromFrame = fromFrame;
  32705. this.toFrame = toFrame;
  32706. this.loopAnimation = loopAnimation;
  32707. this.speedRatio = speedRatio;
  32708. this.onAnimationEnd = onAnimationEnd;
  32709. this._animations = new Array();
  32710. this._paused = false;
  32711. this.animationStarted = false;
  32712. if (animations) {
  32713. this.appendAnimations(target, animations);
  32714. }
  32715. this._scene = scene;
  32716. scene._activeAnimatables.push(this);
  32717. }
  32718. // Methods
  32719. Animatable.prototype.getAnimations = function () {
  32720. return this._animations;
  32721. };
  32722. Animatable.prototype.appendAnimations = function (target, animations) {
  32723. for (var index = 0; index < animations.length; index++) {
  32724. var animation = animations[index];
  32725. animation._target = target;
  32726. this._animations.push(animation);
  32727. }
  32728. };
  32729. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  32730. var animations = this._animations;
  32731. for (var index = 0; index < animations.length; index++) {
  32732. if (animations[index].targetProperty === property) {
  32733. return animations[index];
  32734. }
  32735. }
  32736. return null;
  32737. };
  32738. Animatable.prototype.reset = function () {
  32739. var animations = this._animations;
  32740. for (var index = 0; index < animations.length; index++) {
  32741. animations[index].reset();
  32742. }
  32743. this._localDelayOffset = null;
  32744. this._pausedDelay = null;
  32745. };
  32746. Animatable.prototype.enableBlending = function (blendingSpeed) {
  32747. var animations = this._animations;
  32748. for (var index = 0; index < animations.length; index++) {
  32749. animations[index].enableBlending = true;
  32750. animations[index].blendingSpeed = blendingSpeed;
  32751. }
  32752. };
  32753. Animatable.prototype.disableBlending = function () {
  32754. var animations = this._animations;
  32755. for (var index = 0; index < animations.length; index++) {
  32756. animations[index].enableBlending = false;
  32757. }
  32758. };
  32759. Animatable.prototype.goToFrame = function (frame) {
  32760. var animations = this._animations;
  32761. if (animations[0]) {
  32762. var fps = animations[0].framePerSecond;
  32763. var currentFrame = animations[0].currentFrame;
  32764. var adjustTime = frame - currentFrame;
  32765. var delay = adjustTime * 1000 / fps;
  32766. this._localDelayOffset -= delay;
  32767. }
  32768. for (var index = 0; index < animations.length; index++) {
  32769. animations[index].goToFrame(frame);
  32770. }
  32771. };
  32772. Animatable.prototype.pause = function () {
  32773. if (this._paused) {
  32774. return;
  32775. }
  32776. this._paused = true;
  32777. };
  32778. Animatable.prototype.restart = function () {
  32779. this._paused = false;
  32780. };
  32781. Animatable.prototype.stop = function (animationName) {
  32782. if (animationName) {
  32783. var idx = this._scene._activeAnimatables.indexOf(this);
  32784. if (idx > -1) {
  32785. var animations = this._animations;
  32786. for (var index = animations.length - 1; index >= 0; index--) {
  32787. if (typeof animationName === "string" && animations[index].name != animationName) {
  32788. continue;
  32789. }
  32790. animations[index].reset();
  32791. animations.splice(index, 1);
  32792. }
  32793. if (animations.length == 0) {
  32794. this._scene._activeAnimatables.splice(idx, 1);
  32795. if (this.onAnimationEnd) {
  32796. this.onAnimationEnd();
  32797. }
  32798. }
  32799. }
  32800. }
  32801. else {
  32802. var index = this._scene._activeAnimatables.indexOf(this);
  32803. if (index > -1) {
  32804. this._scene._activeAnimatables.splice(index, 1);
  32805. var animations = this._animations;
  32806. for (var index = 0; index < animations.length; index++) {
  32807. animations[index].reset();
  32808. }
  32809. if (this.onAnimationEnd) {
  32810. this.onAnimationEnd();
  32811. }
  32812. }
  32813. }
  32814. };
  32815. Animatable.prototype._animate = function (delay) {
  32816. if (this._paused) {
  32817. this.animationStarted = false;
  32818. if (!this._pausedDelay) {
  32819. this._pausedDelay = delay;
  32820. }
  32821. return true;
  32822. }
  32823. if (!this._localDelayOffset) {
  32824. this._localDelayOffset = delay;
  32825. }
  32826. else if (this._pausedDelay) {
  32827. this._localDelayOffset += delay - this._pausedDelay;
  32828. this._pausedDelay = null;
  32829. }
  32830. // Animating
  32831. var running = false;
  32832. var animations = this._animations;
  32833. var index;
  32834. for (index = 0; index < animations.length; index++) {
  32835. var animation = animations[index];
  32836. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  32837. running = running || isRunning;
  32838. }
  32839. this.animationStarted = running;
  32840. if (!running) {
  32841. // Remove from active animatables
  32842. index = this._scene._activeAnimatables.indexOf(this);
  32843. this._scene._activeAnimatables.splice(index, 1);
  32844. }
  32845. if (!running && this.onAnimationEnd) {
  32846. this.onAnimationEnd();
  32847. this.onAnimationEnd = null;
  32848. }
  32849. return running;
  32850. };
  32851. return Animatable;
  32852. }());
  32853. BABYLON.Animatable = Animatable;
  32854. })(BABYLON || (BABYLON = {}));
  32855. //# sourceMappingURL=babylon.animatable.js.map
  32856. var BABYLON;
  32857. (function (BABYLON) {
  32858. var EasingFunction = (function () {
  32859. function EasingFunction() {
  32860. // Properties
  32861. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  32862. }
  32863. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  32864. get: function () {
  32865. return EasingFunction._EASINGMODE_EASEIN;
  32866. },
  32867. enumerable: true,
  32868. configurable: true
  32869. });
  32870. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  32871. get: function () {
  32872. return EasingFunction._EASINGMODE_EASEOUT;
  32873. },
  32874. enumerable: true,
  32875. configurable: true
  32876. });
  32877. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  32878. get: function () {
  32879. return EasingFunction._EASINGMODE_EASEINOUT;
  32880. },
  32881. enumerable: true,
  32882. configurable: true
  32883. });
  32884. EasingFunction.prototype.setEasingMode = function (easingMode) {
  32885. var n = Math.min(Math.max(easingMode, 0), 2);
  32886. this._easingMode = n;
  32887. };
  32888. EasingFunction.prototype.getEasingMode = function () {
  32889. return this._easingMode;
  32890. };
  32891. EasingFunction.prototype.easeInCore = function (gradient) {
  32892. throw new Error('You must implement this method');
  32893. };
  32894. EasingFunction.prototype.ease = function (gradient) {
  32895. switch (this._easingMode) {
  32896. case EasingFunction.EASINGMODE_EASEIN:
  32897. return this.easeInCore(gradient);
  32898. case EasingFunction.EASINGMODE_EASEOUT:
  32899. return (1 - this.easeInCore(1 - gradient));
  32900. }
  32901. if (gradient >= 0.5) {
  32902. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  32903. }
  32904. return (this.easeInCore(gradient * 2) * 0.5);
  32905. };
  32906. return EasingFunction;
  32907. }());
  32908. //Statics
  32909. EasingFunction._EASINGMODE_EASEIN = 0;
  32910. EasingFunction._EASINGMODE_EASEOUT = 1;
  32911. EasingFunction._EASINGMODE_EASEINOUT = 2;
  32912. BABYLON.EasingFunction = EasingFunction;
  32913. var CircleEase = (function (_super) {
  32914. __extends(CircleEase, _super);
  32915. function CircleEase() {
  32916. return _super !== null && _super.apply(this, arguments) || this;
  32917. }
  32918. CircleEase.prototype.easeInCore = function (gradient) {
  32919. gradient = Math.max(0, Math.min(1, gradient));
  32920. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  32921. };
  32922. return CircleEase;
  32923. }(EasingFunction));
  32924. BABYLON.CircleEase = CircleEase;
  32925. var BackEase = (function (_super) {
  32926. __extends(BackEase, _super);
  32927. function BackEase(amplitude) {
  32928. if (amplitude === void 0) { amplitude = 1; }
  32929. var _this = _super.call(this) || this;
  32930. _this.amplitude = amplitude;
  32931. return _this;
  32932. }
  32933. BackEase.prototype.easeInCore = function (gradient) {
  32934. var num = Math.max(0, this.amplitude);
  32935. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  32936. };
  32937. return BackEase;
  32938. }(EasingFunction));
  32939. BABYLON.BackEase = BackEase;
  32940. var BounceEase = (function (_super) {
  32941. __extends(BounceEase, _super);
  32942. function BounceEase(bounces, bounciness) {
  32943. if (bounces === void 0) { bounces = 3; }
  32944. if (bounciness === void 0) { bounciness = 2; }
  32945. var _this = _super.call(this) || this;
  32946. _this.bounces = bounces;
  32947. _this.bounciness = bounciness;
  32948. return _this;
  32949. }
  32950. BounceEase.prototype.easeInCore = function (gradient) {
  32951. var y = Math.max(0.0, this.bounces);
  32952. var bounciness = this.bounciness;
  32953. if (bounciness <= 1.0) {
  32954. bounciness = 1.001;
  32955. }
  32956. var num9 = Math.pow(bounciness, y);
  32957. var num5 = 1.0 - bounciness;
  32958. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  32959. var num15 = gradient * num4;
  32960. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  32961. var num3 = Math.floor(num65);
  32962. var num13 = num3 + 1.0;
  32963. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  32964. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  32965. var num7 = (num8 + num12) * 0.5;
  32966. var num6 = gradient - num7;
  32967. var num2 = num7 - num8;
  32968. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  32969. };
  32970. return BounceEase;
  32971. }(EasingFunction));
  32972. BABYLON.BounceEase = BounceEase;
  32973. var CubicEase = (function (_super) {
  32974. __extends(CubicEase, _super);
  32975. function CubicEase() {
  32976. return _super !== null && _super.apply(this, arguments) || this;
  32977. }
  32978. CubicEase.prototype.easeInCore = function (gradient) {
  32979. return (gradient * gradient * gradient);
  32980. };
  32981. return CubicEase;
  32982. }(EasingFunction));
  32983. BABYLON.CubicEase = CubicEase;
  32984. var ElasticEase = (function (_super) {
  32985. __extends(ElasticEase, _super);
  32986. function ElasticEase(oscillations, springiness) {
  32987. if (oscillations === void 0) { oscillations = 3; }
  32988. if (springiness === void 0) { springiness = 3; }
  32989. var _this = _super.call(this) || this;
  32990. _this.oscillations = oscillations;
  32991. _this.springiness = springiness;
  32992. return _this;
  32993. }
  32994. ElasticEase.prototype.easeInCore = function (gradient) {
  32995. var num2;
  32996. var num3 = Math.max(0.0, this.oscillations);
  32997. var num = Math.max(0.0, this.springiness);
  32998. if (num == 0) {
  32999. num2 = gradient;
  33000. }
  33001. else {
  33002. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  33003. }
  33004. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  33005. };
  33006. return ElasticEase;
  33007. }(EasingFunction));
  33008. BABYLON.ElasticEase = ElasticEase;
  33009. var ExponentialEase = (function (_super) {
  33010. __extends(ExponentialEase, _super);
  33011. function ExponentialEase(exponent) {
  33012. if (exponent === void 0) { exponent = 2; }
  33013. var _this = _super.call(this) || this;
  33014. _this.exponent = exponent;
  33015. return _this;
  33016. }
  33017. ExponentialEase.prototype.easeInCore = function (gradient) {
  33018. if (this.exponent <= 0) {
  33019. return gradient;
  33020. }
  33021. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  33022. };
  33023. return ExponentialEase;
  33024. }(EasingFunction));
  33025. BABYLON.ExponentialEase = ExponentialEase;
  33026. var PowerEase = (function (_super) {
  33027. __extends(PowerEase, _super);
  33028. function PowerEase(power) {
  33029. if (power === void 0) { power = 2; }
  33030. var _this = _super.call(this) || this;
  33031. _this.power = power;
  33032. return _this;
  33033. }
  33034. PowerEase.prototype.easeInCore = function (gradient) {
  33035. var y = Math.max(0.0, this.power);
  33036. return Math.pow(gradient, y);
  33037. };
  33038. return PowerEase;
  33039. }(EasingFunction));
  33040. BABYLON.PowerEase = PowerEase;
  33041. var QuadraticEase = (function (_super) {
  33042. __extends(QuadraticEase, _super);
  33043. function QuadraticEase() {
  33044. return _super !== null && _super.apply(this, arguments) || this;
  33045. }
  33046. QuadraticEase.prototype.easeInCore = function (gradient) {
  33047. return (gradient * gradient);
  33048. };
  33049. return QuadraticEase;
  33050. }(EasingFunction));
  33051. BABYLON.QuadraticEase = QuadraticEase;
  33052. var QuarticEase = (function (_super) {
  33053. __extends(QuarticEase, _super);
  33054. function QuarticEase() {
  33055. return _super !== null && _super.apply(this, arguments) || this;
  33056. }
  33057. QuarticEase.prototype.easeInCore = function (gradient) {
  33058. return (gradient * gradient * gradient * gradient);
  33059. };
  33060. return QuarticEase;
  33061. }(EasingFunction));
  33062. BABYLON.QuarticEase = QuarticEase;
  33063. var QuinticEase = (function (_super) {
  33064. __extends(QuinticEase, _super);
  33065. function QuinticEase() {
  33066. return _super !== null && _super.apply(this, arguments) || this;
  33067. }
  33068. QuinticEase.prototype.easeInCore = function (gradient) {
  33069. return (gradient * gradient * gradient * gradient * gradient);
  33070. };
  33071. return QuinticEase;
  33072. }(EasingFunction));
  33073. BABYLON.QuinticEase = QuinticEase;
  33074. var SineEase = (function (_super) {
  33075. __extends(SineEase, _super);
  33076. function SineEase() {
  33077. return _super !== null && _super.apply(this, arguments) || this;
  33078. }
  33079. SineEase.prototype.easeInCore = function (gradient) {
  33080. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  33081. };
  33082. return SineEase;
  33083. }(EasingFunction));
  33084. BABYLON.SineEase = SineEase;
  33085. var BezierCurveEase = (function (_super) {
  33086. __extends(BezierCurveEase, _super);
  33087. function BezierCurveEase(x1, y1, x2, y2) {
  33088. if (x1 === void 0) { x1 = 0; }
  33089. if (y1 === void 0) { y1 = 0; }
  33090. if (x2 === void 0) { x2 = 1; }
  33091. if (y2 === void 0) { y2 = 1; }
  33092. var _this = _super.call(this) || this;
  33093. _this.x1 = x1;
  33094. _this.y1 = y1;
  33095. _this.x2 = x2;
  33096. _this.y2 = y2;
  33097. return _this;
  33098. }
  33099. BezierCurveEase.prototype.easeInCore = function (gradient) {
  33100. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  33101. };
  33102. return BezierCurveEase;
  33103. }(EasingFunction));
  33104. BABYLON.BezierCurveEase = BezierCurveEase;
  33105. })(BABYLON || (BABYLON = {}));
  33106. //# sourceMappingURL=babylon.easing.js.map
  33107. /// <reference path="..\babylon.node.ts" />
  33108. var BABYLON;
  33109. (function (BABYLON) {
  33110. var Bone = (function (_super) {
  33111. __extends(Bone, _super);
  33112. function Bone(name, skeleton, parentBone, matrix, restPose) {
  33113. var _this = _super.call(this, name, skeleton.getScene()) || this;
  33114. _this.name = name;
  33115. _this.children = new Array();
  33116. _this.animations = new Array();
  33117. _this._worldTransform = new BABYLON.Matrix();
  33118. _this._absoluteTransform = new BABYLON.Matrix();
  33119. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  33120. _this._scaleMatrix = BABYLON.Matrix.Identity();
  33121. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  33122. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  33123. _this._scalingDeterminant = 1;
  33124. _this._skeleton = skeleton;
  33125. _this._localMatrix = matrix;
  33126. _this._baseMatrix = matrix.clone();
  33127. _this._restPose = restPose ? restPose : matrix.clone();
  33128. skeleton.bones.push(_this);
  33129. if (parentBone) {
  33130. _this._parent = parentBone;
  33131. parentBone.children.push(_this);
  33132. }
  33133. else {
  33134. _this._parent = null;
  33135. }
  33136. _this._updateDifferenceMatrix();
  33137. if (_this.getAbsoluteTransform().determinant() < 0) {
  33138. _this._scalingDeterminant *= -1;
  33139. }
  33140. return _this;
  33141. }
  33142. Object.defineProperty(Bone.prototype, "_matrix", {
  33143. get: function () {
  33144. return this._localMatrix;
  33145. },
  33146. set: function (val) {
  33147. if (this._localMatrix) {
  33148. this._localMatrix.copyFrom(val);
  33149. }
  33150. else {
  33151. this._localMatrix = val;
  33152. }
  33153. },
  33154. enumerable: true,
  33155. configurable: true
  33156. });
  33157. // Members
  33158. Bone.prototype.getParent = function () {
  33159. return this._parent;
  33160. };
  33161. Bone.prototype.getLocalMatrix = function () {
  33162. return this._localMatrix;
  33163. };
  33164. Bone.prototype.getBaseMatrix = function () {
  33165. return this._baseMatrix;
  33166. };
  33167. Bone.prototype.getRestPose = function () {
  33168. return this._restPose;
  33169. };
  33170. Bone.prototype.returnToRest = function () {
  33171. this.updateMatrix(this._restPose.clone());
  33172. };
  33173. Bone.prototype.getWorldMatrix = function () {
  33174. return this._worldTransform;
  33175. };
  33176. Bone.prototype.getInvertedAbsoluteTransform = function () {
  33177. return this._invertedAbsoluteTransform;
  33178. };
  33179. Bone.prototype.getAbsoluteTransform = function () {
  33180. return this._absoluteTransform;
  33181. };
  33182. // Methods
  33183. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  33184. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  33185. this._baseMatrix = matrix.clone();
  33186. this._localMatrix = matrix.clone();
  33187. this._skeleton._markAsDirty();
  33188. if (updateDifferenceMatrix) {
  33189. this._updateDifferenceMatrix();
  33190. }
  33191. };
  33192. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  33193. if (!rootMatrix) {
  33194. rootMatrix = this._baseMatrix;
  33195. }
  33196. if (this._parent) {
  33197. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  33198. }
  33199. else {
  33200. this._absoluteTransform.copyFrom(rootMatrix);
  33201. }
  33202. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  33203. for (var index = 0; index < this.children.length; index++) {
  33204. this.children[index]._updateDifferenceMatrix();
  33205. }
  33206. };
  33207. Bone.prototype.markAsDirty = function () {
  33208. this._currentRenderId++;
  33209. this._skeleton._markAsDirty();
  33210. };
  33211. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  33212. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  33213. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  33214. // all animation may be coming from a library skeleton, so may need to create animation
  33215. if (this.animations.length === 0) {
  33216. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  33217. this.animations[0].setKeys([]);
  33218. }
  33219. // get animation info / verify there is such a range from the source bone
  33220. var sourceRange = source.animations[0].getRange(rangeName);
  33221. if (!sourceRange) {
  33222. return false;
  33223. }
  33224. var from = sourceRange.from;
  33225. var to = sourceRange.to;
  33226. var sourceKeys = source.animations[0].getKeys();
  33227. // rescaling prep
  33228. var sourceBoneLength = source.length;
  33229. var sourceParent = source.getParent();
  33230. var parent = this.getParent();
  33231. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  33232. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  33233. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  33234. var destKeys = this.animations[0].getKeys();
  33235. // loop vars declaration
  33236. var orig;
  33237. var origTranslation;
  33238. var mat;
  33239. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  33240. orig = sourceKeys[key];
  33241. if (orig.frame >= from && orig.frame <= to) {
  33242. if (rescaleAsRequired) {
  33243. mat = orig.value.clone();
  33244. // scale based on parent ratio, when bone has parent
  33245. if (parentScalingReqd) {
  33246. origTranslation = mat.getTranslation();
  33247. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  33248. }
  33249. else if (dimensionsScalingReqd) {
  33250. origTranslation = mat.getTranslation();
  33251. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  33252. }
  33253. else {
  33254. mat = orig.value;
  33255. }
  33256. }
  33257. else {
  33258. mat = orig.value;
  33259. }
  33260. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  33261. }
  33262. }
  33263. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  33264. return true;
  33265. };
  33266. /**
  33267. * Translate the bone in local or world space.
  33268. * @param vec The amount to translate the bone.
  33269. * @param space The space that the translation is in.
  33270. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33271. */
  33272. Bone.prototype.translate = function (vec, space, mesh) {
  33273. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33274. var lm = this.getLocalMatrix();
  33275. if (space == BABYLON.Space.LOCAL) {
  33276. lm.m[12] += vec.x;
  33277. lm.m[13] += vec.y;
  33278. lm.m[14] += vec.z;
  33279. }
  33280. else {
  33281. this._skeleton.computeAbsoluteTransforms();
  33282. var tmat = BABYLON.Tmp.Matrix[0];
  33283. var tvec = BABYLON.Tmp.Vector3[0];
  33284. if (mesh) {
  33285. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33286. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  33287. }
  33288. else {
  33289. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33290. }
  33291. tmat.m[12] = 0;
  33292. tmat.m[13] = 0;
  33293. tmat.m[14] = 0;
  33294. tmat.invert();
  33295. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  33296. lm.m[12] += tvec.x;
  33297. lm.m[13] += tvec.y;
  33298. lm.m[14] += tvec.z;
  33299. }
  33300. this.markAsDirty();
  33301. };
  33302. /**
  33303. * Set the postion of the bone in local or world space.
  33304. * @param position The position to set the bone.
  33305. * @param space The space that the position is in.
  33306. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33307. */
  33308. Bone.prototype.setPosition = function (position, space, mesh) {
  33309. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33310. var lm = this.getLocalMatrix();
  33311. if (space == BABYLON.Space.LOCAL) {
  33312. lm.m[12] = position.x;
  33313. lm.m[13] = position.y;
  33314. lm.m[14] = position.z;
  33315. }
  33316. else {
  33317. this._skeleton.computeAbsoluteTransforms();
  33318. var tmat = BABYLON.Tmp.Matrix[0];
  33319. var vec = BABYLON.Tmp.Vector3[0];
  33320. if (mesh) {
  33321. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33322. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  33323. }
  33324. else {
  33325. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33326. }
  33327. tmat.invert();
  33328. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  33329. lm.m[12] = vec.x;
  33330. lm.m[13] = vec.y;
  33331. lm.m[14] = vec.z;
  33332. }
  33333. this.markAsDirty();
  33334. };
  33335. /**
  33336. * Set the absolute postion of the bone (world space).
  33337. * @param position The position to set the bone.
  33338. * @param mesh The mesh that this bone is attached to.
  33339. */
  33340. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  33341. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  33342. };
  33343. /**
  33344. * Set the scale of the bone on the x, y and z axes.
  33345. * @param x The scale of the bone on the x axis.
  33346. * @param x The scale of the bone on the y axis.
  33347. * @param z The scale of the bone on the z axis.
  33348. * @param scaleChildren Set this to true if children of the bone should be scaled.
  33349. */
  33350. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  33351. if (scaleChildren === void 0) { scaleChildren = false; }
  33352. if (this.animations[0] && !this.animations[0].isStopped()) {
  33353. if (!scaleChildren) {
  33354. this._negateScaleChildren.x = 1 / x;
  33355. this._negateScaleChildren.y = 1 / y;
  33356. this._negateScaleChildren.z = 1 / z;
  33357. }
  33358. this._syncScaleVector();
  33359. }
  33360. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  33361. };
  33362. /**
  33363. * Scale the bone on the x, y and z axes.
  33364. * @param x The amount to scale the bone on the x axis.
  33365. * @param x The amount to scale the bone on the y axis.
  33366. * @param z The amount to scale the bone on the z axis.
  33367. * @param scaleChildren Set this to true if children of the bone should be scaled.
  33368. */
  33369. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  33370. if (scaleChildren === void 0) { scaleChildren = false; }
  33371. var locMat = this.getLocalMatrix();
  33372. var origLocMat = BABYLON.Tmp.Matrix[0];
  33373. origLocMat.copyFrom(locMat);
  33374. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  33375. origLocMatInv.copyFrom(origLocMat);
  33376. origLocMatInv.invert();
  33377. var scaleMat = BABYLON.Tmp.Matrix[2];
  33378. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  33379. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  33380. this._scaleVector.x *= x;
  33381. this._scaleVector.y *= y;
  33382. this._scaleVector.z *= z;
  33383. locMat.multiplyToRef(origLocMatInv, locMat);
  33384. locMat.multiplyToRef(scaleMat, locMat);
  33385. locMat.multiplyToRef(origLocMat, locMat);
  33386. var parent = this.getParent();
  33387. if (parent) {
  33388. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  33389. }
  33390. else {
  33391. this.getAbsoluteTransform().copyFrom(locMat);
  33392. }
  33393. var len = this.children.length;
  33394. scaleMat.invert();
  33395. for (var i = 0; i < len; i++) {
  33396. var child = this.children[i];
  33397. var cm = child.getLocalMatrix();
  33398. cm.multiplyToRef(scaleMat, cm);
  33399. var lm = child.getLocalMatrix();
  33400. lm.m[12] *= x;
  33401. lm.m[13] *= y;
  33402. lm.m[14] *= z;
  33403. }
  33404. this.computeAbsoluteTransforms();
  33405. if (scaleChildren) {
  33406. for (var i = 0; i < len; i++) {
  33407. this.children[i].scale(x, y, z, scaleChildren);
  33408. }
  33409. }
  33410. this.markAsDirty();
  33411. };
  33412. /**
  33413. * Set the yaw, pitch, and roll of the bone in local or world space.
  33414. * @param yaw The rotation of the bone on the y axis.
  33415. * @param pitch The rotation of the bone on the x axis.
  33416. * @param roll The rotation of the bone on the z axis.
  33417. * @param space The space that the axes of rotation are in.
  33418. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33419. */
  33420. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  33421. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33422. var rotMat = BABYLON.Tmp.Matrix[0];
  33423. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  33424. var rotMatInv = BABYLON.Tmp.Matrix[1];
  33425. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  33426. rotMatInv.multiplyToRef(rotMat, rotMat);
  33427. this._rotateWithMatrix(rotMat, space, mesh);
  33428. };
  33429. /**
  33430. * Rotate the bone on an axis in local or world space.
  33431. * @param axis The axis to rotate the bone on.
  33432. * @param amount The amount to rotate the bone.
  33433. * @param space The space that the axis is in.
  33434. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33435. */
  33436. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  33437. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33438. var rmat = BABYLON.Tmp.Matrix[0];
  33439. rmat.m[12] = 0;
  33440. rmat.m[13] = 0;
  33441. rmat.m[14] = 0;
  33442. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  33443. this._rotateWithMatrix(rmat, space, mesh);
  33444. };
  33445. /**
  33446. * Set the rotation of the bone to a particular axis angle in local or world space.
  33447. * @param axis The axis to rotate the bone on.
  33448. * @param angle The angle that the bone should be rotated to.
  33449. * @param space The space that the axis is in.
  33450. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33451. */
  33452. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  33453. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33454. var rotMat = BABYLON.Tmp.Matrix[0];
  33455. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  33456. var rotMatInv = BABYLON.Tmp.Matrix[1];
  33457. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  33458. rotMatInv.multiplyToRef(rotMat, rotMat);
  33459. this._rotateWithMatrix(rotMat, space, mesh);
  33460. };
  33461. /**
  33462. * Set the euler rotation of the bone in local of world space.
  33463. * @param rotation The euler rotation that the bone should be set to.
  33464. * @param space The space that the rotation is in.
  33465. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33466. */
  33467. Bone.prototype.setRotation = function (rotation, space, mesh) {
  33468. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33469. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  33470. };
  33471. /**
  33472. * Set the quaternion rotation of the bone in local of world space.
  33473. * @param quat The quaternion rotation that the bone should be set to.
  33474. * @param space The space that the rotation is in.
  33475. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33476. */
  33477. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  33478. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33479. var rotMatInv = BABYLON.Tmp.Matrix[0];
  33480. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  33481. var rotMat = BABYLON.Tmp.Matrix[1];
  33482. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  33483. rotMatInv.multiplyToRef(rotMat, rotMat);
  33484. this._rotateWithMatrix(rotMat, space, mesh);
  33485. };
  33486. /**
  33487. * Set the rotation matrix of the bone in local of world space.
  33488. * @param rotMat The rotation matrix that the bone should be set to.
  33489. * @param space The space that the rotation is in.
  33490. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33491. */
  33492. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  33493. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33494. var rotMatInv = BABYLON.Tmp.Matrix[0];
  33495. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  33496. var rotMat2 = BABYLON.Tmp.Matrix[1];
  33497. rotMat2.copyFrom(rotMat);
  33498. rotMatInv.multiplyToRef(rotMat, rotMat2);
  33499. this._rotateWithMatrix(rotMat2, space, mesh);
  33500. };
  33501. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  33502. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33503. var lmat = this.getLocalMatrix();
  33504. var lx = lmat.m[12];
  33505. var ly = lmat.m[13];
  33506. var lz = lmat.m[14];
  33507. var parent = this.getParent();
  33508. var parentScale = BABYLON.Tmp.Matrix[3];
  33509. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  33510. if (parent) {
  33511. if (space == BABYLON.Space.WORLD) {
  33512. if (mesh) {
  33513. parentScale.copyFrom(mesh.getWorldMatrix());
  33514. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  33515. }
  33516. else {
  33517. parentScale.copyFrom(parent.getAbsoluteTransform());
  33518. }
  33519. }
  33520. else {
  33521. parentScale = parent._scaleMatrix;
  33522. }
  33523. parentScaleInv.copyFrom(parentScale);
  33524. parentScaleInv.invert();
  33525. lmat.multiplyToRef(parentScale, lmat);
  33526. lmat.multiplyToRef(rmat, lmat);
  33527. lmat.multiplyToRef(parentScaleInv, lmat);
  33528. }
  33529. else {
  33530. if (space == BABYLON.Space.WORLD && mesh) {
  33531. parentScale.copyFrom(mesh.getWorldMatrix());
  33532. parentScaleInv.copyFrom(parentScale);
  33533. parentScaleInv.invert();
  33534. lmat.multiplyToRef(parentScale, lmat);
  33535. lmat.multiplyToRef(rmat, lmat);
  33536. lmat.multiplyToRef(parentScaleInv, lmat);
  33537. }
  33538. else {
  33539. lmat.multiplyToRef(rmat, lmat);
  33540. }
  33541. }
  33542. lmat.m[12] = lx;
  33543. lmat.m[13] = ly;
  33544. lmat.m[14] = lz;
  33545. this.computeAbsoluteTransforms();
  33546. this.markAsDirty();
  33547. };
  33548. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  33549. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33550. if (space == BABYLON.Space.WORLD) {
  33551. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  33552. scaleMatrix.copyFrom(this._scaleMatrix);
  33553. rotMatInv.copyFrom(this.getAbsoluteTransform());
  33554. if (mesh) {
  33555. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  33556. var meshScale = BABYLON.Tmp.Matrix[3];
  33557. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  33558. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  33559. }
  33560. rotMatInv.invert();
  33561. scaleMatrix.m[0] *= this._scalingDeterminant;
  33562. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  33563. }
  33564. else {
  33565. rotMatInv.copyFrom(this.getLocalMatrix());
  33566. rotMatInv.invert();
  33567. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  33568. scaleMatrix.copyFrom(this._scaleMatrix);
  33569. if (this._parent) {
  33570. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  33571. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  33572. pscaleMatrix.invert();
  33573. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  33574. }
  33575. else {
  33576. scaleMatrix.m[0] *= this._scalingDeterminant;
  33577. }
  33578. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  33579. }
  33580. };
  33581. /**
  33582. * Get the scale of the bone
  33583. * @returns the scale of the bone
  33584. */
  33585. Bone.prototype.getScale = function () {
  33586. return this._scaleVector.clone();
  33587. };
  33588. /**
  33589. * Copy the scale of the bone to a vector3.
  33590. * @param result The vector3 to copy the scale to
  33591. */
  33592. Bone.prototype.getScaleToRef = function (result) {
  33593. result.copyFrom(this._scaleVector);
  33594. };
  33595. /**
  33596. * Get the position of the bone in local or world space.
  33597. * @param space The space that the returned position is in.
  33598. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33599. * @returns The position of the bone
  33600. */
  33601. Bone.prototype.getPosition = function (space, mesh) {
  33602. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33603. var pos = BABYLON.Vector3.Zero();
  33604. this.getPositionToRef(space, mesh, pos);
  33605. return pos;
  33606. };
  33607. /**
  33608. * Copy the position of the bone to a vector3 in local or world space.
  33609. * @param space The space that the returned position is in.
  33610. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33611. * @param result The vector3 to copy the position to.
  33612. */
  33613. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  33614. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33615. if (space == BABYLON.Space.LOCAL) {
  33616. var lm = this.getLocalMatrix();
  33617. result.x = lm.m[12];
  33618. result.y = lm.m[13];
  33619. result.z = lm.m[14];
  33620. }
  33621. else {
  33622. var wm;
  33623. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  33624. if (mesh) {
  33625. wm = mesh.getWorldMatrix();
  33626. }
  33627. this._skeleton.computeAbsoluteTransforms();
  33628. var tmat = BABYLON.Tmp.Matrix[0];
  33629. if (mesh) {
  33630. tmat.copyFrom(this.getAbsoluteTransform());
  33631. tmat.multiplyToRef(wm, tmat);
  33632. }
  33633. else {
  33634. tmat = this.getAbsoluteTransform();
  33635. }
  33636. result.x = tmat.m[12];
  33637. result.y = tmat.m[13];
  33638. result.z = tmat.m[14];
  33639. }
  33640. };
  33641. /**
  33642. * Get the absolute position of the bone (world space).
  33643. * @param mesh The mesh that this bone is attached to.
  33644. * @returns The absolute position of the bone
  33645. */
  33646. Bone.prototype.getAbsolutePosition = function (mesh) {
  33647. var pos = BABYLON.Vector3.Zero();
  33648. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  33649. return pos;
  33650. };
  33651. /**
  33652. * Copy the absolute position of the bone (world space) to the result param.
  33653. * @param mesh The mesh that this bone is attached to.
  33654. * @param result The vector3 to copy the absolute position to.
  33655. */
  33656. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  33657. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  33658. };
  33659. /**
  33660. * Compute the absolute transforms of this bone and its children.
  33661. */
  33662. Bone.prototype.computeAbsoluteTransforms = function () {
  33663. if (this._parent) {
  33664. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  33665. }
  33666. else {
  33667. this._absoluteTransform.copyFrom(this._localMatrix);
  33668. var poseMatrix = this._skeleton.getPoseMatrix();
  33669. if (poseMatrix) {
  33670. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  33671. }
  33672. }
  33673. var children = this.children;
  33674. var len = children.length;
  33675. for (var i = 0; i < len; i++) {
  33676. children[i].computeAbsoluteTransforms();
  33677. }
  33678. };
  33679. Bone.prototype._syncScaleVector = function () {
  33680. var lm = this.getLocalMatrix();
  33681. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  33682. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  33683. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  33684. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  33685. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  33686. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  33687. this._scaleVector.x = xs * Math.sqrt(xsq);
  33688. this._scaleVector.y = ys * Math.sqrt(ysq);
  33689. this._scaleVector.z = zs * Math.sqrt(zsq);
  33690. if (this._parent) {
  33691. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  33692. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  33693. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  33694. }
  33695. 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);
  33696. };
  33697. /**
  33698. * Get the world direction from an axis that is in the local space of the bone.
  33699. * @param localAxis The local direction that is used to compute the world direction.
  33700. * @param mesh The mesh that this bone is attached to.
  33701. * @returns The world direction
  33702. */
  33703. Bone.prototype.getDirection = function (localAxis, mesh) {
  33704. var result = BABYLON.Vector3.Zero();
  33705. this.getDirectionToRef(localAxis, mesh, result);
  33706. return result;
  33707. };
  33708. /**
  33709. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  33710. * @param localAxis The local direction that is used to compute the world direction.
  33711. * @param mesh The mesh that this bone is attached to.
  33712. * @param result The vector3 that the world direction will be copied to.
  33713. */
  33714. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  33715. this._skeleton.computeAbsoluteTransforms();
  33716. var mat = BABYLON.Tmp.Matrix[0];
  33717. mat.copyFrom(this.getAbsoluteTransform());
  33718. if (mesh) {
  33719. mat.multiplyToRef(mesh.getWorldMatrix(), mat);
  33720. }
  33721. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  33722. result.normalize();
  33723. };
  33724. /**
  33725. * Get the euler rotation of the bone in local or world space.
  33726. * @param space The space that the rotation should be in.
  33727. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33728. * @returns The euler rotation
  33729. */
  33730. Bone.prototype.getRotation = function (space, mesh) {
  33731. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33732. var result = BABYLON.Vector3.Zero();
  33733. this.getRotationToRef(space, mesh, result);
  33734. return result;
  33735. };
  33736. /**
  33737. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  33738. * @param space The space that the rotation should be in.
  33739. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33740. * @param result The vector3 that the rotation should be copied to.
  33741. */
  33742. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  33743. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33744. var quat = BABYLON.Tmp.Quaternion[0];
  33745. this.getRotationQuaternionToRef(space, mesh, quat);
  33746. quat.toEulerAnglesToRef(result);
  33747. };
  33748. /**
  33749. * Get the quaternion rotation of the bone in either local or world space.
  33750. * @param space The space that the rotation should be in.
  33751. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33752. * @returns The quaternion rotation
  33753. */
  33754. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  33755. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33756. var result = BABYLON.Quaternion.Identity();
  33757. this.getRotationQuaternionToRef(space, mesh, result);
  33758. return result;
  33759. };
  33760. /**
  33761. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  33762. * @param space The space that the rotation should be in.
  33763. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33764. * @param result The quaternion that the rotation should be copied to.
  33765. */
  33766. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  33767. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33768. if (space == BABYLON.Space.LOCAL) {
  33769. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  33770. }
  33771. else {
  33772. var mat = BABYLON.Tmp.Matrix[0];
  33773. var amat = this.getAbsoluteTransform();
  33774. if (mesh) {
  33775. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  33776. }
  33777. else {
  33778. mat.copyFrom(amat);
  33779. }
  33780. mat.m[0] *= this._scalingDeterminant;
  33781. mat.m[1] *= this._scalingDeterminant;
  33782. mat.m[2] *= this._scalingDeterminant;
  33783. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  33784. }
  33785. };
  33786. /**
  33787. * Get the rotation matrix of the bone in local or world space.
  33788. * @param space The space that the rotation should be in.
  33789. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33790. * @returns The rotation matrix
  33791. */
  33792. Bone.prototype.getRotationMatrix = function (space, mesh) {
  33793. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33794. var result = BABYLON.Matrix.Identity();
  33795. this.getRotationMatrixToRef(space, mesh, result);
  33796. return result;
  33797. };
  33798. /**
  33799. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  33800. * @param space The space that the rotation should be in.
  33801. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33802. * @param result The quaternion that the rotation should be copied to.
  33803. */
  33804. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  33805. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33806. if (space == BABYLON.Space.LOCAL) {
  33807. this.getLocalMatrix().getRotationMatrixToRef(result);
  33808. }
  33809. else {
  33810. var mat = BABYLON.Tmp.Matrix[0];
  33811. var amat = this.getAbsoluteTransform();
  33812. if (mesh) {
  33813. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  33814. }
  33815. else {
  33816. mat.copyFrom(amat);
  33817. }
  33818. mat.m[0] *= this._scalingDeterminant;
  33819. mat.m[1] *= this._scalingDeterminant;
  33820. mat.m[2] *= this._scalingDeterminant;
  33821. mat.getRotationMatrixToRef(result);
  33822. }
  33823. };
  33824. /**
  33825. * Get the world position of a point that is in the local space of the bone.
  33826. * @param position The local position
  33827. * @param mesh The mesh that this bone is attached to.
  33828. * @returns The world position
  33829. */
  33830. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  33831. var result = BABYLON.Vector3.Zero();
  33832. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  33833. return result;
  33834. };
  33835. /**
  33836. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  33837. * @param position The local position
  33838. * @param mesh The mesh that this bone is attached to.
  33839. * @param result The vector3 that the world position should be copied to.
  33840. */
  33841. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  33842. this._skeleton.computeAbsoluteTransforms();
  33843. var tmat = BABYLON.Tmp.Matrix[0];
  33844. if (mesh) {
  33845. tmat.copyFrom(this.getAbsoluteTransform());
  33846. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  33847. }
  33848. else {
  33849. tmat = this.getAbsoluteTransform();
  33850. }
  33851. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  33852. };
  33853. /**
  33854. * Get the local position of a point that is in world space.
  33855. * @param position The world position
  33856. * @param mesh The mesh that this bone is attached to.
  33857. * @returns The local position
  33858. */
  33859. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  33860. var result = BABYLON.Vector3.Zero();
  33861. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  33862. return result;
  33863. };
  33864. /**
  33865. * Get the local position of a point that is in world space and copy it to the result param.
  33866. * @param position The world position
  33867. * @param mesh The mesh that this bone is attached to.
  33868. * @param result The vector3 that the local position should be copied to.
  33869. */
  33870. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  33871. this._skeleton.computeAbsoluteTransforms();
  33872. var tmat = BABYLON.Tmp.Matrix[0];
  33873. tmat.copyFrom(this.getAbsoluteTransform());
  33874. if (mesh) {
  33875. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  33876. }
  33877. tmat.invert();
  33878. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  33879. };
  33880. return Bone;
  33881. }(BABYLON.Node));
  33882. BABYLON.Bone = Bone;
  33883. })(BABYLON || (BABYLON = {}));
  33884. //# sourceMappingURL=babylon.bone.js.map
  33885. var BABYLON;
  33886. (function (BABYLON) {
  33887. var BoneIKController = (function () {
  33888. function BoneIKController(mesh, bone, options) {
  33889. this.targetPosition = BABYLON.Vector3.Zero();
  33890. this.poleTargetPosition = BABYLON.Vector3.Zero();
  33891. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  33892. this.poleAngle = 0;
  33893. this.slerpAmount = 1;
  33894. this._bone1Quat = BABYLON.Quaternion.Identity();
  33895. this._bone1Mat = BABYLON.Matrix.Identity();
  33896. this._bone2Ang = Math.PI;
  33897. this._maxAngle = Math.PI;
  33898. this._tmpVec1 = BABYLON.Vector3.Zero();
  33899. this._tmpVec2 = BABYLON.Vector3.Zero();
  33900. this._tmpVec3 = BABYLON.Vector3.Zero();
  33901. this._tmpVec4 = BABYLON.Vector3.Zero();
  33902. this._tmpVec5 = BABYLON.Vector3.Zero();
  33903. this._tmpMat1 = BABYLON.Matrix.Identity();
  33904. this._tmpMat2 = BABYLON.Matrix.Identity();
  33905. this._tmpQuat1 = BABYLON.Quaternion.Identity();
  33906. this._rightHandedSystem = false;
  33907. this._bendAxis = BABYLON.Vector3.Right();
  33908. this._slerping = false;
  33909. this._adjustRoll = 0;
  33910. this._bone2 = bone;
  33911. this._bone1 = bone.getParent();
  33912. this.mesh = mesh;
  33913. var bonePos = bone.getPosition();
  33914. if (bone.getAbsoluteTransform().determinant() > 0) {
  33915. this._rightHandedSystem = true;
  33916. this._bendAxis.x = 0;
  33917. this._bendAxis.y = 0;
  33918. this._bendAxis.z = -1;
  33919. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  33920. this._adjustRoll = Math.PI * .5;
  33921. this._bendAxis.z = 1;
  33922. }
  33923. }
  33924. if (this._bone1.length) {
  33925. var boneScale1 = this._bone1.getScale();
  33926. var boneScale2 = this._bone2.getScale();
  33927. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  33928. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  33929. }
  33930. else if (this._bone1.children[0]) {
  33931. mesh.computeWorldMatrix(true);
  33932. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  33933. var pos2 = this._bone2.getAbsolutePosition(mesh);
  33934. var pos3 = this._bone1.getAbsolutePosition(mesh);
  33935. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  33936. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  33937. }
  33938. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  33939. this.maxAngle = Math.PI;
  33940. if (options) {
  33941. if (options.targetMesh) {
  33942. this.targetMesh = options.targetMesh;
  33943. this.targetMesh.computeWorldMatrix(true);
  33944. }
  33945. if (options.poleTargetMesh) {
  33946. this.poleTargetMesh = options.poleTargetMesh;
  33947. this.poleTargetMesh.computeWorldMatrix(true);
  33948. }
  33949. else if (options.poleTargetBone) {
  33950. this.poleTargetBone = options.poleTargetBone;
  33951. }
  33952. else if (this._bone1.getParent()) {
  33953. this.poleTargetBone = this._bone1.getParent();
  33954. }
  33955. if (options.poleTargetLocalOffset) {
  33956. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  33957. }
  33958. if (options.poleAngle) {
  33959. this.poleAngle = options.poleAngle;
  33960. }
  33961. if (options.bendAxis) {
  33962. this._bendAxis.copyFrom(options.bendAxis);
  33963. }
  33964. if (options.maxAngle) {
  33965. this.maxAngle = options.maxAngle;
  33966. }
  33967. if (options.slerpAmount) {
  33968. this.slerpAmount = options.slerpAmount;
  33969. }
  33970. }
  33971. }
  33972. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  33973. get: function () {
  33974. return this._maxAngle;
  33975. },
  33976. set: function (value) {
  33977. this._setMaxAngle(value);
  33978. },
  33979. enumerable: true,
  33980. configurable: true
  33981. });
  33982. BoneIKController.prototype._setMaxAngle = function (ang) {
  33983. if (ang < 0) {
  33984. ang = 0;
  33985. }
  33986. if (ang > Math.PI || ang == undefined) {
  33987. ang = Math.PI;
  33988. }
  33989. this._maxAngle = ang;
  33990. var a = this._bone1Length;
  33991. var b = this._bone2Length;
  33992. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  33993. };
  33994. BoneIKController.prototype.update = function () {
  33995. var bone1 = this._bone1;
  33996. var target = this.targetPosition;
  33997. var poleTarget = this.poleTargetPosition;
  33998. var mat1 = this._tmpMat1;
  33999. var mat2 = this._tmpMat2;
  34000. if (this.targetMesh) {
  34001. target.copyFrom(this.targetMesh.getAbsolutePosition());
  34002. }
  34003. if (this.poleTargetBone) {
  34004. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  34005. }
  34006. else if (this.poleTargetMesh) {
  34007. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  34008. }
  34009. var bonePos = this._tmpVec1;
  34010. var zaxis = this._tmpVec2;
  34011. var xaxis = this._tmpVec3;
  34012. var yaxis = this._tmpVec4;
  34013. var upAxis = this._tmpVec5;
  34014. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  34015. poleTarget.subtractToRef(bonePos, upAxis);
  34016. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  34017. upAxis.y = 1;
  34018. }
  34019. else {
  34020. upAxis.normalize();
  34021. }
  34022. target.subtractToRef(bonePos, yaxis);
  34023. yaxis.normalize();
  34024. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  34025. zaxis.normalize();
  34026. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  34027. xaxis.normalize();
  34028. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  34029. var a = this._bone1Length;
  34030. var b = this._bone2Length;
  34031. var c = BABYLON.Vector3.Distance(bonePos, target);
  34032. if (this._maxReach > 0) {
  34033. c = Math.min(this._maxReach, c);
  34034. }
  34035. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  34036. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  34037. if (acosa > 1) {
  34038. acosa = 1;
  34039. }
  34040. if (acosb > 1) {
  34041. acosb = 1;
  34042. }
  34043. if (acosa < -1) {
  34044. acosa = -1;
  34045. }
  34046. if (acosb < -1) {
  34047. acosb = -1;
  34048. }
  34049. var angA = Math.acos(acosa);
  34050. var angB = Math.acos(acosb);
  34051. var angC = -angA - angB;
  34052. if (this._rightHandedSystem) {
  34053. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  34054. mat2.multiplyToRef(mat1, mat1);
  34055. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  34056. mat2.multiplyToRef(mat1, mat1);
  34057. }
  34058. else {
  34059. this._tmpVec1.copyFrom(this._bendAxis);
  34060. this._tmpVec1.x *= -1;
  34061. BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
  34062. mat2.multiplyToRef(mat1, mat1);
  34063. }
  34064. if (this.poleAngle) {
  34065. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  34066. mat1.multiplyToRef(mat2, mat1);
  34067. }
  34068. if (this.slerpAmount < 1) {
  34069. if (!this._slerping) {
  34070. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  34071. }
  34072. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, this._tmpQuat1);
  34073. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, this._tmpQuat1, this.slerpAmount, this._bone1Quat);
  34074. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  34075. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  34076. this._slerping = true;
  34077. }
  34078. else {
  34079. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  34080. this._bone1Mat.copyFrom(mat1);
  34081. this._slerping = false;
  34082. }
  34083. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  34084. this._bone2Ang = angC;
  34085. };
  34086. return BoneIKController;
  34087. }());
  34088. BABYLON.BoneIKController = BoneIKController;
  34089. })(BABYLON || (BABYLON = {}));
  34090. //# sourceMappingURL=babylon.boneIKController.js.map
  34091. var BABYLON;
  34092. (function (BABYLON) {
  34093. var BoneLookController = (function () {
  34094. function BoneLookController(mesh, bone, target, options) {
  34095. this.upAxis = BABYLON.Vector3.Up();
  34096. this.adjustYaw = 0;
  34097. this.adjustPitch = 0;
  34098. this.adjustRoll = 0;
  34099. this._tmpVec1 = BABYLON.Vector3.Zero();
  34100. this._tmpVec2 = BABYLON.Vector3.Zero();
  34101. this._tmpVec3 = BABYLON.Vector3.Zero();
  34102. this._tmpVec4 = BABYLON.Vector3.Zero();
  34103. this._tmpMat1 = BABYLON.Matrix.Identity();
  34104. this._tmpMat2 = BABYLON.Matrix.Identity();
  34105. this.mesh = mesh;
  34106. this.bone = bone;
  34107. this.target = target;
  34108. if (options) {
  34109. if (options.adjustYaw) {
  34110. this.adjustYaw = options.adjustYaw;
  34111. }
  34112. if (options.adjustPitch) {
  34113. this.adjustPitch = options.adjustPitch;
  34114. }
  34115. if (options.adjustRoll) {
  34116. this.adjustRoll = options.adjustRoll;
  34117. }
  34118. }
  34119. }
  34120. BoneLookController.prototype.update = function () {
  34121. var bone = this.bone;
  34122. var target = this.target;
  34123. var bonePos = this._tmpVec1;
  34124. var zaxis = this._tmpVec2;
  34125. var xaxis = this._tmpVec3;
  34126. var yaxis = this._tmpVec4;
  34127. var mat1 = this._tmpMat1;
  34128. var mat2 = this._tmpMat2;
  34129. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  34130. target.subtractToRef(bonePos, zaxis);
  34131. zaxis.normalize();
  34132. BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
  34133. xaxis.normalize();
  34134. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  34135. yaxis.normalize();
  34136. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  34137. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  34138. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
  34139. mat2.multiplyToRef(mat1, mat1);
  34140. }
  34141. this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  34142. };
  34143. return BoneLookController;
  34144. }());
  34145. BABYLON.BoneLookController = BoneLookController;
  34146. })(BABYLON || (BABYLON = {}));
  34147. //# sourceMappingURL=babylon.boneLookController.js.map
  34148. var BABYLON;
  34149. (function (BABYLON) {
  34150. var Skeleton = (function () {
  34151. function Skeleton(name, id, scene) {
  34152. this.name = name;
  34153. this.id = id;
  34154. this.bones = new Array();
  34155. this.needInitialSkinMatrix = false;
  34156. this._isDirty = true;
  34157. this._meshesWithPoseMatrix = new Array();
  34158. this._identity = BABYLON.Matrix.Identity();
  34159. this._ranges = {};
  34160. this._lastAbsoluteTransformsUpdateId = -1;
  34161. // Events
  34162. /**
  34163. * An event triggered before computing the skeleton's matrices
  34164. * @type {BABYLON.Observable}
  34165. */
  34166. this.onBeforeComputeObservable = new BABYLON.Observable();
  34167. this.bones = [];
  34168. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34169. scene.skeletons.push(this);
  34170. //make sure it will recalculate the matrix next time prepare is called.
  34171. this._isDirty = true;
  34172. }
  34173. // Members
  34174. Skeleton.prototype.getTransformMatrices = function (mesh) {
  34175. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  34176. return mesh._bonesTransformMatrices;
  34177. }
  34178. if (!this._transformMatrices) {
  34179. this.prepare();
  34180. }
  34181. return this._transformMatrices;
  34182. };
  34183. Skeleton.prototype.getScene = function () {
  34184. return this._scene;
  34185. };
  34186. // Methods
  34187. /**
  34188. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  34189. */
  34190. Skeleton.prototype.toString = function (fullDetails) {
  34191. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  34192. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  34193. if (fullDetails) {
  34194. ret += ", Ranges: {";
  34195. var first = true;
  34196. for (var name_1 in this._ranges) {
  34197. if (first) {
  34198. ret += ", ";
  34199. first = false;
  34200. }
  34201. ret += name_1;
  34202. }
  34203. ret += "}";
  34204. }
  34205. return ret;
  34206. };
  34207. /**
  34208. * Get bone's index searching by name
  34209. * @param {string} name is bone's name to search for
  34210. * @return {number} Indice of the bone. Returns -1 if not found
  34211. */
  34212. Skeleton.prototype.getBoneIndexByName = function (name) {
  34213. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  34214. if (this.bones[boneIndex].name === name) {
  34215. return boneIndex;
  34216. }
  34217. }
  34218. return -1;
  34219. };
  34220. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  34221. // check name not already in use
  34222. if (!this._ranges[name]) {
  34223. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  34224. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  34225. if (this.bones[i].animations[0]) {
  34226. this.bones[i].animations[0].createRange(name, from, to);
  34227. }
  34228. }
  34229. }
  34230. };
  34231. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  34232. if (deleteFrames === void 0) { deleteFrames = true; }
  34233. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  34234. if (this.bones[i].animations[0]) {
  34235. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  34236. }
  34237. }
  34238. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  34239. };
  34240. Skeleton.prototype.getAnimationRange = function (name) {
  34241. return this._ranges[name];
  34242. };
  34243. /**
  34244. * Returns as an Array, all AnimationRanges defined on this skeleton
  34245. */
  34246. Skeleton.prototype.getAnimationRanges = function () {
  34247. var animationRanges = [];
  34248. var name;
  34249. var i = 0;
  34250. for (name in this._ranges) {
  34251. animationRanges[i] = this._ranges[name];
  34252. i++;
  34253. }
  34254. return animationRanges;
  34255. };
  34256. /**
  34257. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  34258. */
  34259. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  34260. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  34261. if (this._ranges[name] || !source.getAnimationRange(name)) {
  34262. return false;
  34263. }
  34264. var ret = true;
  34265. var frameOffset = this._getHighestAnimationFrame() + 1;
  34266. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  34267. var boneDict = {};
  34268. var sourceBones = source.bones;
  34269. var nBones;
  34270. var i;
  34271. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  34272. boneDict[sourceBones[i].name] = sourceBones[i];
  34273. }
  34274. if (this.bones.length !== sourceBones.length) {
  34275. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  34276. ret = false;
  34277. }
  34278. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  34279. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  34280. var boneName = this.bones[i].name;
  34281. var sourceBone = boneDict[boneName];
  34282. if (sourceBone) {
  34283. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  34284. }
  34285. else {
  34286. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  34287. ret = false;
  34288. }
  34289. }
  34290. // do not call createAnimationRange(), since it also is done to bones, which was already done
  34291. var range = source.getAnimationRange(name);
  34292. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  34293. return ret;
  34294. };
  34295. Skeleton.prototype.returnToRest = function () {
  34296. for (var index = 0; index < this.bones.length; index++) {
  34297. this.bones[index].returnToRest();
  34298. }
  34299. };
  34300. Skeleton.prototype._getHighestAnimationFrame = function () {
  34301. var ret = 0;
  34302. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  34303. if (this.bones[i].animations[0]) {
  34304. var highest = this.bones[i].animations[0].getHighestFrame();
  34305. if (ret < highest) {
  34306. ret = highest;
  34307. }
  34308. }
  34309. }
  34310. return ret;
  34311. };
  34312. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  34313. var range = this.getAnimationRange(name);
  34314. if (!range) {
  34315. return null;
  34316. }
  34317. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  34318. };
  34319. Skeleton.prototype._markAsDirty = function () {
  34320. this._isDirty = true;
  34321. };
  34322. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  34323. this._meshesWithPoseMatrix.push(mesh);
  34324. };
  34325. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  34326. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  34327. if (index > -1) {
  34328. this._meshesWithPoseMatrix.splice(index, 1);
  34329. }
  34330. };
  34331. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  34332. this.onBeforeComputeObservable.notifyObservers(this);
  34333. for (var index = 0; index < this.bones.length; index++) {
  34334. var bone = this.bones[index];
  34335. var parentBone = bone.getParent();
  34336. if (parentBone) {
  34337. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  34338. }
  34339. else {
  34340. if (initialSkinMatrix) {
  34341. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  34342. }
  34343. else {
  34344. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  34345. }
  34346. }
  34347. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  34348. }
  34349. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  34350. };
  34351. Skeleton.prototype.prepare = function () {
  34352. if (!this._isDirty) {
  34353. return;
  34354. }
  34355. if (this.needInitialSkinMatrix) {
  34356. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  34357. var mesh = this._meshesWithPoseMatrix[index];
  34358. var poseMatrix = mesh.getPoseMatrix();
  34359. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  34360. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  34361. }
  34362. if (this._synchronizedWithMesh !== mesh) {
  34363. this._synchronizedWithMesh = mesh;
  34364. // Prepare bones
  34365. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  34366. var bone = this.bones[boneIndex];
  34367. if (!bone.getParent()) {
  34368. var matrix = bone.getBaseMatrix();
  34369. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  34370. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  34371. }
  34372. }
  34373. }
  34374. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  34375. }
  34376. }
  34377. else {
  34378. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  34379. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  34380. }
  34381. this._computeTransformMatrices(this._transformMatrices, null);
  34382. }
  34383. this._isDirty = false;
  34384. this._scene._activeBones.addCount(this.bones.length, false);
  34385. };
  34386. Skeleton.prototype.getAnimatables = function () {
  34387. if (!this._animatables || this._animatables.length !== this.bones.length) {
  34388. this._animatables = [];
  34389. for (var index = 0; index < this.bones.length; index++) {
  34390. this._animatables.push(this.bones[index]);
  34391. }
  34392. }
  34393. return this._animatables;
  34394. };
  34395. Skeleton.prototype.clone = function (name, id) {
  34396. var result = new Skeleton(name, id || name, this._scene);
  34397. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  34398. for (var index = 0; index < this.bones.length; index++) {
  34399. var source = this.bones[index];
  34400. var parentBone = null;
  34401. if (source.getParent()) {
  34402. var parentIndex = this.bones.indexOf(source.getParent());
  34403. parentBone = result.bones[parentIndex];
  34404. }
  34405. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  34406. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  34407. }
  34408. if (this._ranges) {
  34409. result._ranges = {};
  34410. for (var rangeName in this._ranges) {
  34411. result._ranges[rangeName] = this._ranges[rangeName].clone();
  34412. }
  34413. }
  34414. this._isDirty = true;
  34415. return result;
  34416. };
  34417. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  34418. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  34419. this.bones.forEach(function (bone) {
  34420. bone.animations.forEach(function (animation) {
  34421. animation.enableBlending = true;
  34422. animation.blendingSpeed = blendingSpeed;
  34423. });
  34424. });
  34425. };
  34426. Skeleton.prototype.dispose = function () {
  34427. this._meshesWithPoseMatrix = [];
  34428. // Animations
  34429. this.getScene().stopAnimation(this);
  34430. // Remove from scene
  34431. this.getScene().removeSkeleton(this);
  34432. };
  34433. Skeleton.prototype.serialize = function () {
  34434. var serializationObject = {};
  34435. serializationObject.name = this.name;
  34436. serializationObject.id = this.id;
  34437. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  34438. serializationObject.bones = [];
  34439. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  34440. for (var index = 0; index < this.bones.length; index++) {
  34441. var bone = this.bones[index];
  34442. var serializedBone = {
  34443. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  34444. name: bone.name,
  34445. matrix: bone.getLocalMatrix().toArray(),
  34446. rest: bone.getRestPose().toArray()
  34447. };
  34448. serializationObject.bones.push(serializedBone);
  34449. if (bone.length) {
  34450. serializedBone.length = bone.length;
  34451. }
  34452. if (bone.animations && bone.animations.length > 0) {
  34453. serializedBone.animation = bone.animations[0].serialize();
  34454. }
  34455. serializationObject.ranges = [];
  34456. for (var name in this._ranges) {
  34457. var range = {};
  34458. range.name = name;
  34459. range.from = this._ranges[name].from;
  34460. range.to = this._ranges[name].to;
  34461. serializationObject.ranges.push(range);
  34462. }
  34463. }
  34464. return serializationObject;
  34465. };
  34466. Skeleton.Parse = function (parsedSkeleton, scene) {
  34467. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  34468. if (parsedSkeleton.dimensionsAtRest) {
  34469. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  34470. }
  34471. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  34472. var index;
  34473. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  34474. var parsedBone = parsedSkeleton.bones[index];
  34475. var parentBone = null;
  34476. if (parsedBone.parentBoneIndex > -1) {
  34477. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  34478. }
  34479. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  34480. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  34481. if (parsedBone.length) {
  34482. bone.length = parsedBone.length;
  34483. }
  34484. if (parsedBone.animation) {
  34485. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  34486. }
  34487. }
  34488. // placed after bones, so createAnimationRange can cascade down
  34489. if (parsedSkeleton.ranges) {
  34490. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  34491. var data = parsedSkeleton.ranges[index];
  34492. skeleton.createAnimationRange(data.name, data.from, data.to);
  34493. }
  34494. }
  34495. return skeleton;
  34496. };
  34497. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  34498. if (forceUpdate === void 0) { forceUpdate = false; }
  34499. var renderId = this._scene.getRenderId();
  34500. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  34501. this.bones[0].computeAbsoluteTransforms();
  34502. this._lastAbsoluteTransformsUpdateId = renderId;
  34503. }
  34504. };
  34505. Skeleton.prototype.getPoseMatrix = function () {
  34506. var poseMatrix;
  34507. if (this._meshesWithPoseMatrix.length > 0) {
  34508. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  34509. }
  34510. return poseMatrix;
  34511. };
  34512. return Skeleton;
  34513. }());
  34514. BABYLON.Skeleton = Skeleton;
  34515. })(BABYLON || (BABYLON = {}));
  34516. //# sourceMappingURL=babylon.skeleton.js.map
  34517. var BABYLON;
  34518. (function (BABYLON) {
  34519. var PostProcess = (function () {
  34520. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  34521. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  34522. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  34523. this.name = name;
  34524. this.width = -1;
  34525. this.height = -1;
  34526. /*
  34527. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  34528. Can only be used on a single postprocess or on the last one of a chain.
  34529. */
  34530. this.enablePixelPerfectMode = false;
  34531. this._reusable = false;
  34532. this._textures = new BABYLON.SmartArray(2);
  34533. this._currentRenderTextureInd = 0;
  34534. this._scaleRatio = new BABYLON.Vector2(1, 1);
  34535. // Events
  34536. /**
  34537. * An event triggered when the postprocess is activated.
  34538. * @type {BABYLON.Observable}
  34539. */
  34540. this.onActivateObservable = new BABYLON.Observable();
  34541. /**
  34542. * An event triggered when the postprocess changes its size.
  34543. * @type {BABYLON.Observable}
  34544. */
  34545. this.onSizeChangedObservable = new BABYLON.Observable();
  34546. /**
  34547. * An event triggered when the postprocess applies its effect.
  34548. * @type {BABYLON.Observable}
  34549. */
  34550. this.onApplyObservable = new BABYLON.Observable();
  34551. /**
  34552. * An event triggered before rendering the postprocess
  34553. * @type {BABYLON.Observable}
  34554. */
  34555. this.onBeforeRenderObservable = new BABYLON.Observable();
  34556. /**
  34557. * An event triggered after rendering the postprocess
  34558. * @type {BABYLON.Observable}
  34559. */
  34560. this.onAfterRenderObservable = new BABYLON.Observable();
  34561. if (camera != null) {
  34562. this._camera = camera;
  34563. this._scene = camera.getScene();
  34564. camera.attachPostProcess(this);
  34565. this._engine = this._scene.getEngine();
  34566. }
  34567. else {
  34568. this._engine = engine;
  34569. }
  34570. this._options = options;
  34571. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  34572. this._reusable = reusable || false;
  34573. this._textureType = textureType;
  34574. this._samplers = samplers || [];
  34575. this._samplers.push("textureSampler");
  34576. this._fragmentUrl = fragmentUrl;
  34577. this._parameters = parameters || [];
  34578. this._parameters.push("scale");
  34579. this.updateEffect(defines);
  34580. }
  34581. Object.defineProperty(PostProcess.prototype, "onActivate", {
  34582. set: function (callback) {
  34583. if (this._onActivateObserver) {
  34584. this.onActivateObservable.remove(this._onActivateObserver);
  34585. }
  34586. this._onActivateObserver = this.onActivateObservable.add(callback);
  34587. },
  34588. enumerable: true,
  34589. configurable: true
  34590. });
  34591. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  34592. set: function (callback) {
  34593. if (this._onSizeChangedObserver) {
  34594. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  34595. }
  34596. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  34597. },
  34598. enumerable: true,
  34599. configurable: true
  34600. });
  34601. Object.defineProperty(PostProcess.prototype, "onApply", {
  34602. set: function (callback) {
  34603. if (this._onApplyObserver) {
  34604. this.onApplyObservable.remove(this._onApplyObserver);
  34605. }
  34606. this._onApplyObserver = this.onApplyObservable.add(callback);
  34607. },
  34608. enumerable: true,
  34609. configurable: true
  34610. });
  34611. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  34612. set: function (callback) {
  34613. if (this._onBeforeRenderObserver) {
  34614. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  34615. }
  34616. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  34617. },
  34618. enumerable: true,
  34619. configurable: true
  34620. });
  34621. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  34622. set: function (callback) {
  34623. if (this._onAfterRenderObserver) {
  34624. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  34625. }
  34626. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  34627. },
  34628. enumerable: true,
  34629. configurable: true
  34630. });
  34631. PostProcess.prototype.updateEffect = function (defines) {
  34632. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  34633. };
  34634. PostProcess.prototype.isReusable = function () {
  34635. return this._reusable;
  34636. };
  34637. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  34638. PostProcess.prototype.markTextureDirty = function () {
  34639. this.width = -1;
  34640. };
  34641. PostProcess.prototype.activate = function (camera, sourceTexture) {
  34642. camera = camera || this._camera;
  34643. var scene = camera.getScene();
  34644. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  34645. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  34646. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  34647. var desiredWidth = this._options.width || requiredWidth;
  34648. var desiredHeight = this._options.height || requiredHeight;
  34649. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  34650. if (!this._options.width) {
  34651. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  34652. }
  34653. if (!this._options.height) {
  34654. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  34655. }
  34656. }
  34657. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  34658. if (this._textures.length > 0) {
  34659. for (var i = 0; i < this._textures.length; i++) {
  34660. this._engine._releaseTexture(this._textures.data[i]);
  34661. }
  34662. this._textures.reset();
  34663. }
  34664. this.width = desiredWidth;
  34665. this.height = desiredHeight;
  34666. var textureSize = { width: this.width, height: this.height };
  34667. var textureOptions = {
  34668. generateMipMaps: false,
  34669. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  34670. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  34671. samplingMode: this.renderTargetSamplingMode,
  34672. type: this._textureType
  34673. };
  34674. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  34675. if (this._reusable) {
  34676. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  34677. }
  34678. this.onSizeChangedObservable.notifyObservers(this);
  34679. }
  34680. if (this.enablePixelPerfectMode) {
  34681. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  34682. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  34683. }
  34684. else {
  34685. this._scaleRatio.copyFromFloats(1, 1);
  34686. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  34687. }
  34688. this.onActivateObservable.notifyObservers(camera);
  34689. // Clear
  34690. if (this.clearColor) {
  34691. this._engine.clear(this.clearColor, true, true, true);
  34692. }
  34693. else {
  34694. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  34695. }
  34696. if (this._reusable) {
  34697. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  34698. }
  34699. };
  34700. Object.defineProperty(PostProcess.prototype, "isSupported", {
  34701. get: function () {
  34702. return this._effect.isSupported;
  34703. },
  34704. enumerable: true,
  34705. configurable: true
  34706. });
  34707. PostProcess.prototype.apply = function () {
  34708. // Check
  34709. if (!this._effect.isReady())
  34710. return null;
  34711. // States
  34712. this._engine.enableEffect(this._effect);
  34713. this._engine.setState(false);
  34714. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34715. this._engine.setDepthBuffer(false);
  34716. this._engine.setDepthWrite(false);
  34717. // Texture
  34718. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  34719. // Parameters
  34720. this._effect.setVector2("scale", this._scaleRatio);
  34721. this.onApplyObservable.notifyObservers(this._effect);
  34722. return this._effect;
  34723. };
  34724. PostProcess.prototype.dispose = function (camera) {
  34725. camera = camera || this._camera;
  34726. if (this._textures.length > 0) {
  34727. for (var i = 0; i < this._textures.length; i++) {
  34728. this._engine._releaseTexture(this._textures.data[i]);
  34729. }
  34730. this._textures.reset();
  34731. }
  34732. if (!camera) {
  34733. return;
  34734. }
  34735. camera.detachPostProcess(this);
  34736. var index = camera._postProcesses.indexOf(this);
  34737. if (index === 0 && camera._postProcesses.length > 0) {
  34738. this._camera._postProcesses[0].markTextureDirty();
  34739. }
  34740. this.onActivateObservable.clear();
  34741. this.onAfterRenderObservable.clear();
  34742. this.onApplyObservable.clear();
  34743. this.onBeforeRenderObservable.clear();
  34744. this.onSizeChangedObservable.clear();
  34745. };
  34746. return PostProcess;
  34747. }());
  34748. BABYLON.PostProcess = PostProcess;
  34749. })(BABYLON || (BABYLON = {}));
  34750. //# sourceMappingURL=babylon.postProcess.js.map
  34751. var BABYLON;
  34752. (function (BABYLON) {
  34753. var PostProcessManager = (function () {
  34754. function PostProcessManager(scene) {
  34755. this._vertexBuffers = {};
  34756. this._scene = scene;
  34757. }
  34758. PostProcessManager.prototype._prepareBuffers = function () {
  34759. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  34760. return;
  34761. }
  34762. // VBO
  34763. var vertices = [];
  34764. vertices.push(1, 1);
  34765. vertices.push(-1, 1);
  34766. vertices.push(-1, -1);
  34767. vertices.push(1, -1);
  34768. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  34769. // Indices
  34770. var indices = [];
  34771. indices.push(0);
  34772. indices.push(1);
  34773. indices.push(2);
  34774. indices.push(0);
  34775. indices.push(2);
  34776. indices.push(3);
  34777. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  34778. };
  34779. // Methods
  34780. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  34781. var postProcesses = this._scene.activeCamera._postProcesses;
  34782. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34783. return false;
  34784. }
  34785. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  34786. return true;
  34787. };
  34788. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  34789. var engine = this._scene.getEngine();
  34790. for (var index = 0; index < postProcesses.length; index++) {
  34791. if (index < postProcesses.length - 1) {
  34792. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34793. }
  34794. else {
  34795. if (targetTexture) {
  34796. engine.bindFramebuffer(targetTexture);
  34797. }
  34798. else {
  34799. engine.restoreDefaultFramebuffer();
  34800. }
  34801. }
  34802. var pp = postProcesses[index];
  34803. var effect = pp.apply();
  34804. if (effect) {
  34805. pp.onBeforeRenderObservable.notifyObservers(effect);
  34806. // VBOs
  34807. this._prepareBuffers();
  34808. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34809. // Draw order
  34810. engine.draw(true, 0, 6);
  34811. pp.onAfterRenderObservable.notifyObservers(effect);
  34812. }
  34813. }
  34814. // Restore depth buffer
  34815. engine.setDepthBuffer(true);
  34816. engine.setDepthWrite(true);
  34817. };
  34818. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  34819. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  34820. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34821. return;
  34822. }
  34823. var engine = this._scene.getEngine();
  34824. for (var index = 0, len = postProcesses.length; index < len; index++) {
  34825. if (index < len - 1) {
  34826. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34827. }
  34828. else {
  34829. if (targetTexture) {
  34830. engine.bindFramebuffer(targetTexture, faceIndex);
  34831. }
  34832. else {
  34833. engine.restoreDefaultFramebuffer();
  34834. }
  34835. }
  34836. if (doNotPresent) {
  34837. break;
  34838. }
  34839. var pp = postProcesses[index];
  34840. var effect = pp.apply();
  34841. if (effect) {
  34842. pp.onBeforeRenderObservable.notifyObservers(effect);
  34843. // VBOs
  34844. this._prepareBuffers();
  34845. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34846. // Draw order
  34847. engine.draw(true, 0, 6);
  34848. pp.onAfterRenderObservable.notifyObservers(effect);
  34849. }
  34850. }
  34851. // Restore depth buffer
  34852. engine.setDepthBuffer(true);
  34853. engine.setDepthWrite(true);
  34854. };
  34855. PostProcessManager.prototype.dispose = function () {
  34856. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34857. if (buffer) {
  34858. buffer.dispose();
  34859. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34860. }
  34861. if (this._indexBuffer) {
  34862. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34863. this._indexBuffer = null;
  34864. }
  34865. };
  34866. return PostProcessManager;
  34867. }());
  34868. BABYLON.PostProcessManager = PostProcessManager;
  34869. })(BABYLON || (BABYLON = {}));
  34870. //# sourceMappingURL=babylon.postProcessManager.js.map
  34871. var BABYLON;
  34872. (function (BABYLON) {
  34873. var PassPostProcess = (function (_super) {
  34874. __extends(PassPostProcess, _super);
  34875. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  34876. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable) || this;
  34877. }
  34878. return PassPostProcess;
  34879. }(BABYLON.PostProcess));
  34880. BABYLON.PassPostProcess = PassPostProcess;
  34881. })(BABYLON || (BABYLON = {}));
  34882. //# sourceMappingURL=babylon.passPostProcess.js.map
  34883. var BABYLON;
  34884. (function (BABYLON) {
  34885. /**
  34886. * This is a holder class for the physics joint created by the physics plugin.
  34887. * It holds a set of functions to control the underlying joint.
  34888. */
  34889. var PhysicsJoint = (function () {
  34890. function PhysicsJoint(type, jointData) {
  34891. this.type = type;
  34892. this.jointData = jointData;
  34893. jointData.nativeParams = jointData.nativeParams || {};
  34894. }
  34895. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  34896. get: function () {
  34897. return this._physicsJoint;
  34898. },
  34899. set: function (newJoint) {
  34900. if (this._physicsJoint) {
  34901. }
  34902. this._physicsJoint = newJoint;
  34903. },
  34904. enumerable: true,
  34905. configurable: true
  34906. });
  34907. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  34908. set: function (physicsPlugin) {
  34909. this._physicsPlugin = physicsPlugin;
  34910. },
  34911. enumerable: true,
  34912. configurable: true
  34913. });
  34914. /**
  34915. * Execute a function that is physics-plugin specific.
  34916. * @param {Function} func the function that will be executed.
  34917. * It accepts two parameters: the physics world and the physics joint.
  34918. */
  34919. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  34920. func(this._physicsPlugin.world, this._physicsJoint);
  34921. };
  34922. return PhysicsJoint;
  34923. }());
  34924. //TODO check if the native joints are the same
  34925. //Joint Types
  34926. PhysicsJoint.DistanceJoint = 0;
  34927. PhysicsJoint.HingeJoint = 1;
  34928. PhysicsJoint.BallAndSocketJoint = 2;
  34929. PhysicsJoint.WheelJoint = 3;
  34930. PhysicsJoint.SliderJoint = 4;
  34931. //OIMO
  34932. PhysicsJoint.PrismaticJoint = 5;
  34933. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  34934. PhysicsJoint.UniversalJoint = 6;
  34935. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  34936. //Cannon
  34937. //Similar to a Ball-Joint. Different in params
  34938. PhysicsJoint.PointToPointJoint = 8;
  34939. //Cannon only at the moment
  34940. PhysicsJoint.SpringJoint = 9;
  34941. PhysicsJoint.LockJoint = 10;
  34942. BABYLON.PhysicsJoint = PhysicsJoint;
  34943. /**
  34944. * A class representing a physics distance joint.
  34945. */
  34946. var DistanceJoint = (function (_super) {
  34947. __extends(DistanceJoint, _super);
  34948. function DistanceJoint(jointData) {
  34949. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  34950. }
  34951. /**
  34952. * Update the predefined distance.
  34953. */
  34954. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  34955. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  34956. };
  34957. return DistanceJoint;
  34958. }(PhysicsJoint));
  34959. BABYLON.DistanceJoint = DistanceJoint;
  34960. var MotorEnabledJoint = (function (_super) {
  34961. __extends(MotorEnabledJoint, _super);
  34962. function MotorEnabledJoint(type, jointData) {
  34963. return _super.call(this, type, jointData) || this;
  34964. }
  34965. /**
  34966. * Set the motor values.
  34967. * Attention, this function is plugin specific. Engines won't react 100% the same.
  34968. * @param {number} force the force to apply
  34969. * @param {number} maxForce max force for this motor.
  34970. */
  34971. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  34972. this._physicsPlugin.setMotor(this, force, maxForce);
  34973. };
  34974. /**
  34975. * Set the motor's limits.
  34976. * Attention, this function is plugin specific. Engines won't react 100% the same.
  34977. */
  34978. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  34979. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  34980. };
  34981. return MotorEnabledJoint;
  34982. }(PhysicsJoint));
  34983. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  34984. /**
  34985. * This class represents a single hinge physics joint
  34986. */
  34987. var HingeJoint = (function (_super) {
  34988. __extends(HingeJoint, _super);
  34989. function HingeJoint(jointData) {
  34990. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  34991. }
  34992. /**
  34993. * Set the motor values.
  34994. * Attention, this function is plugin specific. Engines won't react 100% the same.
  34995. * @param {number} force the force to apply
  34996. * @param {number} maxForce max force for this motor.
  34997. */
  34998. HingeJoint.prototype.setMotor = function (force, maxForce) {
  34999. this._physicsPlugin.setMotor(this, force, maxForce);
  35000. };
  35001. /**
  35002. * Set the motor's limits.
  35003. * Attention, this function is plugin specific. Engines won't react 100% the same.
  35004. */
  35005. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  35006. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  35007. };
  35008. return HingeJoint;
  35009. }(MotorEnabledJoint));
  35010. BABYLON.HingeJoint = HingeJoint;
  35011. /**
  35012. * This class represents a dual hinge physics joint (same as wheel joint)
  35013. */
  35014. var Hinge2Joint = (function (_super) {
  35015. __extends(Hinge2Joint, _super);
  35016. function Hinge2Joint(jointData) {
  35017. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  35018. }
  35019. /**
  35020. * Set the motor values.
  35021. * Attention, this function is plugin specific. Engines won't react 100% the same.
  35022. * @param {number} force the force to apply
  35023. * @param {number} maxForce max force for this motor.
  35024. * @param {motorIndex} the motor's index, 0 or 1.
  35025. */
  35026. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  35027. if (motorIndex === void 0) { motorIndex = 0; }
  35028. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  35029. };
  35030. /**
  35031. * Set the motor limits.
  35032. * Attention, this function is plugin specific. Engines won't react 100% the same.
  35033. * @param {number} upperLimit the upper limit
  35034. * @param {number} lowerLimit lower limit
  35035. * @param {motorIndex} the motor's index, 0 or 1.
  35036. */
  35037. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  35038. if (motorIndex === void 0) { motorIndex = 0; }
  35039. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  35040. };
  35041. return Hinge2Joint;
  35042. }(MotorEnabledJoint));
  35043. BABYLON.Hinge2Joint = Hinge2Joint;
  35044. })(BABYLON || (BABYLON = {}));
  35045. //# sourceMappingURL=babylon.physicsJoint.js.map
  35046. var BABYLON;
  35047. (function (BABYLON) {
  35048. var PhysicsImpostor = (function () {
  35049. function PhysicsImpostor(object, type, _options, _scene) {
  35050. if (_options === void 0) { _options = { mass: 0 }; }
  35051. var _this = this;
  35052. this.object = object;
  35053. this.type = type;
  35054. this._options = _options;
  35055. this._scene = _scene;
  35056. this._bodyUpdateRequired = false;
  35057. this._onBeforePhysicsStepCallbacks = new Array();
  35058. this._onAfterPhysicsStepCallbacks = new Array();
  35059. this._onPhysicsCollideCallbacks = [];
  35060. this._deltaPosition = BABYLON.Vector3.Zero();
  35061. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  35062. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  35063. /**
  35064. * this function is executed by the physics engine.
  35065. */
  35066. this.beforeStep = function () {
  35067. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  35068. //conjugate deltaRotation
  35069. if (_this._deltaRotationConjugated) {
  35070. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  35071. }
  35072. else {
  35073. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  35074. }
  35075. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  35076. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  35077. func(_this);
  35078. });
  35079. };
  35080. /**
  35081. * this function is executed by the physics engine.
  35082. */
  35083. this.afterStep = function () {
  35084. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  35085. func(_this);
  35086. });
  35087. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  35088. _this.object.position.addInPlace(_this._deltaPosition);
  35089. if (_this._deltaRotation) {
  35090. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  35091. }
  35092. };
  35093. /**
  35094. * Legacy collision detection event support
  35095. */
  35096. this.onCollideEvent = null;
  35097. //event and body object due to cannon's event-based architecture.
  35098. this.onCollide = function (e) {
  35099. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  35100. return;
  35101. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  35102. if (otherImpostor) {
  35103. // Legacy collision detection event support
  35104. if (_this.onCollideEvent) {
  35105. _this.onCollideEvent(_this, otherImpostor);
  35106. }
  35107. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  35108. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  35109. }).forEach(function (obj) {
  35110. obj.callback(_this, otherImpostor);
  35111. });
  35112. }
  35113. };
  35114. //sanity check!
  35115. if (!this.object) {
  35116. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  35117. return;
  35118. }
  35119. //legacy support for old syntax.
  35120. if (!this._scene && object.getScene) {
  35121. this._scene = object.getScene();
  35122. }
  35123. this._physicsEngine = this._scene.getPhysicsEngine();
  35124. if (!this._physicsEngine) {
  35125. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  35126. }
  35127. else {
  35128. //set the object's quaternion, if not set
  35129. if (!this.object.rotationQuaternion) {
  35130. if (this.object.rotation) {
  35131. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  35132. }
  35133. else {
  35134. this.object.rotationQuaternion = new BABYLON.Quaternion();
  35135. }
  35136. }
  35137. //default options params
  35138. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  35139. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  35140. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  35141. this._joints = [];
  35142. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  35143. if (!this.object.parent) {
  35144. this._init();
  35145. }
  35146. }
  35147. }
  35148. /**
  35149. * This function will completly initialize this impostor.
  35150. * It will create a new body - but only if this mesh has no parent.
  35151. * If it has, this impostor will not be used other than to define the impostor
  35152. * of the child mesh.
  35153. */
  35154. PhysicsImpostor.prototype._init = function () {
  35155. this._physicsEngine.removeImpostor(this);
  35156. this.physicsBody = null;
  35157. this._parent = this._parent || this._getPhysicsParent();
  35158. if (!this.parent) {
  35159. this._physicsEngine.addImpostor(this);
  35160. }
  35161. };
  35162. PhysicsImpostor.prototype._getPhysicsParent = function () {
  35163. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  35164. var parentMesh = this.object.parent;
  35165. return parentMesh.physicsImpostor;
  35166. }
  35167. return;
  35168. };
  35169. /**
  35170. * Should a new body be generated.
  35171. */
  35172. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  35173. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  35174. };
  35175. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  35176. this.forceUpdate();
  35177. };
  35178. /**
  35179. * Force a regeneration of this or the parent's impostor's body.
  35180. * Use under cautious - This will remove all joints already implemented.
  35181. */
  35182. PhysicsImpostor.prototype.forceUpdate = function () {
  35183. this._init();
  35184. if (this.parent) {
  35185. this.parent.forceUpdate();
  35186. }
  35187. };
  35188. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  35189. /*public get mesh(): AbstractMesh {
  35190. return this._mesh;
  35191. }*/
  35192. /**
  35193. * Gets the body that holds this impostor. Either its own, or its parent.
  35194. */
  35195. get: function () {
  35196. return this._parent ? this._parent.physicsBody : this._physicsBody;
  35197. },
  35198. /**
  35199. * Set the physics body. Used mainly by the physics engine/plugin
  35200. */
  35201. set: function (physicsBody) {
  35202. if (this._physicsBody) {
  35203. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  35204. }
  35205. this._physicsBody = physicsBody;
  35206. this.resetUpdateFlags();
  35207. },
  35208. enumerable: true,
  35209. configurable: true
  35210. });
  35211. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  35212. get: function () {
  35213. return this._parent;
  35214. },
  35215. set: function (value) {
  35216. this._parent = value;
  35217. },
  35218. enumerable: true,
  35219. configurable: true
  35220. });
  35221. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  35222. this._bodyUpdateRequired = false;
  35223. };
  35224. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  35225. if (this.object.getBoundingInfo) {
  35226. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  35227. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  35228. }
  35229. else {
  35230. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  35231. }
  35232. };
  35233. PhysicsImpostor.prototype.getObjectCenter = function () {
  35234. if (this.object.getBoundingInfo) {
  35235. return this.object.getBoundingInfo().boundingBox.center;
  35236. }
  35237. else {
  35238. return this.object.position;
  35239. }
  35240. };
  35241. /**
  35242. * Get a specific parametes from the options parameter.
  35243. */
  35244. PhysicsImpostor.prototype.getParam = function (paramName) {
  35245. return this._options[paramName];
  35246. };
  35247. /**
  35248. * Sets a specific parameter in the options given to the physics plugin
  35249. */
  35250. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  35251. this._options[paramName] = value;
  35252. this._bodyUpdateRequired = true;
  35253. };
  35254. /**
  35255. * Specifically change the body's mass option. Won't recreate the physics body object
  35256. */
  35257. PhysicsImpostor.prototype.setMass = function (mass) {
  35258. if (this.getParam("mass") !== mass) {
  35259. this.setParam("mass", mass);
  35260. }
  35261. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  35262. };
  35263. PhysicsImpostor.prototype.getLinearVelocity = function () {
  35264. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  35265. };
  35266. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  35267. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  35268. };
  35269. PhysicsImpostor.prototype.getAngularVelocity = function () {
  35270. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  35271. };
  35272. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  35273. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  35274. };
  35275. /**
  35276. * Execute a function with the physics plugin native code.
  35277. * Provide a function the will have two variables - the world object and the physics body object.
  35278. */
  35279. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  35280. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  35281. };
  35282. /**
  35283. * Register a function that will be executed before the physics world is stepping forward.
  35284. */
  35285. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  35286. this._onBeforePhysicsStepCallbacks.push(func);
  35287. };
  35288. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  35289. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  35290. if (index > -1) {
  35291. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  35292. }
  35293. else {
  35294. BABYLON.Tools.Warn("Function to remove was not found");
  35295. }
  35296. };
  35297. /**
  35298. * Register a function that will be executed after the physics step
  35299. */
  35300. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  35301. this._onAfterPhysicsStepCallbacks.push(func);
  35302. };
  35303. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  35304. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  35305. if (index > -1) {
  35306. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  35307. }
  35308. else {
  35309. BABYLON.Tools.Warn("Function to remove was not found");
  35310. }
  35311. };
  35312. /**
  35313. * register a function that will be executed when this impostor collides against a different body.
  35314. */
  35315. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  35316. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  35317. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  35318. };
  35319. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  35320. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  35321. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  35322. if (index > -1) {
  35323. this._onPhysicsCollideCallbacks.splice(index, 1);
  35324. }
  35325. else {
  35326. BABYLON.Tools.Warn("Function to remove was not found");
  35327. }
  35328. };
  35329. /**
  35330. * Apply a force
  35331. */
  35332. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  35333. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  35334. };
  35335. /**
  35336. * Apply an impulse
  35337. */
  35338. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  35339. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  35340. };
  35341. /**
  35342. * A help function to create a joint.
  35343. */
  35344. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  35345. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  35346. this.addJoint(otherImpostor, joint);
  35347. };
  35348. /**
  35349. * Add a joint to this impostor with a different impostor.
  35350. */
  35351. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  35352. this._joints.push({
  35353. otherImpostor: otherImpostor,
  35354. joint: joint
  35355. });
  35356. this._physicsEngine.addJoint(this, otherImpostor, joint);
  35357. };
  35358. /**
  35359. * Will keep this body still, in a sleep mode.
  35360. */
  35361. PhysicsImpostor.prototype.sleep = function () {
  35362. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  35363. };
  35364. /**
  35365. * Wake the body up.
  35366. */
  35367. PhysicsImpostor.prototype.wakeUp = function () {
  35368. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  35369. };
  35370. PhysicsImpostor.prototype.clone = function (newObject) {
  35371. if (!newObject)
  35372. return null;
  35373. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  35374. };
  35375. PhysicsImpostor.prototype.dispose = function () {
  35376. var _this = this;
  35377. //no dispose if no physics engine is available.
  35378. if (!this._physicsEngine) {
  35379. return;
  35380. }
  35381. this._joints.forEach(function (j) {
  35382. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  35383. });
  35384. //dispose the physics body
  35385. this._physicsEngine.removeImpostor(this);
  35386. if (this.parent) {
  35387. this.parent.forceUpdate();
  35388. }
  35389. else {
  35390. }
  35391. };
  35392. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  35393. this._deltaPosition.copyFrom(position);
  35394. };
  35395. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  35396. if (!this._deltaRotation) {
  35397. this._deltaRotation = new BABYLON.Quaternion();
  35398. }
  35399. this._deltaRotation.copyFrom(rotation);
  35400. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  35401. };
  35402. return PhysicsImpostor;
  35403. }());
  35404. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  35405. //Impostor types
  35406. PhysicsImpostor.NoImpostor = 0;
  35407. PhysicsImpostor.SphereImpostor = 1;
  35408. PhysicsImpostor.BoxImpostor = 2;
  35409. PhysicsImpostor.PlaneImpostor = 3;
  35410. PhysicsImpostor.MeshImpostor = 4;
  35411. PhysicsImpostor.CylinderImpostor = 7;
  35412. PhysicsImpostor.ParticleImpostor = 8;
  35413. PhysicsImpostor.HeightmapImpostor = 9;
  35414. BABYLON.PhysicsImpostor = PhysicsImpostor;
  35415. })(BABYLON || (BABYLON = {}));
  35416. //# sourceMappingURL=babylon.physicsImpostor.js.map
  35417. var BABYLON;
  35418. (function (BABYLON) {
  35419. var PhysicsEngine = (function () {
  35420. function PhysicsEngine(gravity, _physicsPlugin) {
  35421. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  35422. this._physicsPlugin = _physicsPlugin;
  35423. //new methods and parameters
  35424. this._impostors = [];
  35425. this._joints = [];
  35426. if (!this._physicsPlugin.isSupported()) {
  35427. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  35428. + "Please make sure it is included.");
  35429. }
  35430. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  35431. this.setGravity(gravity);
  35432. this.setTimeStep();
  35433. }
  35434. PhysicsEngine.prototype.setGravity = function (gravity) {
  35435. this.gravity = gravity;
  35436. this._physicsPlugin.setGravity(this.gravity);
  35437. };
  35438. /**
  35439. * Set the time step of the physics engine.
  35440. * default is 1/60.
  35441. * To slow it down, enter 1/600 for example.
  35442. * To speed it up, 1/30
  35443. * @param {number} newTimeStep the new timestep to apply to this world.
  35444. */
  35445. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  35446. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  35447. this._physicsPlugin.setTimeStep(newTimeStep);
  35448. };
  35449. PhysicsEngine.prototype.dispose = function () {
  35450. this._impostors.forEach(function (impostor) {
  35451. impostor.dispose();
  35452. });
  35453. this._physicsPlugin.dispose();
  35454. };
  35455. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  35456. return this._physicsPlugin.name;
  35457. };
  35458. /**
  35459. * Adding a new impostor for the impostor tracking.
  35460. * This will be done by the impostor itself.
  35461. * @param {PhysicsImpostor} impostor the impostor to add
  35462. */
  35463. PhysicsEngine.prototype.addImpostor = function (impostor) {
  35464. impostor.uniqueId = this._impostors.push(impostor);
  35465. //if no parent, generate the body
  35466. if (!impostor.parent) {
  35467. this._physicsPlugin.generatePhysicsBody(impostor);
  35468. }
  35469. };
  35470. /**
  35471. * Remove an impostor from the engine.
  35472. * This impostor and its mesh will not longer be updated by the physics engine.
  35473. * @param {PhysicsImpostor} impostor the impostor to remove
  35474. */
  35475. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  35476. var index = this._impostors.indexOf(impostor);
  35477. if (index > -1) {
  35478. var removed = this._impostors.splice(index, 1);
  35479. //Is it needed?
  35480. if (removed.length) {
  35481. //this will also remove it from the world.
  35482. removed[0].physicsBody = null;
  35483. }
  35484. }
  35485. };
  35486. /**
  35487. * Add a joint to the physics engine
  35488. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  35489. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  35490. * @param {PhysicsJoint} the joint that will connect both impostors.
  35491. */
  35492. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  35493. var impostorJoint = {
  35494. mainImpostor: mainImpostor,
  35495. connectedImpostor: connectedImpostor,
  35496. joint: joint
  35497. };
  35498. joint.physicsPlugin = this._physicsPlugin;
  35499. this._joints.push(impostorJoint);
  35500. this._physicsPlugin.generateJoint(impostorJoint);
  35501. };
  35502. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  35503. var matchingJoints = this._joints.filter(function (impostorJoint) {
  35504. return (impostorJoint.connectedImpostor === connectedImpostor
  35505. && impostorJoint.joint === joint
  35506. && impostorJoint.mainImpostor === mainImpostor);
  35507. });
  35508. if (matchingJoints.length) {
  35509. this._physicsPlugin.removeJoint(matchingJoints[0]);
  35510. }
  35511. };
  35512. /**
  35513. * Called by the scene. no need to call it.
  35514. */
  35515. PhysicsEngine.prototype._step = function (delta) {
  35516. var _this = this;
  35517. //check if any mesh has no body / requires an update
  35518. this._impostors.forEach(function (impostor) {
  35519. if (impostor.isBodyInitRequired()) {
  35520. _this._physicsPlugin.generatePhysicsBody(impostor);
  35521. }
  35522. });
  35523. if (delta > 0.1) {
  35524. delta = 0.1;
  35525. }
  35526. else if (delta <= 0) {
  35527. delta = 1.0 / 60.0;
  35528. }
  35529. this._physicsPlugin.executeStep(delta, this._impostors);
  35530. };
  35531. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  35532. return this._physicsPlugin;
  35533. };
  35534. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  35535. for (var i = 0; i < this._impostors.length; ++i) {
  35536. if (this._impostors[i].object === object) {
  35537. return this._impostors[i];
  35538. }
  35539. }
  35540. };
  35541. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  35542. for (var i = 0; i < this._impostors.length; ++i) {
  35543. if (this._impostors[i].physicsBody === body) {
  35544. return this._impostors[i];
  35545. }
  35546. }
  35547. };
  35548. return PhysicsEngine;
  35549. }());
  35550. // Statics, Legacy support.
  35551. /**
  35552. * @Deprecated
  35553. *
  35554. */
  35555. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  35556. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  35557. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  35558. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  35559. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  35560. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  35561. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  35562. PhysicsEngine.CapsuleImpostor = -1;
  35563. PhysicsEngine.ConeImpostor = -1;
  35564. PhysicsEngine.ConvexHullImpostor = -1;
  35565. PhysicsEngine.Epsilon = 0.001;
  35566. BABYLON.PhysicsEngine = PhysicsEngine;
  35567. })(BABYLON || (BABYLON = {}));
  35568. //# sourceMappingURL=babylon.physicsEngine.js.map
  35569. var BABYLON;
  35570. (function (BABYLON) {
  35571. var VertexData = (function () {
  35572. function VertexData() {
  35573. }
  35574. VertexData.prototype.set = function (data, kind) {
  35575. switch (kind) {
  35576. case BABYLON.VertexBuffer.PositionKind:
  35577. this.positions = data;
  35578. break;
  35579. case BABYLON.VertexBuffer.NormalKind:
  35580. this.normals = data;
  35581. break;
  35582. case BABYLON.VertexBuffer.UVKind:
  35583. this.uvs = data;
  35584. break;
  35585. case BABYLON.VertexBuffer.UV2Kind:
  35586. this.uvs2 = data;
  35587. break;
  35588. case BABYLON.VertexBuffer.UV3Kind:
  35589. this.uvs3 = data;
  35590. break;
  35591. case BABYLON.VertexBuffer.UV4Kind:
  35592. this.uvs4 = data;
  35593. break;
  35594. case BABYLON.VertexBuffer.UV5Kind:
  35595. this.uvs5 = data;
  35596. break;
  35597. case BABYLON.VertexBuffer.UV6Kind:
  35598. this.uvs6 = data;
  35599. break;
  35600. case BABYLON.VertexBuffer.ColorKind:
  35601. this.colors = data;
  35602. break;
  35603. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35604. this.matricesIndices = data;
  35605. break;
  35606. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35607. this.matricesWeights = data;
  35608. break;
  35609. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35610. this.matricesIndicesExtra = data;
  35611. break;
  35612. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35613. this.matricesWeightsExtra = data;
  35614. break;
  35615. }
  35616. };
  35617. /**
  35618. * Associates the vertexData to the passed Mesh.
  35619. * Sets it as updatable or not (default `false`).
  35620. * Returns the VertexData.
  35621. */
  35622. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35623. this._applyTo(mesh, updatable);
  35624. return this;
  35625. };
  35626. /**
  35627. * Associates the vertexData to the passed Geometry.
  35628. * Sets it as updatable or not (default `false`).
  35629. * Returns the VertexData.
  35630. */
  35631. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35632. this._applyTo(geometry, updatable);
  35633. return this;
  35634. };
  35635. /**
  35636. * Updates the associated mesh.
  35637. * Returns the VertexData.
  35638. */
  35639. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35640. this._update(mesh);
  35641. return this;
  35642. };
  35643. /**
  35644. * Updates the associated geometry.
  35645. * Returns the VertexData.
  35646. */
  35647. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35648. this._update(geometry);
  35649. return this;
  35650. };
  35651. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35652. if (this.positions) {
  35653. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35654. }
  35655. if (this.normals) {
  35656. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35657. }
  35658. if (this.uvs) {
  35659. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35660. }
  35661. if (this.uvs2) {
  35662. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35663. }
  35664. if (this.uvs3) {
  35665. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35666. }
  35667. if (this.uvs4) {
  35668. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35669. }
  35670. if (this.uvs5) {
  35671. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35672. }
  35673. if (this.uvs6) {
  35674. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35675. }
  35676. if (this.colors) {
  35677. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35678. }
  35679. if (this.matricesIndices) {
  35680. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35681. }
  35682. if (this.matricesWeights) {
  35683. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35684. }
  35685. if (this.matricesIndicesExtra) {
  35686. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35687. }
  35688. if (this.matricesWeightsExtra) {
  35689. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35690. }
  35691. if (this.indices) {
  35692. meshOrGeometry.setIndices(this.indices);
  35693. }
  35694. return this;
  35695. };
  35696. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35697. if (this.positions) {
  35698. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35699. }
  35700. if (this.normals) {
  35701. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35702. }
  35703. if (this.uvs) {
  35704. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35705. }
  35706. if (this.uvs2) {
  35707. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35708. }
  35709. if (this.uvs3) {
  35710. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35711. }
  35712. if (this.uvs4) {
  35713. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35714. }
  35715. if (this.uvs5) {
  35716. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35717. }
  35718. if (this.uvs6) {
  35719. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35720. }
  35721. if (this.colors) {
  35722. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35723. }
  35724. if (this.matricesIndices) {
  35725. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35726. }
  35727. if (this.matricesWeights) {
  35728. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35729. }
  35730. if (this.matricesIndicesExtra) {
  35731. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35732. }
  35733. if (this.matricesWeightsExtra) {
  35734. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35735. }
  35736. if (this.indices) {
  35737. meshOrGeometry.setIndices(this.indices);
  35738. }
  35739. return this;
  35740. };
  35741. /**
  35742. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  35743. * Returns the VertexData.
  35744. */
  35745. VertexData.prototype.transform = function (matrix) {
  35746. var transformed = BABYLON.Vector3.Zero();
  35747. var index;
  35748. if (this.positions) {
  35749. var position = BABYLON.Vector3.Zero();
  35750. for (index = 0; index < this.positions.length; index += 3) {
  35751. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  35752. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  35753. this.positions[index] = transformed.x;
  35754. this.positions[index + 1] = transformed.y;
  35755. this.positions[index + 2] = transformed.z;
  35756. }
  35757. }
  35758. if (this.normals) {
  35759. var normal = BABYLON.Vector3.Zero();
  35760. for (index = 0; index < this.normals.length; index += 3) {
  35761. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  35762. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  35763. this.normals[index] = transformed.x;
  35764. this.normals[index + 1] = transformed.y;
  35765. this.normals[index + 2] = transformed.z;
  35766. }
  35767. }
  35768. return this;
  35769. };
  35770. /**
  35771. * Merges the passed VertexData into the current one.
  35772. * Returns the modified VertexData.
  35773. */
  35774. VertexData.prototype.merge = function (other) {
  35775. if (other.indices) {
  35776. if (!this.indices) {
  35777. this.indices = [];
  35778. }
  35779. var offset = this.positions ? this.positions.length / 3 : 0;
  35780. for (var index = 0; index < other.indices.length; index++) {
  35781. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  35782. this.indices.push(other.indices[index] + offset);
  35783. }
  35784. }
  35785. this.positions = this._mergeElement(this.positions, other.positions);
  35786. this.normals = this._mergeElement(this.normals, other.normals);
  35787. this.uvs = this._mergeElement(this.uvs, other.uvs);
  35788. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  35789. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  35790. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  35791. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  35792. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  35793. this.colors = this._mergeElement(this.colors, other.colors);
  35794. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  35795. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  35796. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  35797. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  35798. return this;
  35799. };
  35800. VertexData.prototype._mergeElement = function (source, other) {
  35801. if (!other)
  35802. return source;
  35803. if (!source)
  35804. return other;
  35805. var len = other.length + source.length;
  35806. var isSrcTypedArray = source instanceof Float32Array;
  35807. var isOthTypedArray = other instanceof Float32Array;
  35808. // use non-loop method when the source is Float32Array
  35809. if (isSrcTypedArray) {
  35810. var ret32 = new Float32Array(len);
  35811. ret32.set(source);
  35812. ret32.set(other, source.length);
  35813. return ret32;
  35814. }
  35815. else if (!isOthTypedArray) {
  35816. return source.concat(other);
  35817. }
  35818. else {
  35819. var ret = source.slice(0); // copy source to a separate array
  35820. for (var i = 0, len = other.length; i < len; i++) {
  35821. ret.push(other[i]);
  35822. }
  35823. return ret;
  35824. }
  35825. };
  35826. /**
  35827. * Serializes the VertexData.
  35828. * Returns a serialized object.
  35829. */
  35830. VertexData.prototype.serialize = function () {
  35831. var serializationObject = this.serialize();
  35832. if (this.positions) {
  35833. serializationObject.positions = this.positions;
  35834. }
  35835. if (this.normals) {
  35836. serializationObject.normals = this.normals;
  35837. }
  35838. if (this.uvs) {
  35839. serializationObject.uvs = this.uvs;
  35840. }
  35841. if (this.uvs2) {
  35842. serializationObject.uvs2 = this.uvs2;
  35843. }
  35844. if (this.uvs3) {
  35845. serializationObject.uvs3 = this.uvs3;
  35846. }
  35847. if (this.uvs4) {
  35848. serializationObject.uvs4 = this.uvs4;
  35849. }
  35850. if (this.uvs5) {
  35851. serializationObject.uvs5 = this.uvs5;
  35852. }
  35853. if (this.uvs6) {
  35854. serializationObject.uvs6 = this.uvs6;
  35855. }
  35856. if (this.colors) {
  35857. serializationObject.colors = this.colors;
  35858. }
  35859. if (this.matricesIndices) {
  35860. serializationObject.matricesIndices = this.matricesIndices;
  35861. serializationObject.matricesIndices._isExpanded = true;
  35862. }
  35863. if (this.matricesWeights) {
  35864. serializationObject.matricesWeights = this.matricesWeights;
  35865. }
  35866. if (this.matricesIndicesExtra) {
  35867. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  35868. serializationObject.matricesIndicesExtra._isExpanded = true;
  35869. }
  35870. if (this.matricesWeightsExtra) {
  35871. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  35872. }
  35873. serializationObject.indices = this.indices;
  35874. return serializationObject;
  35875. };
  35876. // Statics
  35877. /**
  35878. * Returns the object VertexData associated to the passed mesh.
  35879. */
  35880. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  35881. return VertexData._ExtractFrom(mesh, copyWhenShared);
  35882. };
  35883. /**
  35884. * Returns the object VertexData associated to the passed geometry.
  35885. */
  35886. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  35887. return VertexData._ExtractFrom(geometry, copyWhenShared);
  35888. };
  35889. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  35890. var result = new VertexData();
  35891. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35892. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  35893. }
  35894. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35895. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  35896. }
  35897. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35898. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  35899. }
  35900. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35901. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  35902. }
  35903. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35904. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  35905. }
  35906. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35907. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  35908. }
  35909. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35910. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  35911. }
  35912. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35913. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  35914. }
  35915. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35916. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  35917. }
  35918. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35919. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  35920. }
  35921. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35922. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  35923. }
  35924. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  35925. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  35926. }
  35927. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  35928. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  35929. }
  35930. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  35931. return result;
  35932. };
  35933. /**
  35934. * Creates the vertexData of the Ribbon.
  35935. */
  35936. VertexData.CreateRibbon = function (options) {
  35937. var pathArray = options.pathArray;
  35938. var closeArray = options.closeArray || false;
  35939. var closePath = options.closePath || false;
  35940. var invertUV = options.invertUV || false;
  35941. var defaultOffset = Math.floor(pathArray[0].length / 2);
  35942. var offset = options.offset || defaultOffset;
  35943. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  35944. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35945. var positions = [];
  35946. var indices = [];
  35947. var normals = [];
  35948. var uvs = [];
  35949. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  35950. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  35951. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  35952. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  35953. var minlg; // minimal length among all paths from pathArray
  35954. var lg = []; // array of path lengths : nb of vertex per path
  35955. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  35956. var p; // path iterator
  35957. var i; // point iterator
  35958. var j; // point iterator
  35959. // if single path in pathArray
  35960. if (pathArray.length < 2) {
  35961. var ar1 = [];
  35962. var ar2 = [];
  35963. for (i = 0; i < pathArray[0].length - offset; i++) {
  35964. ar1.push(pathArray[0][i]);
  35965. ar2.push(pathArray[0][i + offset]);
  35966. }
  35967. pathArray = [ar1, ar2];
  35968. }
  35969. // positions and horizontal distances (u)
  35970. var idc = 0;
  35971. var closePathCorr = (closePath) ? 1 : 0;
  35972. var path;
  35973. var l;
  35974. minlg = pathArray[0].length;
  35975. var vectlg;
  35976. var dist;
  35977. for (p = 0; p < pathArray.length; p++) {
  35978. uTotalDistance[p] = 0;
  35979. us[p] = [0];
  35980. path = pathArray[p];
  35981. l = path.length;
  35982. minlg = (minlg < l) ? minlg : l;
  35983. j = 0;
  35984. while (j < l) {
  35985. positions.push(path[j].x, path[j].y, path[j].z);
  35986. if (j > 0) {
  35987. vectlg = path[j].subtract(path[j - 1]).length();
  35988. dist = vectlg + uTotalDistance[p];
  35989. us[p].push(dist);
  35990. uTotalDistance[p] = dist;
  35991. }
  35992. j++;
  35993. }
  35994. if (closePath) {
  35995. j--;
  35996. positions.push(path[0].x, path[0].y, path[0].z);
  35997. vectlg = path[j].subtract(path[0]).length();
  35998. dist = vectlg + uTotalDistance[p];
  35999. us[p].push(dist);
  36000. uTotalDistance[p] = dist;
  36001. }
  36002. lg[p] = l + closePathCorr;
  36003. idx[p] = idc;
  36004. idc += (l + closePathCorr);
  36005. }
  36006. // vertical distances (v)
  36007. var path1;
  36008. var path2;
  36009. var vertex1;
  36010. var vertex2;
  36011. for (i = 0; i < minlg + closePathCorr; i++) {
  36012. vTotalDistance[i] = 0;
  36013. vs[i] = [0];
  36014. for (p = 0; p < pathArray.length - 1; p++) {
  36015. path1 = pathArray[p];
  36016. path2 = pathArray[p + 1];
  36017. if (i === minlg) {
  36018. vertex1 = path1[0];
  36019. vertex2 = path2[0];
  36020. }
  36021. else {
  36022. vertex1 = path1[i];
  36023. vertex2 = path2[i];
  36024. }
  36025. vectlg = vertex2.subtract(vertex1).length();
  36026. dist = vectlg + vTotalDistance[i];
  36027. vs[i].push(dist);
  36028. vTotalDistance[i] = dist;
  36029. }
  36030. if (closeArray) {
  36031. path1 = pathArray[p];
  36032. path2 = pathArray[0];
  36033. if (i === minlg) {
  36034. vertex2 = path2[0];
  36035. }
  36036. vectlg = vertex2.subtract(vertex1).length();
  36037. dist = vectlg + vTotalDistance[i];
  36038. vTotalDistance[i] = dist;
  36039. }
  36040. }
  36041. // uvs
  36042. var u;
  36043. var v;
  36044. for (p = 0; p < pathArray.length; p++) {
  36045. for (i = 0; i < minlg + closePathCorr; i++) {
  36046. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36047. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36048. if (invertUV) {
  36049. uvs.push(v, u);
  36050. }
  36051. else {
  36052. uvs.push(u, v);
  36053. }
  36054. }
  36055. }
  36056. // indices
  36057. p = 0; // path index
  36058. var pi = 0; // positions array index
  36059. var l1 = lg[p] - 1; // path1 length
  36060. var l2 = lg[p + 1] - 1; // path2 length
  36061. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36062. var shft = idx[1] - idx[0]; // shift
  36063. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36064. while (pi <= min && p < path1nb) {
  36065. // 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
  36066. indices.push(pi, pi + shft, pi + 1);
  36067. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36068. pi += 1;
  36069. if (pi === min) {
  36070. p++;
  36071. if (p === lg.length - 1) {
  36072. shft = idx[0] - idx[p];
  36073. l1 = lg[p] - 1;
  36074. l2 = lg[0] - 1;
  36075. }
  36076. else {
  36077. shft = idx[p + 1] - idx[p];
  36078. l1 = lg[p] - 1;
  36079. l2 = lg[p + 1] - 1;
  36080. }
  36081. pi = idx[p];
  36082. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36083. }
  36084. }
  36085. // normals
  36086. VertexData.ComputeNormals(positions, indices, normals);
  36087. if (closePath) {
  36088. var indexFirst = 0;
  36089. var indexLast = 0;
  36090. for (p = 0; p < pathArray.length; p++) {
  36091. indexFirst = idx[p] * 3;
  36092. if (p + 1 < pathArray.length) {
  36093. indexLast = (idx[p + 1] - 1) * 3;
  36094. }
  36095. else {
  36096. indexLast = normals.length - 3;
  36097. }
  36098. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36099. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36100. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36101. normals[indexLast] = normals[indexFirst];
  36102. normals[indexLast + 1] = normals[indexFirst + 1];
  36103. normals[indexLast + 2] = normals[indexFirst + 2];
  36104. }
  36105. }
  36106. // sides
  36107. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36108. // Result
  36109. var vertexData = new VertexData();
  36110. vertexData.indices = indices;
  36111. vertexData.positions = positions;
  36112. vertexData.normals = normals;
  36113. vertexData.uvs = uvs;
  36114. if (closePath) {
  36115. vertexData._idx = idx;
  36116. }
  36117. return vertexData;
  36118. };
  36119. /**
  36120. * Creates the VertexData of the Box.
  36121. */
  36122. VertexData.CreateBox = function (options) {
  36123. var normalsSource = [
  36124. new BABYLON.Vector3(0, 0, 1),
  36125. new BABYLON.Vector3(0, 0, -1),
  36126. new BABYLON.Vector3(1, 0, 0),
  36127. new BABYLON.Vector3(-1, 0, 0),
  36128. new BABYLON.Vector3(0, 1, 0),
  36129. new BABYLON.Vector3(0, -1, 0)
  36130. ];
  36131. var indices = [];
  36132. var positions = [];
  36133. var normals = [];
  36134. var uvs = [];
  36135. var width = options.width || options.size || 1;
  36136. var height = options.height || options.size || 1;
  36137. var depth = options.depth || options.size || 1;
  36138. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36139. var faceUV = options.faceUV || new Array(6);
  36140. var faceColors = options.faceColors;
  36141. var colors = [];
  36142. // default face colors and UV if undefined
  36143. for (var f = 0; f < 6; f++) {
  36144. if (faceUV[f] === undefined) {
  36145. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36146. }
  36147. if (faceColors && faceColors[f] === undefined) {
  36148. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36149. }
  36150. }
  36151. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36152. // Create each face in turn.
  36153. for (var index = 0; index < normalsSource.length; index++) {
  36154. var normal = normalsSource[index];
  36155. // Get two vectors perpendicular to the face normal and to each other.
  36156. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36157. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36158. // Six indices (two triangles) per face.
  36159. var verticesLength = positions.length / 3;
  36160. indices.push(verticesLength);
  36161. indices.push(verticesLength + 1);
  36162. indices.push(verticesLength + 2);
  36163. indices.push(verticesLength);
  36164. indices.push(verticesLength + 2);
  36165. indices.push(verticesLength + 3);
  36166. // Four vertices per face.
  36167. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36168. positions.push(vertex.x, vertex.y, vertex.z);
  36169. normals.push(normal.x, normal.y, normal.z);
  36170. uvs.push(faceUV[index].z, faceUV[index].w);
  36171. if (faceColors) {
  36172. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36173. }
  36174. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36175. positions.push(vertex.x, vertex.y, vertex.z);
  36176. normals.push(normal.x, normal.y, normal.z);
  36177. uvs.push(faceUV[index].x, faceUV[index].w);
  36178. if (faceColors) {
  36179. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36180. }
  36181. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36182. positions.push(vertex.x, vertex.y, vertex.z);
  36183. normals.push(normal.x, normal.y, normal.z);
  36184. uvs.push(faceUV[index].x, faceUV[index].y);
  36185. if (faceColors) {
  36186. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36187. }
  36188. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36189. positions.push(vertex.x, vertex.y, vertex.z);
  36190. normals.push(normal.x, normal.y, normal.z);
  36191. uvs.push(faceUV[index].z, faceUV[index].y);
  36192. if (faceColors) {
  36193. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36194. }
  36195. }
  36196. // sides
  36197. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36198. // Result
  36199. var vertexData = new VertexData();
  36200. vertexData.indices = indices;
  36201. vertexData.positions = positions;
  36202. vertexData.normals = normals;
  36203. vertexData.uvs = uvs;
  36204. if (faceColors) {
  36205. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36206. vertexData.colors = totalColors;
  36207. }
  36208. return vertexData;
  36209. };
  36210. /**
  36211. * Creates the VertexData of the Sphere.
  36212. */
  36213. VertexData.CreateSphere = function (options) {
  36214. var segments = options.segments || 32;
  36215. var diameterX = options.diameterX || options.diameter || 1;
  36216. var diameterY = options.diameterY || options.diameter || 1;
  36217. var diameterZ = options.diameterZ || options.diameter || 1;
  36218. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36219. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36220. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36221. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36222. var totalZRotationSteps = 2 + segments;
  36223. var totalYRotationSteps = 2 * totalZRotationSteps;
  36224. var indices = [];
  36225. var positions = [];
  36226. var normals = [];
  36227. var uvs = [];
  36228. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36229. var normalizedZ = zRotationStep / totalZRotationSteps;
  36230. var angleZ = normalizedZ * Math.PI * slice;
  36231. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36232. var normalizedY = yRotationStep / totalYRotationSteps;
  36233. var angleY = normalizedY * Math.PI * 2 * arc;
  36234. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36235. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36236. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36237. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36238. var vertex = complete.multiply(radius);
  36239. var normal = complete.divide(radius).normalize();
  36240. positions.push(vertex.x, vertex.y, vertex.z);
  36241. normals.push(normal.x, normal.y, normal.z);
  36242. uvs.push(normalizedY, normalizedZ);
  36243. }
  36244. if (zRotationStep > 0) {
  36245. var verticesCount = positions.length / 3;
  36246. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36247. indices.push((firstIndex));
  36248. indices.push((firstIndex + 1));
  36249. indices.push(firstIndex + totalYRotationSteps + 1);
  36250. indices.push((firstIndex + totalYRotationSteps + 1));
  36251. indices.push((firstIndex + 1));
  36252. indices.push((firstIndex + totalYRotationSteps + 2));
  36253. }
  36254. }
  36255. }
  36256. // Sides
  36257. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36258. // Result
  36259. var vertexData = new VertexData();
  36260. vertexData.indices = indices;
  36261. vertexData.positions = positions;
  36262. vertexData.normals = normals;
  36263. vertexData.uvs = uvs;
  36264. return vertexData;
  36265. };
  36266. /**
  36267. * Creates the VertexData of the Cylinder or Cone.
  36268. */
  36269. VertexData.CreateCylinder = function (options) {
  36270. var height = options.height || 2;
  36271. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36272. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36273. var tessellation = options.tessellation || 24;
  36274. var subdivisions = options.subdivisions || 1;
  36275. var hasRings = options.hasRings;
  36276. var enclose = options.enclose;
  36277. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36278. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36279. var faceUV = options.faceUV || new Array(3);
  36280. var faceColors = options.faceColors;
  36281. // default face colors and UV if undefined
  36282. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36283. var ringNb = (hasRings) ? subdivisions : 1;
  36284. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36285. var f;
  36286. for (f = 0; f < surfaceNb; f++) {
  36287. if (faceColors && faceColors[f] === undefined) {
  36288. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36289. }
  36290. }
  36291. for (f = 0; f < surfaceNb; f++) {
  36292. if (faceUV && faceUV[f] === undefined) {
  36293. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36294. }
  36295. }
  36296. var indices = [];
  36297. var positions = [];
  36298. var normals = [];
  36299. var uvs = [];
  36300. var colors = [];
  36301. var angle_step = Math.PI * 2 * arc / tessellation;
  36302. var angle;
  36303. var h;
  36304. var radius;
  36305. var tan = (diameterBottom - diameterTop) / 2 / height;
  36306. var ringVertex = BABYLON.Vector3.Zero();
  36307. var ringNormal = BABYLON.Vector3.Zero();
  36308. var ringFirstVertex = BABYLON.Vector3.Zero();
  36309. var ringFirstNormal = BABYLON.Vector3.Zero();
  36310. var quadNormal = BABYLON.Vector3.Zero();
  36311. var Y = BABYLON.Axis.Y;
  36312. // positions, normals, uvs
  36313. var i;
  36314. var j;
  36315. var r;
  36316. var ringIdx = 1;
  36317. var s = 1; // surface index
  36318. var cs = 0;
  36319. var v = 0;
  36320. for (i = 0; i <= subdivisions; i++) {
  36321. h = i / subdivisions;
  36322. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36323. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36324. for (r = 0; r < ringIdx; r++) {
  36325. if (hasRings) {
  36326. s += r;
  36327. }
  36328. if (enclose) {
  36329. s += 2 * r;
  36330. }
  36331. for (j = 0; j <= tessellation; j++) {
  36332. angle = j * angle_step;
  36333. // position
  36334. ringVertex.x = Math.cos(-angle) * radius;
  36335. ringVertex.y = -height / 2 + h * height;
  36336. ringVertex.z = Math.sin(-angle) * radius;
  36337. // normal
  36338. if (diameterTop === 0 && i === subdivisions) {
  36339. // if no top cap, reuse former normals
  36340. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36341. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36342. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36343. }
  36344. else {
  36345. ringNormal.x = ringVertex.x;
  36346. ringNormal.z = ringVertex.z;
  36347. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36348. ringNormal.normalize();
  36349. }
  36350. // keep first ring vertex values for enclose
  36351. if (j === 0) {
  36352. ringFirstVertex.copyFrom(ringVertex);
  36353. ringFirstNormal.copyFrom(ringNormal);
  36354. }
  36355. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36356. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36357. if (hasRings) {
  36358. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36359. }
  36360. else {
  36361. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36362. }
  36363. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36364. if (faceColors) {
  36365. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36366. }
  36367. }
  36368. // if enclose, add four vertices and their dedicated normals
  36369. if (arc !== 1 && enclose) {
  36370. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36371. positions.push(0, ringVertex.y, 0);
  36372. positions.push(0, ringVertex.y, 0);
  36373. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36374. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36375. quadNormal.normalize();
  36376. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36377. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36378. quadNormal.normalize();
  36379. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36380. if (hasRings) {
  36381. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36382. }
  36383. else {
  36384. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36385. }
  36386. uvs.push(faceUV[s + 1].x, v);
  36387. uvs.push(faceUV[s + 1].z, v);
  36388. if (hasRings) {
  36389. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36390. }
  36391. else {
  36392. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36393. }
  36394. uvs.push(faceUV[s + 2].x, v);
  36395. uvs.push(faceUV[s + 2].z, v);
  36396. if (faceColors) {
  36397. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36398. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36399. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36400. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36401. }
  36402. }
  36403. if (cs !== s) {
  36404. cs = s;
  36405. }
  36406. }
  36407. }
  36408. // indices
  36409. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36410. var s;
  36411. i = 0;
  36412. for (s = 0; s < subdivisions; s++) {
  36413. for (j = 0; j < tessellation; j++) {
  36414. var i0 = i * (e + 1) + j;
  36415. var i1 = (i + 1) * (e + 1) + j;
  36416. var i2 = i * (e + 1) + (j + 1);
  36417. var i3 = (i + 1) * (e + 1) + (j + 1);
  36418. indices.push(i0, i1, i2);
  36419. indices.push(i3, i2, i1);
  36420. }
  36421. if (arc !== 1 && enclose) {
  36422. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36423. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36424. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36425. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36426. }
  36427. i = (hasRings) ? (i + 2) : (i + 1);
  36428. }
  36429. // Caps
  36430. var createCylinderCap = function (isTop) {
  36431. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36432. if (radius === 0) {
  36433. return;
  36434. }
  36435. // Cap positions, normals & uvs
  36436. var angle;
  36437. var circleVector;
  36438. var i;
  36439. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36440. var c;
  36441. if (faceColors) {
  36442. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36443. }
  36444. // cap center
  36445. var vbase = positions.length / 3;
  36446. var offset = isTop ? height / 2 : -height / 2;
  36447. var center = new BABYLON.Vector3(0, offset, 0);
  36448. positions.push(center.x, center.y, center.z);
  36449. normals.push(0, isTop ? 1 : -1, 0);
  36450. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36451. if (faceColors) {
  36452. colors.push(c.r, c.g, c.b, c.a);
  36453. }
  36454. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36455. for (i = 0; i <= tessellation; i++) {
  36456. angle = Math.PI * 2 * i * arc / tessellation;
  36457. var cos = Math.cos(-angle);
  36458. var sin = Math.sin(-angle);
  36459. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36460. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36461. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36462. normals.push(0, isTop ? 1 : -1, 0);
  36463. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36464. if (faceColors) {
  36465. colors.push(c.r, c.g, c.b, c.a);
  36466. }
  36467. }
  36468. // Cap indices
  36469. for (i = 0; i < tessellation; i++) {
  36470. if (!isTop) {
  36471. indices.push(vbase);
  36472. indices.push(vbase + (i + 1));
  36473. indices.push(vbase + (i + 2));
  36474. }
  36475. else {
  36476. indices.push(vbase);
  36477. indices.push(vbase + (i + 2));
  36478. indices.push(vbase + (i + 1));
  36479. }
  36480. }
  36481. };
  36482. // add caps to geometry
  36483. createCylinderCap(false);
  36484. createCylinderCap(true);
  36485. // Sides
  36486. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36487. var vertexData = new VertexData();
  36488. vertexData.indices = indices;
  36489. vertexData.positions = positions;
  36490. vertexData.normals = normals;
  36491. vertexData.uvs = uvs;
  36492. if (faceColors) {
  36493. vertexData.colors = colors;
  36494. }
  36495. return vertexData;
  36496. };
  36497. /**
  36498. * Creates the VertexData of the Torus.
  36499. */
  36500. VertexData.CreateTorus = function (options) {
  36501. var indices = [];
  36502. var positions = [];
  36503. var normals = [];
  36504. var uvs = [];
  36505. var diameter = options.diameter || 1;
  36506. var thickness = options.thickness || 0.5;
  36507. var tessellation = options.tessellation || 16;
  36508. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36509. var stride = tessellation + 1;
  36510. for (var i = 0; i <= tessellation; i++) {
  36511. var u = i / tessellation;
  36512. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36513. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36514. for (var j = 0; j <= tessellation; j++) {
  36515. var v = 1 - j / tessellation;
  36516. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36517. var dx = Math.cos(innerAngle);
  36518. var dy = Math.sin(innerAngle);
  36519. // Create a vertex.
  36520. var normal = new BABYLON.Vector3(dx, dy, 0);
  36521. var position = normal.scale(thickness / 2);
  36522. var textureCoordinate = new BABYLON.Vector2(u, v);
  36523. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36524. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36525. positions.push(position.x, position.y, position.z);
  36526. normals.push(normal.x, normal.y, normal.z);
  36527. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36528. // And create indices for two triangles.
  36529. var nextI = (i + 1) % stride;
  36530. var nextJ = (j + 1) % stride;
  36531. indices.push(i * stride + j);
  36532. indices.push(i * stride + nextJ);
  36533. indices.push(nextI * stride + j);
  36534. indices.push(i * stride + nextJ);
  36535. indices.push(nextI * stride + nextJ);
  36536. indices.push(nextI * stride + j);
  36537. }
  36538. }
  36539. // Sides
  36540. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36541. // Result
  36542. var vertexData = new VertexData();
  36543. vertexData.indices = indices;
  36544. vertexData.positions = positions;
  36545. vertexData.normals = normals;
  36546. vertexData.uvs = uvs;
  36547. return vertexData;
  36548. };
  36549. /**
  36550. * Creates the VertexData of the LineSystem.
  36551. */
  36552. VertexData.CreateLineSystem = function (options) {
  36553. var indices = [];
  36554. var positions = [];
  36555. var lines = options.lines;
  36556. var idx = 0;
  36557. for (var l = 0; l < lines.length; l++) {
  36558. var points = lines[l];
  36559. for (var index = 0; index < points.length; index++) {
  36560. positions.push(points[index].x, points[index].y, points[index].z);
  36561. if (index > 0) {
  36562. indices.push(idx - 1);
  36563. indices.push(idx);
  36564. }
  36565. idx++;
  36566. }
  36567. }
  36568. var vertexData = new VertexData();
  36569. vertexData.indices = indices;
  36570. vertexData.positions = positions;
  36571. return vertexData;
  36572. };
  36573. /**
  36574. * Create the VertexData of the DashedLines.
  36575. */
  36576. VertexData.CreateDashedLines = function (options) {
  36577. var dashSize = options.dashSize || 3;
  36578. var gapSize = options.gapSize || 1;
  36579. var dashNb = options.dashNb || 200;
  36580. var points = options.points;
  36581. var positions = new Array();
  36582. var indices = new Array();
  36583. var curvect = BABYLON.Vector3.Zero();
  36584. var lg = 0;
  36585. var nb = 0;
  36586. var shft = 0;
  36587. var dashshft = 0;
  36588. var curshft = 0;
  36589. var idx = 0;
  36590. var i = 0;
  36591. for (i = 0; i < points.length - 1; i++) {
  36592. points[i + 1].subtractToRef(points[i], curvect);
  36593. lg += curvect.length();
  36594. }
  36595. shft = lg / dashNb;
  36596. dashshft = dashSize * shft / (dashSize + gapSize);
  36597. for (i = 0; i < points.length - 1; i++) {
  36598. points[i + 1].subtractToRef(points[i], curvect);
  36599. nb = Math.floor(curvect.length() / shft);
  36600. curvect.normalize();
  36601. for (var j = 0; j < nb; j++) {
  36602. curshft = shft * j;
  36603. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  36604. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  36605. indices.push(idx, idx + 1);
  36606. idx += 2;
  36607. }
  36608. }
  36609. // Result
  36610. var vertexData = new VertexData();
  36611. vertexData.positions = positions;
  36612. vertexData.indices = indices;
  36613. return vertexData;
  36614. };
  36615. /**
  36616. * Creates the VertexData of the Ground.
  36617. */
  36618. VertexData.CreateGround = function (options) {
  36619. var indices = [];
  36620. var positions = [];
  36621. var normals = [];
  36622. var uvs = [];
  36623. var row, col;
  36624. var width = options.width || 1;
  36625. var height = options.height || 1;
  36626. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  36627. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  36628. for (row = 0; row <= subdivisionsY; row++) {
  36629. for (col = 0; col <= subdivisionsX; col++) {
  36630. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  36631. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36632. positions.push(position.x, position.y, position.z);
  36633. normals.push(normal.x, normal.y, normal.z);
  36634. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  36635. }
  36636. }
  36637. for (row = 0; row < subdivisionsY; row++) {
  36638. for (col = 0; col < subdivisionsX; col++) {
  36639. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36640. indices.push(col + 1 + row * (subdivisionsX + 1));
  36641. indices.push(col + row * (subdivisionsX + 1));
  36642. indices.push(col + (row + 1) * (subdivisionsX + 1));
  36643. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36644. indices.push(col + row * (subdivisionsX + 1));
  36645. }
  36646. }
  36647. // Result
  36648. var vertexData = new VertexData();
  36649. vertexData.indices = indices;
  36650. vertexData.positions = positions;
  36651. vertexData.normals = normals;
  36652. vertexData.uvs = uvs;
  36653. return vertexData;
  36654. };
  36655. /**
  36656. * Creates the VertexData of the TiledGround.
  36657. */
  36658. VertexData.CreateTiledGround = function (options) {
  36659. var xmin = options.xmin || -1.0;
  36660. var zmin = options.zmin || -1.0;
  36661. var xmax = options.xmax || 1.0;
  36662. var zmax = options.zmax || 1.0;
  36663. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  36664. var precision = options.precision || { w: 1, h: 1 };
  36665. var indices = [];
  36666. var positions = [];
  36667. var normals = [];
  36668. var uvs = [];
  36669. var row, col, tileRow, tileCol;
  36670. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  36671. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  36672. precision.w = (precision.w < 1) ? 1 : precision.w;
  36673. precision.h = (precision.h < 1) ? 1 : precision.h;
  36674. var tileSize = {
  36675. 'w': (xmax - xmin) / subdivisions.w,
  36676. 'h': (zmax - zmin) / subdivisions.h
  36677. };
  36678. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  36679. // Indices
  36680. var base = positions.length / 3;
  36681. var rowLength = precision.w + 1;
  36682. for (row = 0; row < precision.h; row++) {
  36683. for (col = 0; col < precision.w; col++) {
  36684. var square = [
  36685. base + col + row * rowLength,
  36686. base + (col + 1) + row * rowLength,
  36687. base + (col + 1) + (row + 1) * rowLength,
  36688. base + col + (row + 1) * rowLength
  36689. ];
  36690. indices.push(square[1]);
  36691. indices.push(square[2]);
  36692. indices.push(square[3]);
  36693. indices.push(square[0]);
  36694. indices.push(square[1]);
  36695. indices.push(square[3]);
  36696. }
  36697. }
  36698. // Position, normals and uvs
  36699. var position = BABYLON.Vector3.Zero();
  36700. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36701. for (row = 0; row <= precision.h; row++) {
  36702. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  36703. for (col = 0; col <= precision.w; col++) {
  36704. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  36705. position.y = 0;
  36706. positions.push(position.x, position.y, position.z);
  36707. normals.push(normal.x, normal.y, normal.z);
  36708. uvs.push(col / precision.w, row / precision.h);
  36709. }
  36710. }
  36711. }
  36712. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  36713. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  36714. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  36715. }
  36716. }
  36717. // Result
  36718. var vertexData = new VertexData();
  36719. vertexData.indices = indices;
  36720. vertexData.positions = positions;
  36721. vertexData.normals = normals;
  36722. vertexData.uvs = uvs;
  36723. return vertexData;
  36724. };
  36725. /**
  36726. * Creates the VertexData of the Ground designed from a heightmap.
  36727. */
  36728. VertexData.CreateGroundFromHeightMap = function (options) {
  36729. var indices = [];
  36730. var positions = [];
  36731. var normals = [];
  36732. var uvs = [];
  36733. var row, col;
  36734. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  36735. // Vertices
  36736. for (row = 0; row <= options.subdivisions; row++) {
  36737. for (col = 0; col <= options.subdivisions; col++) {
  36738. 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));
  36739. // Compute height
  36740. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  36741. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  36742. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  36743. var r = options.buffer[pos] / 255.0;
  36744. var g = options.buffer[pos + 1] / 255.0;
  36745. var b = options.buffer[pos + 2] / 255.0;
  36746. var gradient = r * filter.r + g * filter.g + b * filter.b;
  36747. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  36748. // Add vertex
  36749. positions.push(position.x, position.y, position.z);
  36750. normals.push(0, 0, 0);
  36751. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  36752. }
  36753. }
  36754. // Indices
  36755. for (row = 0; row < options.subdivisions; row++) {
  36756. for (col = 0; col < options.subdivisions; col++) {
  36757. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36758. indices.push(col + 1 + row * (options.subdivisions + 1));
  36759. indices.push(col + row * (options.subdivisions + 1));
  36760. indices.push(col + (row + 1) * (options.subdivisions + 1));
  36761. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36762. indices.push(col + row * (options.subdivisions + 1));
  36763. }
  36764. }
  36765. // Normals
  36766. VertexData.ComputeNormals(positions, indices, normals);
  36767. // Result
  36768. var vertexData = new VertexData();
  36769. vertexData.indices = indices;
  36770. vertexData.positions = positions;
  36771. vertexData.normals = normals;
  36772. vertexData.uvs = uvs;
  36773. return vertexData;
  36774. };
  36775. /**
  36776. * Creates the VertexData of the Plane.
  36777. */
  36778. VertexData.CreatePlane = function (options) {
  36779. var indices = [];
  36780. var positions = [];
  36781. var normals = [];
  36782. var uvs = [];
  36783. var width = options.width || options.size || 1;
  36784. var height = options.height || options.size || 1;
  36785. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36786. // Vertices
  36787. var halfWidth = width / 2.0;
  36788. var halfHeight = height / 2.0;
  36789. positions.push(-halfWidth, -halfHeight, 0);
  36790. normals.push(0, 0, -1.0);
  36791. uvs.push(0.0, 0.0);
  36792. positions.push(halfWidth, -halfHeight, 0);
  36793. normals.push(0, 0, -1.0);
  36794. uvs.push(1.0, 0.0);
  36795. positions.push(halfWidth, halfHeight, 0);
  36796. normals.push(0, 0, -1.0);
  36797. uvs.push(1.0, 1.0);
  36798. positions.push(-halfWidth, halfHeight, 0);
  36799. normals.push(0, 0, -1.0);
  36800. uvs.push(0.0, 1.0);
  36801. // Indices
  36802. indices.push(0);
  36803. indices.push(1);
  36804. indices.push(2);
  36805. indices.push(0);
  36806. indices.push(2);
  36807. indices.push(3);
  36808. // Sides
  36809. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36810. // Result
  36811. var vertexData = new VertexData();
  36812. vertexData.indices = indices;
  36813. vertexData.positions = positions;
  36814. vertexData.normals = normals;
  36815. vertexData.uvs = uvs;
  36816. return vertexData;
  36817. };
  36818. /**
  36819. * Creates the VertexData of the Disc or regular Polygon.
  36820. */
  36821. VertexData.CreateDisc = function (options) {
  36822. var positions = [];
  36823. var indices = [];
  36824. var normals = [];
  36825. var uvs = [];
  36826. var radius = options.radius || 0.5;
  36827. var tessellation = options.tessellation || 64;
  36828. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36829. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36830. // positions and uvs
  36831. positions.push(0, 0, 0); // disc center first
  36832. uvs.push(0.5, 0.5);
  36833. var theta = Math.PI * 2 * arc;
  36834. var step = theta / tessellation;
  36835. for (var a = 0; a < theta; a += step) {
  36836. var x = Math.cos(a);
  36837. var y = Math.sin(a);
  36838. var u = (x + 1) / 2;
  36839. var v = (1 - y) / 2;
  36840. positions.push(radius * x, radius * y, 0);
  36841. uvs.push(u, v);
  36842. }
  36843. if (arc === 1) {
  36844. positions.push(positions[3], positions[4], positions[5]); // close the circle
  36845. uvs.push(uvs[2], uvs[3]);
  36846. }
  36847. //indices
  36848. var vertexNb = positions.length / 3;
  36849. for (var i = 1; i < vertexNb - 1; i++) {
  36850. indices.push(i + 1, 0, i);
  36851. }
  36852. // result
  36853. VertexData.ComputeNormals(positions, indices, normals);
  36854. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36855. var vertexData = new VertexData();
  36856. vertexData.indices = indices;
  36857. vertexData.positions = positions;
  36858. vertexData.normals = normals;
  36859. vertexData.uvs = uvs;
  36860. return vertexData;
  36861. };
  36862. /**
  36863. * Creates the VertexData of the IcoSphere.
  36864. */
  36865. VertexData.CreateIcoSphere = function (options) {
  36866. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36867. var radius = options.radius || 1;
  36868. var flat = (options.flat === undefined) ? true : options.flat;
  36869. var subdivisions = options.subdivisions || 4;
  36870. var radiusX = options.radiusX || radius;
  36871. var radiusY = options.radiusY || radius;
  36872. var radiusZ = options.radiusZ || radius;
  36873. var t = (1 + Math.sqrt(5)) / 2;
  36874. // 12 vertex x,y,z
  36875. var ico_vertices = [
  36876. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  36877. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  36878. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  36879. ];
  36880. // index of 3 vertex makes a face of icopshere
  36881. var ico_indices = [
  36882. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  36883. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  36884. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  36885. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  36886. ];
  36887. // vertex for uv have aliased position, not for UV
  36888. var vertices_unalias_id = [
  36889. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  36890. // vertex alias
  36891. 0,
  36892. 2,
  36893. 3,
  36894. 3,
  36895. 3,
  36896. 4,
  36897. 7,
  36898. 8,
  36899. 9,
  36900. 9,
  36901. 10,
  36902. 11 // 23: B + 12
  36903. ];
  36904. // uv as integer step (not pixels !)
  36905. var ico_vertexuv = [
  36906. 5, 1, 3, 1, 6, 4, 0, 0,
  36907. 5, 3, 4, 2, 2, 2, 4, 0,
  36908. 2, 0, 1, 1, 6, 0, 6, 2,
  36909. // vertex alias (for same vertex on different faces)
  36910. 0, 4,
  36911. 3, 3,
  36912. 4, 4,
  36913. 3, 1,
  36914. 4, 2,
  36915. 4, 4,
  36916. 0, 2,
  36917. 1, 1,
  36918. 2, 2,
  36919. 3, 3,
  36920. 1, 3,
  36921. 2, 4 // 23: B + 12
  36922. ];
  36923. // Vertices[0, 1, ...9, A, B] : position on UV plane
  36924. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  36925. // First island of uv mapping
  36926. // v = 4h 3+ 2
  36927. // v = 3h 9+ 4
  36928. // v = 2h 9+ 5 B
  36929. // v = 1h 9 1 0
  36930. // v = 0h 3 8 7 A
  36931. // u = 0 1 2 3 4 5 6 *a
  36932. // Second island of uv mapping
  36933. // v = 4h 0+ B+ 4+
  36934. // v = 3h A+ 2+
  36935. // v = 2h 7+ 6 3+
  36936. // v = 1h 8+ 3+
  36937. // v = 0h
  36938. // u = 0 1 2 3 4 5 6 *a
  36939. // Face layout on texture UV mapping
  36940. // ============
  36941. // \ 4 /\ 16 / ======
  36942. // \ / \ / /\ 11 /
  36943. // \/ 7 \/ / \ /
  36944. // ======= / 10 \/
  36945. // /\ 17 /\ =======
  36946. // / \ / \ \ 15 /\
  36947. // / 8 \/ 12 \ \ / \
  36948. // ============ \/ 6 \
  36949. // \ 18 /\ ============
  36950. // \ / \ \ 5 /\ 0 /
  36951. // \/ 13 \ \ / \ /
  36952. // ======= \/ 1 \/
  36953. // =============
  36954. // /\ 19 /\ 2 /\
  36955. // / \ / \ / \
  36956. // / 14 \/ 9 \/ 3 \
  36957. // ===================
  36958. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  36959. var ustep = 138 / 1024;
  36960. var vstep = 239 / 1024;
  36961. var uoffset = 60 / 1024;
  36962. var voffset = 26 / 1024;
  36963. // Second island should have margin, not to touch the first island
  36964. // avoid any borderline artefact in pixel rounding
  36965. var island_u_offset = -40 / 1024;
  36966. var island_v_offset = +20 / 1024;
  36967. // face is either island 0 or 1 :
  36968. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  36969. var island = [
  36970. 0, 0, 0, 0, 1,
  36971. 0, 0, 1, 1, 0,
  36972. 0, 0, 1, 1, 0,
  36973. 0, 1, 1, 1, 0 // 15 - 19
  36974. ];
  36975. var indices = [];
  36976. var positions = [];
  36977. var normals = [];
  36978. var uvs = [];
  36979. var current_indice = 0;
  36980. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  36981. var face_vertex_pos = new Array(3);
  36982. var face_vertex_uv = new Array(3);
  36983. var v012;
  36984. for (v012 = 0; v012 < 3; v012++) {
  36985. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  36986. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  36987. }
  36988. // create all with normals
  36989. for (var face = 0; face < 20; face++) {
  36990. // 3 vertex per face
  36991. for (v012 = 0; v012 < 3; v012++) {
  36992. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  36993. var v_id = ico_indices[3 * face + v012];
  36994. // vertex have 3D position (x,y,z)
  36995. 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]);
  36996. // Normalize to get normal, then scale to radius
  36997. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  36998. // uv Coordinates from vertex ID
  36999. 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);
  37000. }
  37001. // Subdivide the face (interpolate pos, norm, uv)
  37002. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37003. // - norm is linear interpolation of vertex corner normal
  37004. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37005. // - uv is linear interpolation
  37006. //
  37007. // Topology is as below for sub-divide by 2
  37008. // vertex shown as v0,v1,v2
  37009. // interp index is i1 to progress in range [v0,v1[
  37010. // interp index is i2 to progress in range [v0,v2[
  37011. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37012. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37013. //
  37014. //
  37015. // i2 v2
  37016. // ^ ^
  37017. // / / \
  37018. // / / \
  37019. // / / \
  37020. // / / (0,1) \
  37021. // / #---------\
  37022. // / / \ (0,0)'/ \
  37023. // / / \ / \
  37024. // / / \ / \
  37025. // / / (0,0) \ / (1,0) \
  37026. // / #---------#---------\
  37027. // v0 v1
  37028. //
  37029. // --------------------> i1
  37030. //
  37031. // interp of (i1,i2):
  37032. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37033. // along i1 : lerp(x0,x1, i1/(S-i2))
  37034. //
  37035. // centroid of triangle is needed to get help normal computation
  37036. // (c1,c2) are used for centroid location
  37037. var interp_vertex = function (i1, i2, c1, c2) {
  37038. // vertex is interpolated from
  37039. // - face_vertex_pos[0..2]
  37040. // - face_vertex_uv[0..2]
  37041. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37042. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37043. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37044. pos_interp.normalize();
  37045. var vertex_normal;
  37046. if (flat) {
  37047. // in flat mode, recalculate normal as face centroid normal
  37048. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37049. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37050. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37051. }
  37052. else {
  37053. // in smooth mode, recalculate normal from each single vertex position
  37054. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37055. }
  37056. // Vertex normal need correction due to X,Y,Z radius scaling
  37057. vertex_normal.x /= radiusX;
  37058. vertex_normal.y /= radiusY;
  37059. vertex_normal.z /= radiusZ;
  37060. vertex_normal.normalize();
  37061. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37062. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37063. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37064. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37065. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37066. uvs.push(uv_interp.x, uv_interp.y);
  37067. // push each vertex has member of a face
  37068. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37069. indices.push(current_indice);
  37070. current_indice++;
  37071. };
  37072. for (var i2 = 0; i2 < subdivisions; i2++) {
  37073. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37074. // face : (i1,i2) for /\ :
  37075. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37076. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37077. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37078. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37079. if (i1 + i2 + 1 < subdivisions) {
  37080. // face : (i1,i2)' for \/ :
  37081. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37082. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37083. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37084. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37085. }
  37086. }
  37087. }
  37088. }
  37089. // Sides
  37090. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37091. // Result
  37092. var vertexData = new VertexData();
  37093. vertexData.indices = indices;
  37094. vertexData.positions = positions;
  37095. vertexData.normals = normals;
  37096. vertexData.uvs = uvs;
  37097. return vertexData;
  37098. };
  37099. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37100. /**
  37101. * Creates the VertexData of the Polyhedron.
  37102. */
  37103. VertexData.CreatePolyhedron = function (options) {
  37104. // provided polyhedron types :
  37105. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37106. // 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)
  37107. var polyhedra = [];
  37108. 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]] };
  37109. 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]] };
  37110. polyhedra[2] = {
  37111. 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]],
  37112. 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]]
  37113. };
  37114. polyhedra[3] = {
  37115. 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]],
  37116. 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]]
  37117. };
  37118. polyhedra[4] = {
  37119. 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]],
  37120. 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]]
  37121. };
  37122. 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]] };
  37123. 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]] };
  37124. 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]] };
  37125. 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]] };
  37126. 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]] };
  37127. 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]] };
  37128. 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]] };
  37129. 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]] };
  37130. 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]] };
  37131. polyhedra[14] = {
  37132. 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]],
  37133. 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]]
  37134. };
  37135. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37136. var size = options.size;
  37137. var sizeX = options.sizeX || size || 1;
  37138. var sizeY = options.sizeY || size || 1;
  37139. var sizeZ = options.sizeZ || size || 1;
  37140. var data = options.custom || polyhedra[type];
  37141. var nbfaces = data.face.length;
  37142. var faceUV = options.faceUV || new Array(nbfaces);
  37143. var faceColors = options.faceColors;
  37144. var flat = (options.flat === undefined) ? true : options.flat;
  37145. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37146. var positions = [];
  37147. var indices = [];
  37148. var normals = [];
  37149. var uvs = [];
  37150. var colors = [];
  37151. var index = 0;
  37152. var faceIdx = 0; // face cursor in the array "indexes"
  37153. var indexes = [];
  37154. var i = 0;
  37155. var f = 0;
  37156. var u, v, ang, x, y, tmp;
  37157. // default face colors and UV if undefined
  37158. if (flat) {
  37159. for (f = 0; f < nbfaces; f++) {
  37160. if (faceColors && faceColors[f] === undefined) {
  37161. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37162. }
  37163. if (faceUV && faceUV[f] === undefined) {
  37164. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37165. }
  37166. }
  37167. }
  37168. if (!flat) {
  37169. for (i = 0; i < data.vertex.length; i++) {
  37170. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37171. uvs.push(0, 0);
  37172. }
  37173. for (f = 0; f < nbfaces; f++) {
  37174. for (i = 0; i < data.face[f].length - 2; i++) {
  37175. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37176. }
  37177. }
  37178. }
  37179. else {
  37180. for (f = 0; f < nbfaces; f++) {
  37181. var fl = data.face[f].length; // number of vertices of the current face
  37182. ang = 2 * Math.PI / fl;
  37183. x = 0.5 * Math.tan(ang / 2);
  37184. y = 0.5;
  37185. // positions, uvs, colors
  37186. for (i = 0; i < fl; i++) {
  37187. // positions
  37188. 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);
  37189. indexes.push(index);
  37190. index++;
  37191. // uvs
  37192. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37193. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37194. uvs.push(u, v);
  37195. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37196. y = x * Math.sin(ang) + y * Math.cos(ang);
  37197. x = tmp;
  37198. // colors
  37199. if (faceColors) {
  37200. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37201. }
  37202. }
  37203. // indices from indexes
  37204. for (i = 0; i < fl - 2; i++) {
  37205. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37206. }
  37207. faceIdx += fl;
  37208. }
  37209. }
  37210. VertexData.ComputeNormals(positions, indices, normals);
  37211. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37212. var vertexData = new VertexData();
  37213. vertexData.positions = positions;
  37214. vertexData.indices = indices;
  37215. vertexData.normals = normals;
  37216. vertexData.uvs = uvs;
  37217. if (faceColors && flat) {
  37218. vertexData.colors = colors;
  37219. }
  37220. return vertexData;
  37221. };
  37222. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37223. /**
  37224. * Creates the VertexData of the Torus Knot.
  37225. */
  37226. VertexData.CreateTorusKnot = function (options) {
  37227. var indices = [];
  37228. var positions = [];
  37229. var normals = [];
  37230. var uvs = [];
  37231. var radius = options.radius || 2;
  37232. var tube = options.tube || 0.5;
  37233. var radialSegments = options.radialSegments || 32;
  37234. var tubularSegments = options.tubularSegments || 32;
  37235. var p = options.p || 2;
  37236. var q = options.q || 3;
  37237. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37238. // Helper
  37239. var getPos = function (angle) {
  37240. var cu = Math.cos(angle);
  37241. var su = Math.sin(angle);
  37242. var quOverP = q / p * angle;
  37243. var cs = Math.cos(quOverP);
  37244. var tx = radius * (2 + cs) * 0.5 * cu;
  37245. var ty = radius * (2 + cs) * su * 0.5;
  37246. var tz = radius * Math.sin(quOverP) * 0.5;
  37247. return new BABYLON.Vector3(tx, ty, tz);
  37248. };
  37249. // Vertices
  37250. var i;
  37251. var j;
  37252. for (i = 0; i <= radialSegments; i++) {
  37253. var modI = i % radialSegments;
  37254. var u = modI / radialSegments * 2 * p * Math.PI;
  37255. var p1 = getPos(u);
  37256. var p2 = getPos(u + 0.01);
  37257. var tang = p2.subtract(p1);
  37258. var n = p2.add(p1);
  37259. var bitan = BABYLON.Vector3.Cross(tang, n);
  37260. n = BABYLON.Vector3.Cross(bitan, tang);
  37261. bitan.normalize();
  37262. n.normalize();
  37263. for (j = 0; j < tubularSegments; j++) {
  37264. var modJ = j % tubularSegments;
  37265. var v = modJ / tubularSegments * 2 * Math.PI;
  37266. var cx = -tube * Math.cos(v);
  37267. var cy = tube * Math.sin(v);
  37268. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37269. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37270. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37271. uvs.push(i / radialSegments);
  37272. uvs.push(j / tubularSegments);
  37273. }
  37274. }
  37275. for (i = 0; i < radialSegments; i++) {
  37276. for (j = 0; j < tubularSegments; j++) {
  37277. var jNext = (j + 1) % tubularSegments;
  37278. var a = i * tubularSegments + j;
  37279. var b = (i + 1) * tubularSegments + j;
  37280. var c = (i + 1) * tubularSegments + jNext;
  37281. var d = i * tubularSegments + jNext;
  37282. indices.push(d);
  37283. indices.push(b);
  37284. indices.push(a);
  37285. indices.push(d);
  37286. indices.push(c);
  37287. indices.push(b);
  37288. }
  37289. }
  37290. // Normals
  37291. VertexData.ComputeNormals(positions, indices, normals);
  37292. // Sides
  37293. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37294. // Result
  37295. var vertexData = new VertexData();
  37296. vertexData.indices = indices;
  37297. vertexData.positions = positions;
  37298. vertexData.normals = normals;
  37299. vertexData.uvs = uvs;
  37300. return vertexData;
  37301. };
  37302. // Tools
  37303. /**
  37304. * @param {any} - positions (number[] or Float32Array)
  37305. * @param {any} - indices (number[] or Uint16Array)
  37306. * @param {any} - normals (number[] or Float32Array)
  37307. * options (optional) :
  37308. * facetPositions : optional array of facet positions (vector3)
  37309. * facetNormals : optional array of facet normals (vector3)
  37310. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37311. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37312. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37313. * bbSize : optional bounding box size data, required for facetPartitioning computation
  37314. * bInfo : optional bounding info, required for facetPartitioning computation
  37315. */
  37316. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37317. // temporary scalar variables
  37318. var index = 0; // facet index
  37319. var p1p2x = 0.0; // p1p2 vector x coordinate
  37320. var p1p2y = 0.0; // p1p2 vector y coordinate
  37321. var p1p2z = 0.0; // p1p2 vector z coordinate
  37322. var p3p2x = 0.0; // p3p2 vector x coordinate
  37323. var p3p2y = 0.0; // p3p2 vector y coordinate
  37324. var p3p2z = 0.0; // p3p2 vector z coordinate
  37325. var faceNormalx = 0.0; // facet normal x coordinate
  37326. var faceNormaly = 0.0; // facet normal y coordinate
  37327. var faceNormalz = 0.0; // facet normal z coordinate
  37328. var length = 0.0; // facet normal length before normalization
  37329. var v1x = 0; // vector1 x index in the positions array
  37330. var v1y = 0; // vector1 y index in the positions array
  37331. var v1z = 0; // vector1 z index in the positions array
  37332. var v2x = 0; // vector2 x index in the positions array
  37333. var v2y = 0; // vector2 y index in the positions array
  37334. var v2z = 0; // vector2 z index in the positions array
  37335. var v3x = 0; // vector3 x index in the positions array
  37336. var v3y = 0; // vector3 y index in the positions array
  37337. var v3z = 0; // vector3 z index in the positions array
  37338. var computeFacetNormals = false;
  37339. var computeFacetPositions = false;
  37340. var computeFacetPartitioning = false;
  37341. if (options) {
  37342. computeFacetNormals = (options.facetNormals) ? true : false;
  37343. computeFacetPositions = (options.facetPositions) ? true : false;
  37344. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37345. }
  37346. // facetPartitioning reinit if needed
  37347. if (computeFacetPartitioning) {
  37348. var ox = 0; // X partitioning index for facet position
  37349. var oy = 0; // Y partinioning index for facet position
  37350. var oz = 0; // Z partinioning index for facet position
  37351. var b1x = 0; // X partitioning index for facet v1 vertex
  37352. var b1y = 0; // Y partitioning index for facet v1 vertex
  37353. var b1z = 0; // z partitioning index for facet v1 vertex
  37354. var b2x = 0; // X partitioning index for facet v2 vertex
  37355. var b2y = 0; // Y partitioning index for facet v2 vertex
  37356. var b2z = 0; // Z partitioning index for facet v2 vertex
  37357. var b3x = 0; // X partitioning index for facet v3 vertex
  37358. var b3y = 0; // Y partitioning index for facet v3 vertex
  37359. var b3z = 0; // Z partitioning index for facet v3 vertex
  37360. var block_idx_o = 0; // facet barycenter block index
  37361. var block_idx_v1 = 0; // v1 vertex block index
  37362. var block_idx_v2 = 0; // v2 vertex block index
  37363. var block_idx_v3 = 0; // v3 vertex block index
  37364. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  37365. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  37366. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  37367. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  37368. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  37369. var subSq = options.subDiv.max * options.subDiv.max;
  37370. options.facetPartitioning.length = 0;
  37371. }
  37372. // reset the normals
  37373. for (index = 0; index < positions.length; index++) {
  37374. normals[index] = 0.0;
  37375. }
  37376. // Loop : 1 indice triplet = 1 facet
  37377. var nbFaces = indices.length / 3;
  37378. for (index = 0; index < nbFaces; index++) {
  37379. // get the indexes of the coordinates of each vertex of the facet
  37380. v1x = indices[index * 3] * 3;
  37381. v1y = v1x + 1;
  37382. v1z = v1x + 2;
  37383. v2x = indices[index * 3 + 1] * 3;
  37384. v2y = v2x + 1;
  37385. v2z = v2x + 2;
  37386. v3x = indices[index * 3 + 2] * 3;
  37387. v3y = v3x + 1;
  37388. v3z = v3x + 2;
  37389. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  37390. p1p2y = positions[v1y] - positions[v2y];
  37391. p1p2z = positions[v1z] - positions[v2z];
  37392. p3p2x = positions[v3x] - positions[v2x];
  37393. p3p2y = positions[v3y] - positions[v2y];
  37394. p3p2z = positions[v3z] - positions[v2z];
  37395. // compute the face normal with the cross product
  37396. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  37397. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  37398. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  37399. // normalize this normal and store it in the array facetData
  37400. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37401. length = (length === 0) ? 1.0 : length;
  37402. faceNormalx /= length;
  37403. faceNormaly /= length;
  37404. faceNormalz /= length;
  37405. if (computeFacetNormals) {
  37406. options.facetNormals[index].x = faceNormalx;
  37407. options.facetNormals[index].y = faceNormaly;
  37408. options.facetNormals[index].z = faceNormalz;
  37409. }
  37410. if (computeFacetPositions) {
  37411. // compute and the facet barycenter coordinates in the array facetPositions
  37412. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  37413. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  37414. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  37415. }
  37416. if (computeFacetPartitioning) {
  37417. // store the facet indexes in arrays in the main facetPartitioning array :
  37418. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  37419. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  37420. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  37421. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  37422. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  37423. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  37424. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  37425. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  37426. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  37427. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  37428. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  37429. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  37430. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  37431. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  37432. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  37433. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  37434. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  37435. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  37436. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  37437. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  37438. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  37439. // push each facet index in each block containing the vertex
  37440. options.facetPartitioning[block_idx_v1].push(index);
  37441. if (block_idx_v2 != block_idx_v1) {
  37442. options.facetPartitioning[block_idx_v2].push(index);
  37443. }
  37444. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  37445. options.facetPartitioning[block_idx_v3].push(index);
  37446. }
  37447. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  37448. options.facetPartitioning[block_idx_o].push(index);
  37449. }
  37450. }
  37451. // compute the normals anyway
  37452. normals[v1x] += faceNormalx; // accumulate all the normals per face
  37453. normals[v1y] += faceNormaly;
  37454. normals[v1z] += faceNormalz;
  37455. normals[v2x] += faceNormalx;
  37456. normals[v2y] += faceNormaly;
  37457. normals[v2z] += faceNormalz;
  37458. normals[v3x] += faceNormalx;
  37459. normals[v3y] += faceNormaly;
  37460. normals[v3z] += faceNormalz;
  37461. }
  37462. // last normalization of each normal
  37463. for (index = 0; index < normals.length / 3; index++) {
  37464. faceNormalx = normals[index * 3];
  37465. faceNormaly = normals[index * 3 + 1];
  37466. faceNormalz = normals[index * 3 + 2];
  37467. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37468. length = (length === 0) ? 1.0 : length;
  37469. faceNormalx /= length;
  37470. faceNormaly /= length;
  37471. faceNormalz /= length;
  37472. normals[index * 3] = faceNormalx;
  37473. normals[index * 3 + 1] = faceNormaly;
  37474. normals[index * 3 + 2] = faceNormalz;
  37475. }
  37476. };
  37477. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  37478. var li = indices.length;
  37479. var ln = normals.length;
  37480. var i;
  37481. var n;
  37482. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37483. switch (sideOrientation) {
  37484. case BABYLON.Mesh.FRONTSIDE:
  37485. // nothing changed
  37486. break;
  37487. case BABYLON.Mesh.BACKSIDE:
  37488. var tmp;
  37489. // indices
  37490. for (i = 0; i < li; i += 3) {
  37491. tmp = indices[i];
  37492. indices[i] = indices[i + 2];
  37493. indices[i + 2] = tmp;
  37494. }
  37495. // normals
  37496. for (n = 0; n < ln; n++) {
  37497. normals[n] = -normals[n];
  37498. }
  37499. break;
  37500. case BABYLON.Mesh.DOUBLESIDE:
  37501. // positions
  37502. var lp = positions.length;
  37503. var l = lp / 3;
  37504. for (var p = 0; p < lp; p++) {
  37505. positions[lp + p] = positions[p];
  37506. }
  37507. // indices
  37508. for (i = 0; i < li; i += 3) {
  37509. indices[i + li] = indices[i + 2] + l;
  37510. indices[i + 1 + li] = indices[i + 1] + l;
  37511. indices[i + 2 + li] = indices[i] + l;
  37512. }
  37513. // normals
  37514. for (n = 0; n < ln; n++) {
  37515. normals[ln + n] = -normals[n];
  37516. }
  37517. // uvs
  37518. var lu = uvs.length;
  37519. for (var u = 0; u < lu; u++) {
  37520. uvs[u + lu] = uvs[u];
  37521. }
  37522. break;
  37523. }
  37524. };
  37525. /**
  37526. * Creates a new VertexData from the imported parameters.
  37527. */
  37528. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  37529. var vertexData = new VertexData();
  37530. // positions
  37531. var positions = parsedVertexData.positions;
  37532. if (positions) {
  37533. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  37534. }
  37535. // normals
  37536. var normals = parsedVertexData.normals;
  37537. if (normals) {
  37538. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  37539. }
  37540. // uvs
  37541. var uvs = parsedVertexData.uvs;
  37542. if (uvs) {
  37543. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  37544. }
  37545. // uv2s
  37546. var uv2s = parsedVertexData.uv2s;
  37547. if (uv2s) {
  37548. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  37549. }
  37550. // uv3s
  37551. var uv3s = parsedVertexData.uv3s;
  37552. if (uv3s) {
  37553. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  37554. }
  37555. // uv4s
  37556. var uv4s = parsedVertexData.uv4s;
  37557. if (uv4s) {
  37558. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  37559. }
  37560. // uv5s
  37561. var uv5s = parsedVertexData.uv5s;
  37562. if (uv5s) {
  37563. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  37564. }
  37565. // uv6s
  37566. var uv6s = parsedVertexData.uv6s;
  37567. if (uv6s) {
  37568. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  37569. }
  37570. // colors
  37571. var colors = parsedVertexData.colors;
  37572. if (colors) {
  37573. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  37574. }
  37575. // matricesIndices
  37576. var matricesIndices = parsedVertexData.matricesIndices;
  37577. if (matricesIndices) {
  37578. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  37579. }
  37580. // matricesWeights
  37581. var matricesWeights = parsedVertexData.matricesWeights;
  37582. if (matricesWeights) {
  37583. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  37584. }
  37585. // indices
  37586. var indices = parsedVertexData.indices;
  37587. if (indices) {
  37588. vertexData.indices = indices;
  37589. }
  37590. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  37591. };
  37592. return VertexData;
  37593. }());
  37594. BABYLON.VertexData = VertexData;
  37595. })(BABYLON || (BABYLON = {}));
  37596. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  37597. var BABYLON;
  37598. (function (BABYLON) {
  37599. var Tags = (function () {
  37600. function Tags() {
  37601. }
  37602. Tags.EnableFor = function (obj) {
  37603. obj._tags = obj._tags || {};
  37604. obj.hasTags = function () {
  37605. return Tags.HasTags(obj);
  37606. };
  37607. obj.addTags = function (tagsString) {
  37608. return Tags.AddTagsTo(obj, tagsString);
  37609. };
  37610. obj.removeTags = function (tagsString) {
  37611. return Tags.RemoveTagsFrom(obj, tagsString);
  37612. };
  37613. obj.matchesTagsQuery = function (tagsQuery) {
  37614. return Tags.MatchesQuery(obj, tagsQuery);
  37615. };
  37616. };
  37617. Tags.DisableFor = function (obj) {
  37618. delete obj._tags;
  37619. delete obj.hasTags;
  37620. delete obj.addTags;
  37621. delete obj.removeTags;
  37622. delete obj.matchesTagsQuery;
  37623. };
  37624. Tags.HasTags = function (obj) {
  37625. if (!obj._tags) {
  37626. return false;
  37627. }
  37628. return !BABYLON.Tools.IsEmpty(obj._tags);
  37629. };
  37630. Tags.GetTags = function (obj, asString) {
  37631. if (asString === void 0) { asString = true; }
  37632. if (!obj._tags) {
  37633. return null;
  37634. }
  37635. if (asString) {
  37636. var tagsArray = [];
  37637. for (var tag in obj._tags) {
  37638. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  37639. tagsArray.push(tag);
  37640. }
  37641. }
  37642. return tagsArray.join(" ");
  37643. }
  37644. else {
  37645. return obj._tags;
  37646. }
  37647. };
  37648. // the tags 'true' and 'false' are reserved and cannot be used as tags
  37649. // a tag cannot start with '||', '&&', and '!'
  37650. // it cannot contain whitespaces
  37651. Tags.AddTagsTo = function (obj, tagsString) {
  37652. if (!tagsString) {
  37653. return;
  37654. }
  37655. if (typeof tagsString !== "string") {
  37656. return;
  37657. }
  37658. var tags = tagsString.split(" ");
  37659. tags.forEach(function (tag, index, array) {
  37660. Tags._AddTagTo(obj, tag);
  37661. });
  37662. };
  37663. Tags._AddTagTo = function (obj, tag) {
  37664. tag = tag.trim();
  37665. if (tag === "" || tag === "true" || tag === "false") {
  37666. return;
  37667. }
  37668. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  37669. return;
  37670. }
  37671. Tags.EnableFor(obj);
  37672. obj._tags[tag] = true;
  37673. };
  37674. Tags.RemoveTagsFrom = function (obj, tagsString) {
  37675. if (!Tags.HasTags(obj)) {
  37676. return;
  37677. }
  37678. var tags = tagsString.split(" ");
  37679. for (var t in tags) {
  37680. Tags._RemoveTagFrom(obj, tags[t]);
  37681. }
  37682. };
  37683. Tags._RemoveTagFrom = function (obj, tag) {
  37684. delete obj._tags[tag];
  37685. };
  37686. Tags.MatchesQuery = function (obj, tagsQuery) {
  37687. if (tagsQuery === undefined) {
  37688. return true;
  37689. }
  37690. if (tagsQuery === "") {
  37691. return Tags.HasTags(obj);
  37692. }
  37693. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  37694. };
  37695. return Tags;
  37696. }());
  37697. BABYLON.Tags = Tags;
  37698. })(BABYLON || (BABYLON = {}));
  37699. //# sourceMappingURL=babylon.tags.js.map
  37700. var BABYLON;
  37701. (function (BABYLON) {
  37702. var Internals;
  37703. (function (Internals) {
  37704. var AndOrNotEvaluator = (function () {
  37705. function AndOrNotEvaluator() {
  37706. }
  37707. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  37708. if (!query.match(/\([^\(\)]*\)/g)) {
  37709. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  37710. }
  37711. else {
  37712. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  37713. // remove parenthesis
  37714. r = r.slice(1, r.length - 1);
  37715. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  37716. });
  37717. }
  37718. if (query === "true") {
  37719. return true;
  37720. }
  37721. if (query === "false") {
  37722. return false;
  37723. }
  37724. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  37725. };
  37726. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  37727. evaluateCallback = evaluateCallback || (function (r) {
  37728. return r === "true" ? true : false;
  37729. });
  37730. var result;
  37731. var or = parenthesisContent.split("||");
  37732. for (var i in or) {
  37733. if (or.hasOwnProperty(i)) {
  37734. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  37735. var and = ori.split("&&");
  37736. if (and.length > 1) {
  37737. for (var j = 0; j < and.length; ++j) {
  37738. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  37739. if (andj !== "true" && andj !== "false") {
  37740. if (andj[0] === "!") {
  37741. result = !evaluateCallback(andj.substring(1));
  37742. }
  37743. else {
  37744. result = evaluateCallback(andj);
  37745. }
  37746. }
  37747. else {
  37748. result = andj === "true" ? true : false;
  37749. }
  37750. if (!result) {
  37751. ori = "false";
  37752. break;
  37753. }
  37754. }
  37755. }
  37756. if (result || ori === "true") {
  37757. result = true;
  37758. break;
  37759. }
  37760. // result equals false (or undefined)
  37761. if (ori !== "true" && ori !== "false") {
  37762. if (ori[0] === "!") {
  37763. result = !evaluateCallback(ori.substring(1));
  37764. }
  37765. else {
  37766. result = evaluateCallback(ori);
  37767. }
  37768. }
  37769. else {
  37770. result = ori === "true" ? true : false;
  37771. }
  37772. }
  37773. }
  37774. // the whole parenthesis scope is replaced by 'true' or 'false'
  37775. return result ? "true" : "false";
  37776. };
  37777. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  37778. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  37779. // remove whitespaces
  37780. r = r.replace(/[\s]/g, function () { return ""; });
  37781. return r.length % 2 ? "!" : "";
  37782. });
  37783. booleanString = booleanString.trim();
  37784. if (booleanString === "!true") {
  37785. booleanString = "false";
  37786. }
  37787. else if (booleanString === "!false") {
  37788. booleanString = "true";
  37789. }
  37790. return booleanString;
  37791. };
  37792. return AndOrNotEvaluator;
  37793. }());
  37794. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  37795. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  37796. })(BABYLON || (BABYLON = {}));
  37797. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  37798. var BABYLON;
  37799. (function (BABYLON) {
  37800. var PostProcessRenderPass = (function () {
  37801. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  37802. this._enabled = true;
  37803. this._refCount = 0;
  37804. this._name = name;
  37805. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  37806. this.setRenderList(renderList);
  37807. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  37808. this._renderTexture.onAfterRenderObservable.add(afterRender);
  37809. this._scene = scene;
  37810. this._renderList = renderList;
  37811. }
  37812. // private
  37813. PostProcessRenderPass.prototype._incRefCount = function () {
  37814. if (this._refCount === 0) {
  37815. this._scene.customRenderTargets.push(this._renderTexture);
  37816. }
  37817. return ++this._refCount;
  37818. };
  37819. PostProcessRenderPass.prototype._decRefCount = function () {
  37820. this._refCount--;
  37821. if (this._refCount <= 0) {
  37822. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  37823. }
  37824. return this._refCount;
  37825. };
  37826. PostProcessRenderPass.prototype._update = function () {
  37827. this.setRenderList(this._renderList);
  37828. };
  37829. // public
  37830. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  37831. this._renderTexture.renderList = renderList;
  37832. };
  37833. PostProcessRenderPass.prototype.getRenderTexture = function () {
  37834. return this._renderTexture;
  37835. };
  37836. return PostProcessRenderPass;
  37837. }());
  37838. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  37839. })(BABYLON || (BABYLON = {}));
  37840. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  37841. var BABYLON;
  37842. (function (BABYLON) {
  37843. var PostProcessRenderEffect = (function () {
  37844. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  37845. this._engine = engine;
  37846. this._name = name;
  37847. this._singleInstance = singleInstance || true;
  37848. this._getPostProcess = getPostProcess;
  37849. this._cameras = [];
  37850. this._indicesForCamera = [];
  37851. this._postProcesses = {};
  37852. this._renderPasses = {};
  37853. this._renderEffectAsPasses = {};
  37854. }
  37855. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  37856. get: function () {
  37857. for (var index in this._postProcesses) {
  37858. if (!this._postProcesses[index].isSupported) {
  37859. return false;
  37860. }
  37861. }
  37862. return true;
  37863. },
  37864. enumerable: true,
  37865. configurable: true
  37866. });
  37867. PostProcessRenderEffect.prototype._update = function () {
  37868. for (var renderPassName in this._renderPasses) {
  37869. this._renderPasses[renderPassName]._update();
  37870. }
  37871. };
  37872. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  37873. this._renderPasses[renderPass._name] = renderPass;
  37874. this._linkParameters();
  37875. };
  37876. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  37877. delete this._renderPasses[renderPass._name];
  37878. this._linkParameters();
  37879. };
  37880. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  37881. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  37882. this._linkParameters();
  37883. };
  37884. PostProcessRenderEffect.prototype.getPass = function (passName) {
  37885. for (var renderPassName in this._renderPasses) {
  37886. if (renderPassName === passName) {
  37887. return this._renderPasses[passName];
  37888. }
  37889. }
  37890. };
  37891. PostProcessRenderEffect.prototype.emptyPasses = function () {
  37892. this._renderPasses = {};
  37893. this._linkParameters();
  37894. };
  37895. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  37896. var cameraKey;
  37897. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  37898. for (var i = 0; i < _cam.length; i++) {
  37899. var camera = _cam[i];
  37900. var cameraName = camera.name;
  37901. if (this._singleInstance) {
  37902. cameraKey = 0;
  37903. }
  37904. else {
  37905. cameraKey = cameraName;
  37906. }
  37907. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  37908. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  37909. if (!this._indicesForCamera[cameraName]) {
  37910. this._indicesForCamera[cameraName] = [];
  37911. }
  37912. this._indicesForCamera[cameraName].push(index);
  37913. if (this._cameras.indexOf(camera) === -1) {
  37914. this._cameras[cameraName] = camera;
  37915. }
  37916. for (var passName in this._renderPasses) {
  37917. this._renderPasses[passName]._incRefCount();
  37918. }
  37919. }
  37920. this._linkParameters();
  37921. };
  37922. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  37923. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  37924. for (var i = 0; i < _cam.length; i++) {
  37925. var camera = _cam[i];
  37926. var cameraName = camera.name;
  37927. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  37928. var index = this._cameras.indexOf(cameraName);
  37929. this._indicesForCamera.splice(index, 1);
  37930. this._cameras.splice(index, 1);
  37931. for (var passName in this._renderPasses) {
  37932. this._renderPasses[passName]._decRefCount();
  37933. }
  37934. }
  37935. };
  37936. PostProcessRenderEffect.prototype._enable = function (cameras) {
  37937. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  37938. for (var i = 0; i < _cam.length; i++) {
  37939. var camera = _cam[i];
  37940. var cameraName = camera.name;
  37941. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  37942. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  37943. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  37944. }
  37945. }
  37946. for (var passName in this._renderPasses) {
  37947. this._renderPasses[passName]._incRefCount();
  37948. }
  37949. }
  37950. };
  37951. PostProcessRenderEffect.prototype._disable = function (cameras) {
  37952. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  37953. for (var i = 0; i < _cam.length; i++) {
  37954. var camera = _cam[i];
  37955. var cameraName = camera.Name;
  37956. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  37957. for (var passName in this._renderPasses) {
  37958. this._renderPasses[passName]._decRefCount();
  37959. }
  37960. }
  37961. };
  37962. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  37963. if (this._singleInstance) {
  37964. return this._postProcesses[0];
  37965. }
  37966. else {
  37967. return this._postProcesses[camera.name];
  37968. }
  37969. };
  37970. PostProcessRenderEffect.prototype._linkParameters = function () {
  37971. var _this = this;
  37972. for (var index in this._postProcesses) {
  37973. if (this.applyParameters) {
  37974. this.applyParameters(this._postProcesses[index]);
  37975. }
  37976. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  37977. _this._linkTextures(effect);
  37978. });
  37979. }
  37980. };
  37981. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  37982. for (var renderPassName in this._renderPasses) {
  37983. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  37984. }
  37985. for (var renderEffectName in this._renderEffectAsPasses) {
  37986. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  37987. }
  37988. };
  37989. return PostProcessRenderEffect;
  37990. }());
  37991. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  37992. })(BABYLON || (BABYLON = {}));
  37993. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  37994. var BABYLON;
  37995. (function (BABYLON) {
  37996. var PostProcessRenderPipeline = (function () {
  37997. function PostProcessRenderPipeline(engine, name) {
  37998. this._engine = engine;
  37999. this._name = name;
  38000. this._renderEffects = {};
  38001. this._renderEffectsForIsolatedPass = {};
  38002. this._cameras = [];
  38003. }
  38004. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  38005. get: function () {
  38006. for (var renderEffectName in this._renderEffects) {
  38007. if (!this._renderEffects[renderEffectName].isSupported) {
  38008. return false;
  38009. }
  38010. }
  38011. return true;
  38012. },
  38013. enumerable: true,
  38014. configurable: true
  38015. });
  38016. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  38017. this._renderEffects[renderEffect._name] = renderEffect;
  38018. };
  38019. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  38020. var renderEffects = this._renderEffects[renderEffectName];
  38021. if (!renderEffects) {
  38022. return;
  38023. }
  38024. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  38025. };
  38026. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  38027. var renderEffects = this._renderEffects[renderEffectName];
  38028. if (!renderEffects) {
  38029. return;
  38030. }
  38031. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  38032. };
  38033. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  38034. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  38035. var indicesToDelete = [];
  38036. var i;
  38037. for (i = 0; i < _cam.length; i++) {
  38038. var camera = _cam[i];
  38039. var cameraName = camera.name;
  38040. if (this._cameras.indexOf(camera) === -1) {
  38041. this._cameras[cameraName] = camera;
  38042. }
  38043. else if (unique) {
  38044. indicesToDelete.push(i);
  38045. }
  38046. }
  38047. for (i = 0; i < indicesToDelete.length; i++) {
  38048. cameras.splice(indicesToDelete[i], 1);
  38049. }
  38050. for (var renderEffectName in this._renderEffects) {
  38051. this._renderEffects[renderEffectName]._attachCameras(_cam);
  38052. }
  38053. };
  38054. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  38055. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  38056. for (var renderEffectName in this._renderEffects) {
  38057. this._renderEffects[renderEffectName]._detachCameras(_cam);
  38058. }
  38059. for (var i = 0; i < _cam.length; i++) {
  38060. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  38061. }
  38062. };
  38063. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  38064. var _this = this;
  38065. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  38066. var pass = null;
  38067. var renderEffectName;
  38068. for (renderEffectName in this._renderEffects) {
  38069. pass = this._renderEffects[renderEffectName].getPass(passName);
  38070. if (pass != null) {
  38071. break;
  38072. }
  38073. }
  38074. if (pass === null) {
  38075. return;
  38076. }
  38077. for (renderEffectName in this._renderEffects) {
  38078. this._renderEffects[renderEffectName]._disable(_cam);
  38079. }
  38080. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  38081. for (var i = 0; i < _cam.length; i++) {
  38082. var camera = _cam[i];
  38083. var cameraName = camera.name;
  38084. 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); });
  38085. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  38086. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  38087. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  38088. }
  38089. };
  38090. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  38091. var _this = this;
  38092. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  38093. for (var i = 0; i < _cam.length; i++) {
  38094. var camera = _cam[i];
  38095. var cameraName = camera.name;
  38096. 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); });
  38097. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  38098. }
  38099. for (var renderEffectName in this._renderEffects) {
  38100. this._renderEffects[renderEffectName]._enable(_cam);
  38101. }
  38102. };
  38103. PostProcessRenderPipeline.prototype._update = function () {
  38104. for (var renderEffectName in this._renderEffects) {
  38105. this._renderEffects[renderEffectName]._update();
  38106. }
  38107. for (var i = 0; i < this._cameras.length; i++) {
  38108. var cameraName = this._cameras[i].name;
  38109. if (this._renderEffectsForIsolatedPass[cameraName]) {
  38110. this._renderEffectsForIsolatedPass[cameraName]._update();
  38111. }
  38112. }
  38113. };
  38114. PostProcessRenderPipeline.prototype.dispose = function () {
  38115. // Must be implemented by children
  38116. };
  38117. return PostProcessRenderPipeline;
  38118. }());
  38119. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  38120. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  38121. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  38122. })(BABYLON || (BABYLON = {}));
  38123. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  38124. var BABYLON;
  38125. (function (BABYLON) {
  38126. var PostProcessRenderPipelineManager = (function () {
  38127. function PostProcessRenderPipelineManager() {
  38128. this._renderPipelines = {};
  38129. }
  38130. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  38131. this._renderPipelines[renderPipeline._name] = renderPipeline;
  38132. };
  38133. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  38134. var renderPipeline = this._renderPipelines[renderPipelineName];
  38135. if (!renderPipeline) {
  38136. return;
  38137. }
  38138. renderPipeline._attachCameras(cameras, unique);
  38139. };
  38140. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  38141. var renderPipeline = this._renderPipelines[renderPipelineName];
  38142. if (!renderPipeline) {
  38143. return;
  38144. }
  38145. renderPipeline._detachCameras(cameras);
  38146. };
  38147. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  38148. var renderPipeline = this._renderPipelines[renderPipelineName];
  38149. if (!renderPipeline) {
  38150. return;
  38151. }
  38152. renderPipeline._enableEffect(renderEffectName, cameras);
  38153. };
  38154. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  38155. var renderPipeline = this._renderPipelines[renderPipelineName];
  38156. if (!renderPipeline) {
  38157. return;
  38158. }
  38159. renderPipeline._disableEffect(renderEffectName, cameras);
  38160. };
  38161. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  38162. var renderPipeline = this._renderPipelines[renderPipelineName];
  38163. if (!renderPipeline) {
  38164. return;
  38165. }
  38166. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  38167. };
  38168. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  38169. var renderPipeline = this._renderPipelines[renderPipelineName];
  38170. if (!renderPipeline) {
  38171. return;
  38172. }
  38173. renderPipeline._disableDisplayOnlyPass(cameras);
  38174. };
  38175. PostProcessRenderPipelineManager.prototype.update = function () {
  38176. for (var renderPipelineName in this._renderPipelines) {
  38177. var pipeline = this._renderPipelines[renderPipelineName];
  38178. if (!pipeline.isSupported) {
  38179. pipeline.dispose();
  38180. delete this._renderPipelines[renderPipelineName];
  38181. }
  38182. else {
  38183. pipeline._update();
  38184. }
  38185. }
  38186. };
  38187. return PostProcessRenderPipelineManager;
  38188. }());
  38189. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  38190. })(BABYLON || (BABYLON = {}));
  38191. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  38192. var BABYLON;
  38193. (function (BABYLON) {
  38194. var BoundingBoxRenderer = (function () {
  38195. function BoundingBoxRenderer(scene) {
  38196. this.frontColor = new BABYLON.Color3(1, 1, 1);
  38197. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  38198. this.showBackLines = true;
  38199. this.renderList = new BABYLON.SmartArray(32);
  38200. this._vertexBuffers = {};
  38201. this._scene = scene;
  38202. }
  38203. BoundingBoxRenderer.prototype._prepareRessources = function () {
  38204. if (this._colorShader) {
  38205. return;
  38206. }
  38207. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  38208. attributes: [BABYLON.VertexBuffer.PositionKind],
  38209. uniforms: ["worldViewProjection", "color"]
  38210. });
  38211. var engine = this._scene.getEngine();
  38212. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  38213. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  38214. 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]);
  38215. };
  38216. BoundingBoxRenderer.prototype.reset = function () {
  38217. this.renderList.reset();
  38218. };
  38219. BoundingBoxRenderer.prototype.render = function () {
  38220. if (this.renderList.length === 0) {
  38221. return;
  38222. }
  38223. this._prepareRessources();
  38224. if (!this._colorShader.isReady()) {
  38225. return;
  38226. }
  38227. var engine = this._scene.getEngine();
  38228. engine.setDepthWrite(false);
  38229. this._colorShader._preBind();
  38230. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  38231. var boundingBox = this.renderList.data[boundingBoxIndex];
  38232. var min = boundingBox.minimum;
  38233. var max = boundingBox.maximum;
  38234. var diff = max.subtract(min);
  38235. var median = min.add(diff.scale(0.5));
  38236. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  38237. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  38238. .multiply(boundingBox.getWorldMatrix());
  38239. // VBOs
  38240. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  38241. if (this.showBackLines) {
  38242. // Back
  38243. engine.setDepthFunctionToGreaterOrEqual();
  38244. this._scene.resetCachedMaterial();
  38245. this._colorShader.setColor4("color", this.backColor.toColor4());
  38246. this._colorShader.bind(worldMatrix);
  38247. // Draw order
  38248. engine.draw(false, 0, 24);
  38249. }
  38250. // Front
  38251. engine.setDepthFunctionToLess();
  38252. this._scene.resetCachedMaterial();
  38253. this._colorShader.setColor4("color", this.frontColor.toColor4());
  38254. this._colorShader.bind(worldMatrix);
  38255. // Draw order
  38256. engine.draw(false, 0, 24);
  38257. }
  38258. this._colorShader.unbind();
  38259. engine.setDepthFunctionToLessOrEqual();
  38260. engine.setDepthWrite(true);
  38261. };
  38262. BoundingBoxRenderer.prototype.dispose = function () {
  38263. if (!this._colorShader) {
  38264. return;
  38265. }
  38266. this._colorShader.dispose();
  38267. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38268. if (buffer) {
  38269. buffer.dispose();
  38270. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  38271. }
  38272. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38273. };
  38274. return BoundingBoxRenderer;
  38275. }());
  38276. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  38277. })(BABYLON || (BABYLON = {}));
  38278. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  38279. var BABYLON;
  38280. (function (BABYLON) {
  38281. var Condition = (function () {
  38282. function Condition(actionManager) {
  38283. this._actionManager = actionManager;
  38284. }
  38285. Condition.prototype.isValid = function () {
  38286. return true;
  38287. };
  38288. Condition.prototype._getProperty = function (propertyPath) {
  38289. return this._actionManager._getProperty(propertyPath);
  38290. };
  38291. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  38292. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38293. };
  38294. Condition.prototype.serialize = function () {
  38295. };
  38296. Condition.prototype._serialize = function (serializedCondition) {
  38297. return {
  38298. type: 2,
  38299. children: [],
  38300. name: serializedCondition.name,
  38301. properties: serializedCondition.properties
  38302. };
  38303. };
  38304. return Condition;
  38305. }());
  38306. BABYLON.Condition = Condition;
  38307. var ValueCondition = (function (_super) {
  38308. __extends(ValueCondition, _super);
  38309. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  38310. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  38311. var _this = _super.call(this, actionManager) || this;
  38312. _this.propertyPath = propertyPath;
  38313. _this.value = value;
  38314. _this.operator = operator;
  38315. _this._target = target;
  38316. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  38317. _this._property = _this._getProperty(_this.propertyPath);
  38318. return _this;
  38319. }
  38320. Object.defineProperty(ValueCondition, "IsEqual", {
  38321. get: function () {
  38322. return ValueCondition._IsEqual;
  38323. },
  38324. enumerable: true,
  38325. configurable: true
  38326. });
  38327. Object.defineProperty(ValueCondition, "IsDifferent", {
  38328. get: function () {
  38329. return ValueCondition._IsDifferent;
  38330. },
  38331. enumerable: true,
  38332. configurable: true
  38333. });
  38334. Object.defineProperty(ValueCondition, "IsGreater", {
  38335. get: function () {
  38336. return ValueCondition._IsGreater;
  38337. },
  38338. enumerable: true,
  38339. configurable: true
  38340. });
  38341. Object.defineProperty(ValueCondition, "IsLesser", {
  38342. get: function () {
  38343. return ValueCondition._IsLesser;
  38344. },
  38345. enumerable: true,
  38346. configurable: true
  38347. });
  38348. // Methods
  38349. ValueCondition.prototype.isValid = function () {
  38350. switch (this.operator) {
  38351. case ValueCondition.IsGreater:
  38352. return this._effectiveTarget[this._property] > this.value;
  38353. case ValueCondition.IsLesser:
  38354. return this._effectiveTarget[this._property] < this.value;
  38355. case ValueCondition.IsEqual:
  38356. case ValueCondition.IsDifferent:
  38357. var check;
  38358. if (this.value.equals) {
  38359. check = this.value.equals(this._effectiveTarget[this._property]);
  38360. }
  38361. else {
  38362. check = this.value === this._effectiveTarget[this._property];
  38363. }
  38364. return this.operator === ValueCondition.IsEqual ? check : !check;
  38365. }
  38366. return false;
  38367. };
  38368. ValueCondition.prototype.serialize = function () {
  38369. return this._serialize({
  38370. name: "ValueCondition",
  38371. properties: [
  38372. BABYLON.Action._GetTargetProperty(this._target),
  38373. { name: "propertyPath", value: this.propertyPath },
  38374. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  38375. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  38376. ]
  38377. });
  38378. };
  38379. ValueCondition.GetOperatorName = function (operator) {
  38380. switch (operator) {
  38381. case ValueCondition._IsEqual: return "IsEqual";
  38382. case ValueCondition._IsDifferent: return "IsDifferent";
  38383. case ValueCondition._IsGreater: return "IsGreater";
  38384. case ValueCondition._IsLesser: return "IsLesser";
  38385. default: return "";
  38386. }
  38387. };
  38388. return ValueCondition;
  38389. }(Condition));
  38390. // Statics
  38391. ValueCondition._IsEqual = 0;
  38392. ValueCondition._IsDifferent = 1;
  38393. ValueCondition._IsGreater = 2;
  38394. ValueCondition._IsLesser = 3;
  38395. BABYLON.ValueCondition = ValueCondition;
  38396. var PredicateCondition = (function (_super) {
  38397. __extends(PredicateCondition, _super);
  38398. function PredicateCondition(actionManager, predicate) {
  38399. var _this = _super.call(this, actionManager) || this;
  38400. _this.predicate = predicate;
  38401. return _this;
  38402. }
  38403. PredicateCondition.prototype.isValid = function () {
  38404. return this.predicate();
  38405. };
  38406. return PredicateCondition;
  38407. }(Condition));
  38408. BABYLON.PredicateCondition = PredicateCondition;
  38409. var StateCondition = (function (_super) {
  38410. __extends(StateCondition, _super);
  38411. function StateCondition(actionManager, target, value) {
  38412. var _this = _super.call(this, actionManager) || this;
  38413. _this.value = value;
  38414. _this._target = target;
  38415. return _this;
  38416. }
  38417. // Methods
  38418. StateCondition.prototype.isValid = function () {
  38419. return this._target.state === this.value;
  38420. };
  38421. StateCondition.prototype.serialize = function () {
  38422. return this._serialize({
  38423. name: "StateCondition",
  38424. properties: [
  38425. BABYLON.Action._GetTargetProperty(this._target),
  38426. { name: "value", value: this.value }
  38427. ]
  38428. });
  38429. };
  38430. return StateCondition;
  38431. }(Condition));
  38432. BABYLON.StateCondition = StateCondition;
  38433. })(BABYLON || (BABYLON = {}));
  38434. //# sourceMappingURL=babylon.condition.js.map
  38435. var BABYLON;
  38436. (function (BABYLON) {
  38437. var Action = (function () {
  38438. function Action(triggerOptions, condition) {
  38439. this.triggerOptions = triggerOptions;
  38440. if (triggerOptions.parameter) {
  38441. this.trigger = triggerOptions.trigger;
  38442. this._triggerParameter = triggerOptions.parameter;
  38443. }
  38444. else {
  38445. this.trigger = triggerOptions;
  38446. }
  38447. this._nextActiveAction = this;
  38448. this._condition = condition;
  38449. }
  38450. // Methods
  38451. Action.prototype._prepare = function () {
  38452. };
  38453. Action.prototype.getTriggerParameter = function () {
  38454. return this._triggerParameter;
  38455. };
  38456. Action.prototype._executeCurrent = function (evt) {
  38457. if (this._nextActiveAction._condition) {
  38458. var condition = this._nextActiveAction._condition;
  38459. var currentRenderId = this._actionManager.getScene().getRenderId();
  38460. // We cache the current evaluation for the current frame
  38461. if (condition._evaluationId === currentRenderId) {
  38462. if (!condition._currentResult) {
  38463. return;
  38464. }
  38465. }
  38466. else {
  38467. condition._evaluationId = currentRenderId;
  38468. if (!condition.isValid()) {
  38469. condition._currentResult = false;
  38470. return;
  38471. }
  38472. condition._currentResult = true;
  38473. }
  38474. }
  38475. this._nextActiveAction.execute(evt);
  38476. this.skipToNextActiveAction();
  38477. };
  38478. Action.prototype.execute = function (evt) {
  38479. };
  38480. Action.prototype.skipToNextActiveAction = function () {
  38481. if (this._nextActiveAction._child) {
  38482. if (!this._nextActiveAction._child._actionManager) {
  38483. this._nextActiveAction._child._actionManager = this._actionManager;
  38484. }
  38485. this._nextActiveAction = this._nextActiveAction._child;
  38486. }
  38487. else {
  38488. this._nextActiveAction = this;
  38489. }
  38490. };
  38491. Action.prototype.then = function (action) {
  38492. this._child = action;
  38493. action._actionManager = this._actionManager;
  38494. action._prepare();
  38495. return action;
  38496. };
  38497. Action.prototype._getProperty = function (propertyPath) {
  38498. return this._actionManager._getProperty(propertyPath);
  38499. };
  38500. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  38501. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38502. };
  38503. Action.prototype.serialize = function (parent) {
  38504. };
  38505. // Called by BABYLON.Action objects in serialize(...). Internal use
  38506. Action.prototype._serialize = function (serializedAction, parent) {
  38507. var serializationObject = {
  38508. type: 1,
  38509. children: [],
  38510. name: serializedAction.name,
  38511. properties: serializedAction.properties || []
  38512. };
  38513. // Serialize child
  38514. if (this._child) {
  38515. this._child.serialize(serializationObject);
  38516. }
  38517. // Check if "this" has a condition
  38518. if (this._condition) {
  38519. var serializedCondition = this._condition.serialize();
  38520. serializedCondition.children.push(serializationObject);
  38521. if (parent) {
  38522. parent.children.push(serializedCondition);
  38523. }
  38524. return serializedCondition;
  38525. }
  38526. if (parent) {
  38527. parent.children.push(serializationObject);
  38528. }
  38529. return serializationObject;
  38530. };
  38531. return Action;
  38532. }());
  38533. Action._SerializeValueAsString = function (value) {
  38534. if (typeof value === "number") {
  38535. return value.toString();
  38536. }
  38537. if (typeof value === "boolean") {
  38538. return value ? "true" : "false";
  38539. }
  38540. if (value instanceof BABYLON.Vector2) {
  38541. return value.x + ", " + value.y;
  38542. }
  38543. if (value instanceof BABYLON.Vector3) {
  38544. return value.x + ", " + value.y + ", " + value.z;
  38545. }
  38546. if (value instanceof BABYLON.Color3) {
  38547. return value.r + ", " + value.g + ", " + value.b;
  38548. }
  38549. if (value instanceof BABYLON.Color4) {
  38550. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  38551. }
  38552. return value; // string
  38553. };
  38554. Action._GetTargetProperty = function (target) {
  38555. return {
  38556. name: "target",
  38557. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  38558. : target instanceof BABYLON.Light ? "LightProperties"
  38559. : target instanceof BABYLON.Camera ? "CameraProperties"
  38560. : "SceneProperties",
  38561. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  38562. };
  38563. };
  38564. BABYLON.Action = Action;
  38565. })(BABYLON || (BABYLON = {}));
  38566. //# sourceMappingURL=babylon.action.js.map
  38567. var BABYLON;
  38568. (function (BABYLON) {
  38569. /**
  38570. * ActionEvent is the event beint sent when an action is triggered.
  38571. */
  38572. var ActionEvent = (function () {
  38573. /**
  38574. * @constructor
  38575. * @param source The mesh or sprite that triggered the action.
  38576. * @param pointerX The X mouse cursor position at the time of the event
  38577. * @param pointerY The Y mouse cursor position at the time of the event
  38578. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  38579. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  38580. */
  38581. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  38582. this.source = source;
  38583. this.pointerX = pointerX;
  38584. this.pointerY = pointerY;
  38585. this.meshUnderPointer = meshUnderPointer;
  38586. this.sourceEvent = sourceEvent;
  38587. this.additionalData = additionalData;
  38588. }
  38589. /**
  38590. * Helper function to auto-create an ActionEvent from a source mesh.
  38591. * @param source The source mesh that triggered the event
  38592. * @param evt {Event} The original (browser) event
  38593. */
  38594. ActionEvent.CreateNew = function (source, evt, additionalData) {
  38595. var scene = source.getScene();
  38596. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38597. };
  38598. /**
  38599. * Helper function to auto-create an ActionEvent from a source mesh.
  38600. * @param source The source sprite that triggered the event
  38601. * @param scene Scene associated with the sprite
  38602. * @param evt {Event} The original (browser) event
  38603. */
  38604. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  38605. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38606. };
  38607. /**
  38608. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  38609. * @param scene the scene where the event occurred
  38610. * @param evt {Event} The original (browser) event
  38611. */
  38612. ActionEvent.CreateNewFromScene = function (scene, evt) {
  38613. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  38614. };
  38615. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  38616. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  38617. };
  38618. return ActionEvent;
  38619. }());
  38620. BABYLON.ActionEvent = ActionEvent;
  38621. /**
  38622. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  38623. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  38624. */
  38625. var ActionManager = (function () {
  38626. function ActionManager(scene) {
  38627. // Members
  38628. this.actions = new Array();
  38629. this.hoverCursor = '';
  38630. this._scene = scene;
  38631. scene._actionManagers.push(this);
  38632. }
  38633. Object.defineProperty(ActionManager, "NothingTrigger", {
  38634. get: function () {
  38635. return ActionManager._NothingTrigger;
  38636. },
  38637. enumerable: true,
  38638. configurable: true
  38639. });
  38640. Object.defineProperty(ActionManager, "OnPickTrigger", {
  38641. get: function () {
  38642. return ActionManager._OnPickTrigger;
  38643. },
  38644. enumerable: true,
  38645. configurable: true
  38646. });
  38647. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  38648. get: function () {
  38649. return ActionManager._OnLeftPickTrigger;
  38650. },
  38651. enumerable: true,
  38652. configurable: true
  38653. });
  38654. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  38655. get: function () {
  38656. return ActionManager._OnRightPickTrigger;
  38657. },
  38658. enumerable: true,
  38659. configurable: true
  38660. });
  38661. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  38662. get: function () {
  38663. return ActionManager._OnCenterPickTrigger;
  38664. },
  38665. enumerable: true,
  38666. configurable: true
  38667. });
  38668. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  38669. get: function () {
  38670. return ActionManager._OnPickDownTrigger;
  38671. },
  38672. enumerable: true,
  38673. configurable: true
  38674. });
  38675. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  38676. get: function () {
  38677. return ActionManager._OnPickUpTrigger;
  38678. },
  38679. enumerable: true,
  38680. configurable: true
  38681. });
  38682. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  38683. /// This trigger will only be raised if you also declared a OnPickDown
  38684. get: function () {
  38685. return ActionManager._OnPickOutTrigger;
  38686. },
  38687. enumerable: true,
  38688. configurable: true
  38689. });
  38690. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  38691. get: function () {
  38692. return ActionManager._OnLongPressTrigger;
  38693. },
  38694. enumerable: true,
  38695. configurable: true
  38696. });
  38697. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  38698. get: function () {
  38699. return ActionManager._OnPointerOverTrigger;
  38700. },
  38701. enumerable: true,
  38702. configurable: true
  38703. });
  38704. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  38705. get: function () {
  38706. return ActionManager._OnPointerOutTrigger;
  38707. },
  38708. enumerable: true,
  38709. configurable: true
  38710. });
  38711. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  38712. get: function () {
  38713. return ActionManager._OnEveryFrameTrigger;
  38714. },
  38715. enumerable: true,
  38716. configurable: true
  38717. });
  38718. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  38719. get: function () {
  38720. return ActionManager._OnIntersectionEnterTrigger;
  38721. },
  38722. enumerable: true,
  38723. configurable: true
  38724. });
  38725. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  38726. get: function () {
  38727. return ActionManager._OnIntersectionExitTrigger;
  38728. },
  38729. enumerable: true,
  38730. configurable: true
  38731. });
  38732. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  38733. get: function () {
  38734. return ActionManager._OnKeyDownTrigger;
  38735. },
  38736. enumerable: true,
  38737. configurable: true
  38738. });
  38739. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  38740. get: function () {
  38741. return ActionManager._OnKeyUpTrigger;
  38742. },
  38743. enumerable: true,
  38744. configurable: true
  38745. });
  38746. // Methods
  38747. ActionManager.prototype.dispose = function () {
  38748. var index = this._scene._actionManagers.indexOf(this);
  38749. if (index > -1) {
  38750. this._scene._actionManagers.splice(index, 1);
  38751. }
  38752. };
  38753. ActionManager.prototype.getScene = function () {
  38754. return this._scene;
  38755. };
  38756. /**
  38757. * Does this action manager handles actions of any of the given triggers
  38758. * @param {number[]} triggers - the triggers to be tested
  38759. * @return {boolean} whether one (or more) of the triggers is handeled
  38760. */
  38761. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  38762. for (var index = 0; index < this.actions.length; index++) {
  38763. var action = this.actions[index];
  38764. if (triggers.indexOf(action.trigger) > -1) {
  38765. return true;
  38766. }
  38767. }
  38768. return false;
  38769. };
  38770. /**
  38771. * Does this action manager handles actions of a given trigger
  38772. * @param {number} trigger - the trigger to be tested
  38773. * @return {boolean} whether the trigger is handeled
  38774. */
  38775. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  38776. for (var index = 0; index < this.actions.length; index++) {
  38777. var action = this.actions[index];
  38778. if (action.trigger === trigger) {
  38779. return true;
  38780. }
  38781. }
  38782. return false;
  38783. };
  38784. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  38785. /**
  38786. * Does this action manager has pointer triggers
  38787. * @return {boolean} whether or not it has pointer triggers
  38788. */
  38789. get: function () {
  38790. for (var index = 0; index < this.actions.length; index++) {
  38791. var action = this.actions[index];
  38792. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  38793. return true;
  38794. }
  38795. }
  38796. return false;
  38797. },
  38798. enumerable: true,
  38799. configurable: true
  38800. });
  38801. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  38802. /**
  38803. * Does this action manager has pick triggers
  38804. * @return {boolean} whether or not it has pick triggers
  38805. */
  38806. get: function () {
  38807. for (var index = 0; index < this.actions.length; index++) {
  38808. var action = this.actions[index];
  38809. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  38810. return true;
  38811. }
  38812. }
  38813. return false;
  38814. },
  38815. enumerable: true,
  38816. configurable: true
  38817. });
  38818. /**
  38819. * Registers an action to this action manager
  38820. * @param {BABYLON.Action} action - the action to be registered
  38821. * @return {BABYLON.Action} the action amended (prepared) after registration
  38822. */
  38823. ActionManager.prototype.registerAction = function (action) {
  38824. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  38825. if (this.getScene().actionManager !== this) {
  38826. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  38827. return null;
  38828. }
  38829. }
  38830. this.actions.push(action);
  38831. action._actionManager = this;
  38832. action._prepare();
  38833. return action;
  38834. };
  38835. /**
  38836. * Process a specific trigger
  38837. * @param {number} trigger - the trigger to process
  38838. * @param evt {BABYLON.ActionEvent} the event details to be processed
  38839. */
  38840. ActionManager.prototype.processTrigger = function (trigger, evt) {
  38841. for (var index = 0; index < this.actions.length; index++) {
  38842. var action = this.actions[index];
  38843. if (action.trigger === trigger) {
  38844. if (trigger === ActionManager.OnKeyUpTrigger
  38845. || trigger === ActionManager.OnKeyDownTrigger) {
  38846. var parameter = action.getTriggerParameter();
  38847. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  38848. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  38849. var actualkey = String.fromCharCode(unicode).toLowerCase();
  38850. if (actualkey !== parameter.toLowerCase()) {
  38851. continue;
  38852. }
  38853. }
  38854. }
  38855. action._executeCurrent(evt);
  38856. }
  38857. }
  38858. };
  38859. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  38860. var properties = propertyPath.split(".");
  38861. for (var index = 0; index < properties.length - 1; index++) {
  38862. target = target[properties[index]];
  38863. }
  38864. return target;
  38865. };
  38866. ActionManager.prototype._getProperty = function (propertyPath) {
  38867. var properties = propertyPath.split(".");
  38868. return properties[properties.length - 1];
  38869. };
  38870. ActionManager.prototype.serialize = function (name) {
  38871. var root = {
  38872. children: [],
  38873. name: name,
  38874. type: 3,
  38875. properties: [] // Empty for root but required
  38876. };
  38877. for (var i = 0; i < this.actions.length; i++) {
  38878. var triggerObject = {
  38879. type: 0,
  38880. children: [],
  38881. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  38882. properties: []
  38883. };
  38884. var triggerOptions = this.actions[i].triggerOptions;
  38885. if (triggerOptions && typeof triggerOptions !== "number") {
  38886. if (triggerOptions.parameter instanceof BABYLON.Node) {
  38887. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  38888. }
  38889. else {
  38890. var parameter = {};
  38891. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  38892. if (triggerOptions.parameter.mesh) {
  38893. parameter._meshId = triggerOptions.parameter.mesh.id;
  38894. }
  38895. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  38896. }
  38897. }
  38898. // Serialize child action, recursively
  38899. this.actions[i].serialize(triggerObject);
  38900. // Add serialized trigger
  38901. root.children.push(triggerObject);
  38902. }
  38903. return root;
  38904. };
  38905. ActionManager.Parse = function (parsedActions, object, scene) {
  38906. var actionManager = new BABYLON.ActionManager(scene);
  38907. if (object === null)
  38908. scene.actionManager = actionManager;
  38909. else
  38910. object.actionManager = actionManager;
  38911. // instanciate a new object
  38912. var instanciate = function (name, params) {
  38913. var newInstance = Object.create(BABYLON[name].prototype);
  38914. newInstance.constructor.apply(newInstance, params);
  38915. return newInstance;
  38916. };
  38917. var parseParameter = function (name, value, target, propertyPath) {
  38918. if (propertyPath === null) {
  38919. // String, boolean or float
  38920. var floatValue = parseFloat(value);
  38921. if (value === "true" || value === "false")
  38922. return value === "true";
  38923. else
  38924. return isNaN(floatValue) ? value : floatValue;
  38925. }
  38926. var effectiveTarget = propertyPath.split(".");
  38927. var values = value.split(",");
  38928. // Get effective Target
  38929. for (var i = 0; i < effectiveTarget.length; i++) {
  38930. target = target[effectiveTarget[i]];
  38931. }
  38932. // Return appropriate value with its type
  38933. if (typeof (target) === "boolean")
  38934. return values[0] === "true";
  38935. if (typeof (target) === "string")
  38936. return values[0];
  38937. // Parameters with multiple values such as Vector3 etc.
  38938. var split = new Array();
  38939. for (var i = 0; i < values.length; i++)
  38940. split.push(parseFloat(values[i]));
  38941. if (target instanceof BABYLON.Vector3)
  38942. return BABYLON.Vector3.FromArray(split);
  38943. if (target instanceof BABYLON.Vector4)
  38944. return BABYLON.Vector4.FromArray(split);
  38945. if (target instanceof BABYLON.Color3)
  38946. return BABYLON.Color3.FromArray(split);
  38947. if (target instanceof BABYLON.Color4)
  38948. return BABYLON.Color4.FromArray(split);
  38949. return parseFloat(values[0]);
  38950. };
  38951. // traverse graph per trigger
  38952. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  38953. if (combineArray === void 0) { combineArray = null; }
  38954. if (parsedAction.detached)
  38955. return;
  38956. var parameters = new Array();
  38957. var target = null;
  38958. var propertyPath = null;
  38959. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  38960. // Parameters
  38961. if (parsedAction.type === 2)
  38962. parameters.push(actionManager);
  38963. else
  38964. parameters.push(trigger);
  38965. if (combine) {
  38966. var actions = new Array();
  38967. for (var j = 0; j < parsedAction.combine.length; j++) {
  38968. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  38969. }
  38970. parameters.push(actions);
  38971. }
  38972. else {
  38973. for (var i = 0; i < parsedAction.properties.length; i++) {
  38974. var value = parsedAction.properties[i].value;
  38975. var name = parsedAction.properties[i].name;
  38976. var targetType = parsedAction.properties[i].targetType;
  38977. if (name === "target")
  38978. if (targetType !== null && targetType === "SceneProperties")
  38979. value = target = scene;
  38980. else
  38981. value = target = scene.getNodeByName(value);
  38982. else if (name === "parent")
  38983. value = scene.getNodeByName(value);
  38984. else if (name === "sound")
  38985. value = scene.getSoundByName(value);
  38986. else if (name !== "propertyPath") {
  38987. if (parsedAction.type === 2 && name === "operator")
  38988. value = BABYLON.ValueCondition[value];
  38989. else
  38990. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  38991. }
  38992. else {
  38993. propertyPath = value;
  38994. }
  38995. parameters.push(value);
  38996. }
  38997. }
  38998. if (combineArray === null) {
  38999. parameters.push(condition);
  39000. }
  39001. else {
  39002. parameters.push(null);
  39003. }
  39004. // If interpolate value action
  39005. if (parsedAction.name === "InterpolateValueAction") {
  39006. var param = parameters[parameters.length - 2];
  39007. parameters[parameters.length - 1] = param;
  39008. parameters[parameters.length - 2] = condition;
  39009. }
  39010. // Action or condition(s) and not CombineAction
  39011. var newAction = instanciate(parsedAction.name, parameters);
  39012. if (newAction instanceof BABYLON.Condition && condition !== null) {
  39013. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  39014. if (action)
  39015. action.then(nothing);
  39016. else
  39017. actionManager.registerAction(nothing);
  39018. action = nothing;
  39019. }
  39020. if (combineArray === null) {
  39021. if (newAction instanceof BABYLON.Condition) {
  39022. condition = newAction;
  39023. newAction = action;
  39024. }
  39025. else {
  39026. condition = null;
  39027. if (action)
  39028. action.then(newAction);
  39029. else
  39030. actionManager.registerAction(newAction);
  39031. }
  39032. }
  39033. else {
  39034. combineArray.push(newAction);
  39035. }
  39036. for (var i = 0; i < parsedAction.children.length; i++)
  39037. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  39038. };
  39039. // triggers
  39040. for (var i = 0; i < parsedActions.children.length; i++) {
  39041. var triggerParams;
  39042. var trigger = parsedActions.children[i];
  39043. if (trigger.properties.length > 0) {
  39044. var param = trigger.properties[0].value;
  39045. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  39046. if (value._meshId) {
  39047. value.mesh = scene.getMeshByID(value._meshId);
  39048. }
  39049. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  39050. }
  39051. else
  39052. triggerParams = BABYLON.ActionManager[trigger.name];
  39053. for (var j = 0; j < trigger.children.length; j++) {
  39054. if (!trigger.detached)
  39055. traverse(trigger.children[j], triggerParams, null, null);
  39056. }
  39057. }
  39058. };
  39059. ActionManager.GetTriggerName = function (trigger) {
  39060. switch (trigger) {
  39061. case 0: return "NothingTrigger";
  39062. case 1: return "OnPickTrigger";
  39063. case 2: return "OnLeftPickTrigger";
  39064. case 3: return "OnRightPickTrigger";
  39065. case 4: return "OnCenterPickTrigger";
  39066. case 5: return "OnPickDownTrigger";
  39067. case 6: return "OnPickUpTrigger";
  39068. case 7: return "OnLongPressTrigger";
  39069. case 8: return "OnPointerOverTrigger";
  39070. case 9: return "OnPointerOutTrigger";
  39071. case 10: return "OnEveryFrameTrigger";
  39072. case 11: return "OnIntersectionEnterTrigger";
  39073. case 12: return "OnIntersectionExitTrigger";
  39074. case 13: return "OnKeyDownTrigger";
  39075. case 14: return "OnKeyUpTrigger";
  39076. case 15: return "OnPickOutTrigger";
  39077. default: return "";
  39078. }
  39079. };
  39080. return ActionManager;
  39081. }());
  39082. // Statics
  39083. ActionManager._NothingTrigger = 0;
  39084. ActionManager._OnPickTrigger = 1;
  39085. ActionManager._OnLeftPickTrigger = 2;
  39086. ActionManager._OnRightPickTrigger = 3;
  39087. ActionManager._OnCenterPickTrigger = 4;
  39088. ActionManager._OnPickDownTrigger = 5;
  39089. ActionManager._OnPickUpTrigger = 6;
  39090. ActionManager._OnLongPressTrigger = 7;
  39091. ActionManager._OnPointerOverTrigger = 8;
  39092. ActionManager._OnPointerOutTrigger = 9;
  39093. ActionManager._OnEveryFrameTrigger = 10;
  39094. ActionManager._OnIntersectionEnterTrigger = 11;
  39095. ActionManager._OnIntersectionExitTrigger = 12;
  39096. ActionManager._OnKeyDownTrigger = 13;
  39097. ActionManager._OnKeyUpTrigger = 14;
  39098. ActionManager._OnPickOutTrigger = 15;
  39099. ActionManager.DragMovementThreshold = 10; // in pixels
  39100. ActionManager.LongPressDelay = 500; // in milliseconds
  39101. BABYLON.ActionManager = ActionManager;
  39102. })(BABYLON || (BABYLON = {}));
  39103. //# sourceMappingURL=babylon.actionManager.js.map
  39104. var BABYLON;
  39105. (function (BABYLON) {
  39106. var InterpolateValueAction = (function (_super) {
  39107. __extends(InterpolateValueAction, _super);
  39108. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  39109. if (duration === void 0) { duration = 1000; }
  39110. var _this = _super.call(this, triggerOptions, condition) || this;
  39111. _this.propertyPath = propertyPath;
  39112. _this.value = value;
  39113. _this.duration = duration;
  39114. _this.stopOtherAnimations = stopOtherAnimations;
  39115. _this.onInterpolationDone = onInterpolationDone;
  39116. _this._target = _this._effectiveTarget = target;
  39117. return _this;
  39118. }
  39119. InterpolateValueAction.prototype._prepare = function () {
  39120. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39121. this._property = this._getProperty(this.propertyPath);
  39122. };
  39123. InterpolateValueAction.prototype.execute = function () {
  39124. var scene = this._actionManager.getScene();
  39125. var keys = [
  39126. {
  39127. frame: 0,
  39128. value: this._effectiveTarget[this._property]
  39129. }, {
  39130. frame: 100,
  39131. value: this.value
  39132. }
  39133. ];
  39134. var dataType;
  39135. if (typeof this.value === "number") {
  39136. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  39137. }
  39138. else if (this.value instanceof BABYLON.Color3) {
  39139. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  39140. }
  39141. else if (this.value instanceof BABYLON.Vector3) {
  39142. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  39143. }
  39144. else if (this.value instanceof BABYLON.Matrix) {
  39145. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  39146. }
  39147. else if (this.value instanceof BABYLON.Quaternion) {
  39148. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  39149. }
  39150. else {
  39151. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  39152. return;
  39153. }
  39154. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  39155. animation.setKeys(keys);
  39156. if (this.stopOtherAnimations) {
  39157. scene.stopAnimation(this._effectiveTarget);
  39158. }
  39159. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  39160. };
  39161. InterpolateValueAction.prototype.serialize = function (parent) {
  39162. return _super.prototype._serialize.call(this, {
  39163. name: "InterpolateValueAction",
  39164. properties: [
  39165. BABYLON.Action._GetTargetProperty(this._target),
  39166. { name: "propertyPath", value: this.propertyPath },
  39167. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  39168. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  39169. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  39170. ]
  39171. }, parent);
  39172. };
  39173. return InterpolateValueAction;
  39174. }(BABYLON.Action));
  39175. BABYLON.InterpolateValueAction = InterpolateValueAction;
  39176. })(BABYLON || (BABYLON = {}));
  39177. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  39178. var BABYLON;
  39179. (function (BABYLON) {
  39180. var SwitchBooleanAction = (function (_super) {
  39181. __extends(SwitchBooleanAction, _super);
  39182. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  39183. var _this = _super.call(this, triggerOptions, condition) || this;
  39184. _this.propertyPath = propertyPath;
  39185. _this._target = _this._effectiveTarget = target;
  39186. return _this;
  39187. }
  39188. SwitchBooleanAction.prototype._prepare = function () {
  39189. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39190. this._property = this._getProperty(this.propertyPath);
  39191. };
  39192. SwitchBooleanAction.prototype.execute = function () {
  39193. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  39194. };
  39195. SwitchBooleanAction.prototype.serialize = function (parent) {
  39196. return _super.prototype._serialize.call(this, {
  39197. name: "SwitchBooleanAction",
  39198. properties: [
  39199. BABYLON.Action._GetTargetProperty(this._target),
  39200. { name: "propertyPath", value: this.propertyPath }
  39201. ]
  39202. }, parent);
  39203. };
  39204. return SwitchBooleanAction;
  39205. }(BABYLON.Action));
  39206. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  39207. var SetStateAction = (function (_super) {
  39208. __extends(SetStateAction, _super);
  39209. function SetStateAction(triggerOptions, target, value, condition) {
  39210. var _this = _super.call(this, triggerOptions, condition) || this;
  39211. _this.value = value;
  39212. _this._target = target;
  39213. return _this;
  39214. }
  39215. SetStateAction.prototype.execute = function () {
  39216. this._target.state = this.value;
  39217. };
  39218. SetStateAction.prototype.serialize = function (parent) {
  39219. return _super.prototype._serialize.call(this, {
  39220. name: "SetStateAction",
  39221. properties: [
  39222. BABYLON.Action._GetTargetProperty(this._target),
  39223. { name: "value", value: this.value }
  39224. ]
  39225. }, parent);
  39226. };
  39227. return SetStateAction;
  39228. }(BABYLON.Action));
  39229. BABYLON.SetStateAction = SetStateAction;
  39230. var SetValueAction = (function (_super) {
  39231. __extends(SetValueAction, _super);
  39232. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  39233. var _this = _super.call(this, triggerOptions, condition) || this;
  39234. _this.propertyPath = propertyPath;
  39235. _this.value = value;
  39236. _this._target = _this._effectiveTarget = target;
  39237. return _this;
  39238. }
  39239. SetValueAction.prototype._prepare = function () {
  39240. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39241. this._property = this._getProperty(this.propertyPath);
  39242. };
  39243. SetValueAction.prototype.execute = function () {
  39244. this._effectiveTarget[this._property] = this.value;
  39245. if (this._target.markAsDirty) {
  39246. this._target.markAsDirty(this._property);
  39247. }
  39248. };
  39249. SetValueAction.prototype.serialize = function (parent) {
  39250. return _super.prototype._serialize.call(this, {
  39251. name: "SetValueAction",
  39252. properties: [
  39253. BABYLON.Action._GetTargetProperty(this._target),
  39254. { name: "propertyPath", value: this.propertyPath },
  39255. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39256. ]
  39257. }, parent);
  39258. };
  39259. return SetValueAction;
  39260. }(BABYLON.Action));
  39261. BABYLON.SetValueAction = SetValueAction;
  39262. var IncrementValueAction = (function (_super) {
  39263. __extends(IncrementValueAction, _super);
  39264. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  39265. var _this = _super.call(this, triggerOptions, condition) || this;
  39266. _this.propertyPath = propertyPath;
  39267. _this.value = value;
  39268. _this._target = _this._effectiveTarget = target;
  39269. return _this;
  39270. }
  39271. IncrementValueAction.prototype._prepare = function () {
  39272. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39273. this._property = this._getProperty(this.propertyPath);
  39274. if (typeof this._effectiveTarget[this._property] !== "number") {
  39275. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  39276. }
  39277. };
  39278. IncrementValueAction.prototype.execute = function () {
  39279. this._effectiveTarget[this._property] += this.value;
  39280. if (this._target.markAsDirty) {
  39281. this._target.markAsDirty(this._property);
  39282. }
  39283. };
  39284. IncrementValueAction.prototype.serialize = function (parent) {
  39285. return _super.prototype._serialize.call(this, {
  39286. name: "IncrementValueAction",
  39287. properties: [
  39288. BABYLON.Action._GetTargetProperty(this._target),
  39289. { name: "propertyPath", value: this.propertyPath },
  39290. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39291. ]
  39292. }, parent);
  39293. };
  39294. return IncrementValueAction;
  39295. }(BABYLON.Action));
  39296. BABYLON.IncrementValueAction = IncrementValueAction;
  39297. var PlayAnimationAction = (function (_super) {
  39298. __extends(PlayAnimationAction, _super);
  39299. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  39300. var _this = _super.call(this, triggerOptions, condition) || this;
  39301. _this.from = from;
  39302. _this.to = to;
  39303. _this.loop = loop;
  39304. _this._target = target;
  39305. return _this;
  39306. }
  39307. PlayAnimationAction.prototype._prepare = function () {
  39308. };
  39309. PlayAnimationAction.prototype.execute = function () {
  39310. var scene = this._actionManager.getScene();
  39311. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  39312. };
  39313. PlayAnimationAction.prototype.serialize = function (parent) {
  39314. return _super.prototype._serialize.call(this, {
  39315. name: "PlayAnimationAction",
  39316. properties: [
  39317. BABYLON.Action._GetTargetProperty(this._target),
  39318. { name: "from", value: String(this.from) },
  39319. { name: "to", value: String(this.to) },
  39320. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  39321. ]
  39322. }, parent);
  39323. };
  39324. return PlayAnimationAction;
  39325. }(BABYLON.Action));
  39326. BABYLON.PlayAnimationAction = PlayAnimationAction;
  39327. var StopAnimationAction = (function (_super) {
  39328. __extends(StopAnimationAction, _super);
  39329. function StopAnimationAction(triggerOptions, target, condition) {
  39330. var _this = _super.call(this, triggerOptions, condition) || this;
  39331. _this._target = target;
  39332. return _this;
  39333. }
  39334. StopAnimationAction.prototype._prepare = function () {
  39335. };
  39336. StopAnimationAction.prototype.execute = function () {
  39337. var scene = this._actionManager.getScene();
  39338. scene.stopAnimation(this._target);
  39339. };
  39340. StopAnimationAction.prototype.serialize = function (parent) {
  39341. return _super.prototype._serialize.call(this, {
  39342. name: "StopAnimationAction",
  39343. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  39344. }, parent);
  39345. };
  39346. return StopAnimationAction;
  39347. }(BABYLON.Action));
  39348. BABYLON.StopAnimationAction = StopAnimationAction;
  39349. var DoNothingAction = (function (_super) {
  39350. __extends(DoNothingAction, _super);
  39351. function DoNothingAction(triggerOptions, condition) {
  39352. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  39353. return _super.call(this, triggerOptions, condition) || this;
  39354. }
  39355. DoNothingAction.prototype.execute = function () {
  39356. };
  39357. DoNothingAction.prototype.serialize = function (parent) {
  39358. return _super.prototype._serialize.call(this, {
  39359. name: "DoNothingAction",
  39360. properties: []
  39361. }, parent);
  39362. };
  39363. return DoNothingAction;
  39364. }(BABYLON.Action));
  39365. BABYLON.DoNothingAction = DoNothingAction;
  39366. var CombineAction = (function (_super) {
  39367. __extends(CombineAction, _super);
  39368. function CombineAction(triggerOptions, children, condition) {
  39369. var _this = _super.call(this, triggerOptions, condition) || this;
  39370. _this.children = children;
  39371. return _this;
  39372. }
  39373. CombineAction.prototype._prepare = function () {
  39374. for (var index = 0; index < this.children.length; index++) {
  39375. this.children[index]._actionManager = this._actionManager;
  39376. this.children[index]._prepare();
  39377. }
  39378. };
  39379. CombineAction.prototype.execute = function (evt) {
  39380. for (var index = 0; index < this.children.length; index++) {
  39381. this.children[index].execute(evt);
  39382. }
  39383. };
  39384. CombineAction.prototype.serialize = function (parent) {
  39385. var serializationObject = _super.prototype._serialize.call(this, {
  39386. name: "CombineAction",
  39387. properties: [],
  39388. combine: []
  39389. }, parent);
  39390. for (var i = 0; i < this.children.length; i++) {
  39391. serializationObject.combine.push(this.children[i].serialize(null));
  39392. }
  39393. return serializationObject;
  39394. };
  39395. return CombineAction;
  39396. }(BABYLON.Action));
  39397. BABYLON.CombineAction = CombineAction;
  39398. var ExecuteCodeAction = (function (_super) {
  39399. __extends(ExecuteCodeAction, _super);
  39400. function ExecuteCodeAction(triggerOptions, func, condition) {
  39401. var _this = _super.call(this, triggerOptions, condition) || this;
  39402. _this.func = func;
  39403. return _this;
  39404. }
  39405. ExecuteCodeAction.prototype.execute = function (evt) {
  39406. this.func(evt);
  39407. };
  39408. return ExecuteCodeAction;
  39409. }(BABYLON.Action));
  39410. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  39411. var SetParentAction = (function (_super) {
  39412. __extends(SetParentAction, _super);
  39413. function SetParentAction(triggerOptions, target, parent, condition) {
  39414. var _this = _super.call(this, triggerOptions, condition) || this;
  39415. _this._target = target;
  39416. _this._parent = parent;
  39417. return _this;
  39418. }
  39419. SetParentAction.prototype._prepare = function () {
  39420. };
  39421. SetParentAction.prototype.execute = function () {
  39422. if (this._target.parent === this._parent) {
  39423. return;
  39424. }
  39425. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  39426. invertParentWorldMatrix.invert();
  39427. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  39428. this._target.parent = this._parent;
  39429. };
  39430. SetParentAction.prototype.serialize = function (parent) {
  39431. return _super.prototype._serialize.call(this, {
  39432. name: "SetParentAction",
  39433. properties: [
  39434. BABYLON.Action._GetTargetProperty(this._target),
  39435. BABYLON.Action._GetTargetProperty(this._parent),
  39436. ]
  39437. }, parent);
  39438. };
  39439. return SetParentAction;
  39440. }(BABYLON.Action));
  39441. BABYLON.SetParentAction = SetParentAction;
  39442. var PlaySoundAction = (function (_super) {
  39443. __extends(PlaySoundAction, _super);
  39444. function PlaySoundAction(triggerOptions, sound, condition) {
  39445. var _this = _super.call(this, triggerOptions, condition) || this;
  39446. _this._sound = sound;
  39447. return _this;
  39448. }
  39449. PlaySoundAction.prototype._prepare = function () {
  39450. };
  39451. PlaySoundAction.prototype.execute = function () {
  39452. if (this._sound !== undefined)
  39453. this._sound.play();
  39454. };
  39455. PlaySoundAction.prototype.serialize = function (parent) {
  39456. return _super.prototype._serialize.call(this, {
  39457. name: "PlaySoundAction",
  39458. properties: [{ name: "sound", value: this._sound.name }]
  39459. }, parent);
  39460. };
  39461. return PlaySoundAction;
  39462. }(BABYLON.Action));
  39463. BABYLON.PlaySoundAction = PlaySoundAction;
  39464. var StopSoundAction = (function (_super) {
  39465. __extends(StopSoundAction, _super);
  39466. function StopSoundAction(triggerOptions, sound, condition) {
  39467. var _this = _super.call(this, triggerOptions, condition) || this;
  39468. _this._sound = sound;
  39469. return _this;
  39470. }
  39471. StopSoundAction.prototype._prepare = function () {
  39472. };
  39473. StopSoundAction.prototype.execute = function () {
  39474. if (this._sound !== undefined)
  39475. this._sound.stop();
  39476. };
  39477. StopSoundAction.prototype.serialize = function (parent) {
  39478. return _super.prototype._serialize.call(this, {
  39479. name: "StopSoundAction",
  39480. properties: [{ name: "sound", value: this._sound.name }]
  39481. }, parent);
  39482. };
  39483. return StopSoundAction;
  39484. }(BABYLON.Action));
  39485. BABYLON.StopSoundAction = StopSoundAction;
  39486. })(BABYLON || (BABYLON = {}));
  39487. //# sourceMappingURL=babylon.directActions.js.map
  39488. var BABYLON;
  39489. (function (BABYLON) {
  39490. var Geometry = (function () {
  39491. function Geometry(id, scene, vertexData, updatable, mesh) {
  39492. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39493. this._totalVertices = 0;
  39494. this._isDisposed = false;
  39495. this.id = id;
  39496. this._engine = scene.getEngine();
  39497. this._meshes = [];
  39498. this._scene = scene;
  39499. //Init vertex buffer cache
  39500. this._vertexBuffers = {};
  39501. this._indices = [];
  39502. // vertexData
  39503. if (vertexData) {
  39504. this.setAllVerticesData(vertexData, updatable);
  39505. }
  39506. else {
  39507. this._totalVertices = 0;
  39508. this._indices = [];
  39509. }
  39510. if (this._engine.getCaps().vertexArrayObject) {
  39511. this._vertexArrayObjects = {};
  39512. }
  39513. // applyToMesh
  39514. if (mesh) {
  39515. if (mesh instanceof BABYLON.LinesMesh) {
  39516. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39517. this.updateExtend();
  39518. }
  39519. this.applyToMesh(mesh);
  39520. mesh.computeWorldMatrix(true);
  39521. }
  39522. }
  39523. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39524. /**
  39525. * 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
  39526. * @returns The Bias Vector
  39527. */
  39528. get: function () {
  39529. return this._boundingBias;
  39530. },
  39531. set: function (value) {
  39532. if (this._boundingBias && this._boundingBias.equals(value)) {
  39533. return;
  39534. }
  39535. this._boundingBias = value.clone();
  39536. this.updateBoundingInfo(true, null);
  39537. },
  39538. enumerable: true,
  39539. configurable: true
  39540. });
  39541. Object.defineProperty(Geometry.prototype, "extend", {
  39542. get: function () {
  39543. return this._extend;
  39544. },
  39545. enumerable: true,
  39546. configurable: true
  39547. });
  39548. Geometry.prototype.getScene = function () {
  39549. return this._scene;
  39550. };
  39551. Geometry.prototype.getEngine = function () {
  39552. return this._engine;
  39553. };
  39554. Geometry.prototype.isReady = function () {
  39555. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39556. };
  39557. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39558. get: function () {
  39559. for (var index = 0; index < this._meshes.length; index++) {
  39560. if (!this._meshes[index].doNotSerialize) {
  39561. return false;
  39562. }
  39563. }
  39564. return true;
  39565. },
  39566. enumerable: true,
  39567. configurable: true
  39568. });
  39569. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39570. vertexData.applyToGeometry(this, updatable);
  39571. this.notifyUpdate();
  39572. };
  39573. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39574. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39575. this.setVerticesBuffer(buffer);
  39576. };
  39577. Geometry.prototype.setVerticesBuffer = function (buffer) {
  39578. var kind = buffer.getKind();
  39579. if (this._vertexBuffers[kind]) {
  39580. this._vertexBuffers[kind].dispose();
  39581. }
  39582. this._vertexBuffers[kind] = buffer;
  39583. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39584. var data = buffer.getData();
  39585. var stride = buffer.getStrideSize();
  39586. this._totalVertices = data.length / stride;
  39587. this.updateExtend(data, stride);
  39588. var meshes = this._meshes;
  39589. var numOfMeshes = meshes.length;
  39590. for (var index = 0; index < numOfMeshes; index++) {
  39591. var mesh = meshes[index];
  39592. mesh._resetPointsArrayCache();
  39593. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39594. mesh._createGlobalSubMesh();
  39595. mesh.computeWorldMatrix(true);
  39596. }
  39597. }
  39598. this.notifyUpdate(kind);
  39599. if (this._vertexArrayObjects) {
  39600. this._disposeVertexArrayObjects();
  39601. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39602. }
  39603. };
  39604. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  39605. var vertexBuffer = this.getVertexBuffer(kind);
  39606. if (!vertexBuffer) {
  39607. return;
  39608. }
  39609. vertexBuffer.updateDirectly(data, offset);
  39610. this.notifyUpdate(kind);
  39611. };
  39612. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39613. var vertexBuffer = this.getVertexBuffer(kind);
  39614. if (!vertexBuffer) {
  39615. return;
  39616. }
  39617. vertexBuffer.update(data);
  39618. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39619. var stride = vertexBuffer.getStrideSize();
  39620. this._totalVertices = data.length / stride;
  39621. this.updateBoundingInfo(updateExtends, data);
  39622. }
  39623. this.notifyUpdate(kind);
  39624. };
  39625. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  39626. if (updateExtends) {
  39627. this.updateExtend(data);
  39628. }
  39629. var meshes = this._meshes;
  39630. var numOfMeshes = meshes.length;
  39631. for (var index = 0; index < numOfMeshes; index++) {
  39632. var mesh = meshes[index];
  39633. mesh._resetPointsArrayCache();
  39634. if (updateExtends) {
  39635. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39636. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39637. var subMesh = mesh.subMeshes[subIndex];
  39638. subMesh.refreshBoundingInfo();
  39639. }
  39640. }
  39641. }
  39642. };
  39643. Geometry.prototype._bind = function (effect, indexToBind) {
  39644. if (indexToBind === void 0) { indexToBind = undefined; }
  39645. if (indexToBind === undefined) {
  39646. indexToBind = this._indexBuffer;
  39647. }
  39648. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39649. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  39650. return;
  39651. }
  39652. // Using VAO
  39653. if (!this._vertexArrayObjects[effect.key]) {
  39654. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  39655. }
  39656. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39657. };
  39658. Geometry.prototype.getTotalVertices = function () {
  39659. if (!this.isReady()) {
  39660. return 0;
  39661. }
  39662. return this._totalVertices;
  39663. };
  39664. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  39665. var vertexBuffer = this.getVertexBuffer(kind);
  39666. if (!vertexBuffer) {
  39667. return null;
  39668. }
  39669. var orig = vertexBuffer.getData();
  39670. if (!copyWhenShared || this._meshes.length === 1) {
  39671. return orig;
  39672. }
  39673. else {
  39674. var len = orig.length;
  39675. var copy = [];
  39676. for (var i = 0; i < len; i++) {
  39677. copy.push(orig[i]);
  39678. }
  39679. return copy;
  39680. }
  39681. };
  39682. Geometry.prototype.getVertexBuffer = function (kind) {
  39683. if (!this.isReady()) {
  39684. return null;
  39685. }
  39686. return this._vertexBuffers[kind];
  39687. };
  39688. Geometry.prototype.getVertexBuffers = function () {
  39689. if (!this.isReady()) {
  39690. return null;
  39691. }
  39692. return this._vertexBuffers;
  39693. };
  39694. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39695. if (!this._vertexBuffers) {
  39696. if (this._delayInfo) {
  39697. return this._delayInfo.indexOf(kind) !== -1;
  39698. }
  39699. return false;
  39700. }
  39701. return this._vertexBuffers[kind] !== undefined;
  39702. };
  39703. Geometry.prototype.getVerticesDataKinds = function () {
  39704. var result = [];
  39705. var kind;
  39706. if (!this._vertexBuffers && this._delayInfo) {
  39707. for (kind in this._delayInfo) {
  39708. result.push(kind);
  39709. }
  39710. }
  39711. else {
  39712. for (kind in this._vertexBuffers) {
  39713. result.push(kind);
  39714. }
  39715. }
  39716. return result;
  39717. };
  39718. Geometry.prototype.setIndices = function (indices, totalVertices) {
  39719. if (this._indexBuffer) {
  39720. this._engine._releaseBuffer(this._indexBuffer);
  39721. }
  39722. this._disposeVertexArrayObjects();
  39723. this._indices = indices;
  39724. if (this._meshes.length !== 0 && this._indices) {
  39725. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39726. }
  39727. if (totalVertices !== undefined) {
  39728. this._totalVertices = totalVertices;
  39729. }
  39730. var meshes = this._meshes;
  39731. var numOfMeshes = meshes.length;
  39732. for (var index = 0; index < numOfMeshes; index++) {
  39733. meshes[index]._createGlobalSubMesh();
  39734. }
  39735. this.notifyUpdate();
  39736. };
  39737. Geometry.prototype.getTotalIndices = function () {
  39738. if (!this.isReady()) {
  39739. return 0;
  39740. }
  39741. return this._indices.length;
  39742. };
  39743. Geometry.prototype.getIndices = function (copyWhenShared) {
  39744. if (!this.isReady()) {
  39745. return null;
  39746. }
  39747. var orig = this._indices;
  39748. if (!copyWhenShared || this._meshes.length === 1) {
  39749. return orig;
  39750. }
  39751. else {
  39752. var len = orig.length;
  39753. var copy = [];
  39754. for (var i = 0; i < len; i++) {
  39755. copy.push(orig[i]);
  39756. }
  39757. return copy;
  39758. }
  39759. };
  39760. Geometry.prototype.getIndexBuffer = function () {
  39761. if (!this.isReady()) {
  39762. return null;
  39763. }
  39764. return this._indexBuffer;
  39765. };
  39766. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39767. var meshes = this._meshes;
  39768. var index = meshes.indexOf(mesh);
  39769. if (index === -1) {
  39770. return;
  39771. }
  39772. meshes.splice(index, 1);
  39773. mesh._geometry = null;
  39774. if (meshes.length === 0 && shouldDispose) {
  39775. this.dispose();
  39776. }
  39777. };
  39778. Geometry.prototype.applyToMesh = function (mesh) {
  39779. if (mesh._geometry === this) {
  39780. return;
  39781. }
  39782. var previousGeometry = mesh._geometry;
  39783. if (previousGeometry) {
  39784. previousGeometry.releaseForMesh(mesh);
  39785. }
  39786. var meshes = this._meshes;
  39787. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39788. mesh._geometry = this;
  39789. this._scene.pushGeometry(this);
  39790. meshes.push(mesh);
  39791. if (this.isReady()) {
  39792. this._applyToMesh(mesh);
  39793. }
  39794. else {
  39795. mesh._boundingInfo = this._boundingInfo;
  39796. }
  39797. };
  39798. Geometry.prototype.updateExtend = function (data, stride) {
  39799. if (data === void 0) { data = null; }
  39800. if (!data) {
  39801. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  39802. }
  39803. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  39804. };
  39805. Geometry.prototype._applyToMesh = function (mesh) {
  39806. var numOfMeshes = this._meshes.length;
  39807. // vertexBuffers
  39808. for (var kind in this._vertexBuffers) {
  39809. if (numOfMeshes === 1) {
  39810. this._vertexBuffers[kind].create();
  39811. }
  39812. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  39813. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39814. mesh._resetPointsArrayCache();
  39815. if (!this._extend) {
  39816. this.updateExtend(this._vertexBuffers[kind].getData());
  39817. }
  39818. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39819. mesh._createGlobalSubMesh();
  39820. //bounding info was just created again, world matrix should be applied again.
  39821. mesh._updateBoundingInfo();
  39822. }
  39823. }
  39824. // indexBuffer
  39825. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39826. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39827. }
  39828. if (this._indexBuffer) {
  39829. this._indexBuffer.references = numOfMeshes;
  39830. }
  39831. };
  39832. Geometry.prototype.notifyUpdate = function (kind) {
  39833. if (this.onGeometryUpdated) {
  39834. this.onGeometryUpdated(this, kind);
  39835. }
  39836. };
  39837. Geometry.prototype.load = function (scene, onLoaded) {
  39838. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39839. return;
  39840. }
  39841. if (this.isReady()) {
  39842. if (onLoaded) {
  39843. onLoaded();
  39844. }
  39845. return;
  39846. }
  39847. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39848. this._queueLoad(scene, onLoaded);
  39849. };
  39850. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39851. var _this = this;
  39852. scene._addPendingData(this);
  39853. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  39854. _this._delayLoadingFunction(JSON.parse(data), _this);
  39855. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39856. _this._delayInfo = [];
  39857. scene._removePendingData(_this);
  39858. var meshes = _this._meshes;
  39859. var numOfMeshes = meshes.length;
  39860. for (var index = 0; index < numOfMeshes; index++) {
  39861. _this._applyToMesh(meshes[index]);
  39862. }
  39863. if (onLoaded) {
  39864. onLoaded();
  39865. }
  39866. }, function () { }, scene.database);
  39867. };
  39868. /**
  39869. * Invert the geometry to move from a right handed system to a left handed one.
  39870. */
  39871. Geometry.prototype.toLeftHanded = function () {
  39872. // Flip faces
  39873. var tIndices = this.getIndices(false);
  39874. if (tIndices != null && tIndices.length > 0) {
  39875. for (var i = 0; i < tIndices.length; i += 3) {
  39876. var tTemp = tIndices[i + 0];
  39877. tIndices[i + 0] = tIndices[i + 2];
  39878. tIndices[i + 2] = tTemp;
  39879. }
  39880. this.setIndices(tIndices);
  39881. }
  39882. // Negate position.z
  39883. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39884. if (tPositions != null && tPositions.length > 0) {
  39885. for (var i = 0; i < tPositions.length; i += 3) {
  39886. tPositions[i + 2] = -tPositions[i + 2];
  39887. }
  39888. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39889. }
  39890. // Negate normal.z
  39891. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39892. if (tNormals != null && tNormals.length > 0) {
  39893. for (var i = 0; i < tNormals.length; i += 3) {
  39894. tNormals[i + 2] = -tNormals[i + 2];
  39895. }
  39896. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39897. }
  39898. };
  39899. Geometry.prototype.isDisposed = function () {
  39900. return this._isDisposed;
  39901. };
  39902. Geometry.prototype._disposeVertexArrayObjects = function () {
  39903. if (this._vertexArrayObjects) {
  39904. for (var kind in this._vertexArrayObjects) {
  39905. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39906. }
  39907. this._vertexArrayObjects = {};
  39908. }
  39909. };
  39910. Geometry.prototype.dispose = function () {
  39911. var meshes = this._meshes;
  39912. var numOfMeshes = meshes.length;
  39913. var index;
  39914. for (index = 0; index < numOfMeshes; index++) {
  39915. this.releaseForMesh(meshes[index]);
  39916. }
  39917. this._meshes = [];
  39918. this._disposeVertexArrayObjects();
  39919. for (var kind in this._vertexBuffers) {
  39920. this._vertexBuffers[kind].dispose();
  39921. }
  39922. this._vertexBuffers = {};
  39923. this._totalVertices = 0;
  39924. if (this._indexBuffer) {
  39925. this._engine._releaseBuffer(this._indexBuffer);
  39926. }
  39927. this._indexBuffer = null;
  39928. this._indices = [];
  39929. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39930. this.delayLoadingFile = null;
  39931. this._delayLoadingFunction = null;
  39932. this._delayInfo = [];
  39933. this._boundingInfo = null;
  39934. this._scene.removeGeometry(this);
  39935. this._isDisposed = true;
  39936. };
  39937. Geometry.prototype.copy = function (id) {
  39938. var vertexData = new BABYLON.VertexData();
  39939. vertexData.indices = [];
  39940. var indices = this.getIndices();
  39941. for (var index = 0; index < indices.length; index++) {
  39942. vertexData.indices.push(indices[index]);
  39943. }
  39944. var updatable = false;
  39945. var stopChecking = false;
  39946. var kind;
  39947. for (kind in this._vertexBuffers) {
  39948. // using slice() to make a copy of the array and not just reference it
  39949. var data = this.getVerticesData(kind);
  39950. if (data instanceof Float32Array) {
  39951. vertexData.set(new Float32Array(data), kind);
  39952. }
  39953. else {
  39954. vertexData.set(data.slice(0), kind);
  39955. }
  39956. if (!stopChecking) {
  39957. updatable = this.getVertexBuffer(kind).isUpdatable();
  39958. stopChecking = !updatable;
  39959. }
  39960. }
  39961. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  39962. geometry.delayLoadState = this.delayLoadState;
  39963. geometry.delayLoadingFile = this.delayLoadingFile;
  39964. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39965. for (kind in this._delayInfo) {
  39966. geometry._delayInfo = geometry._delayInfo || [];
  39967. geometry._delayInfo.push(kind);
  39968. }
  39969. // Bounding info
  39970. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39971. return geometry;
  39972. };
  39973. Geometry.prototype.serialize = function () {
  39974. var serializationObject = {};
  39975. serializationObject.id = this.id;
  39976. if (BABYLON.Tags.HasTags(this)) {
  39977. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39978. }
  39979. return serializationObject;
  39980. };
  39981. Geometry.prototype.serializeVerticeData = function () {
  39982. var serializationObject = this.serialize();
  39983. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39984. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39985. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  39986. serializationObject.positions._updatable = true;
  39987. }
  39988. }
  39989. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39990. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39991. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  39992. serializationObject.normals._updatable = true;
  39993. }
  39994. }
  39995. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39996. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39997. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  39998. serializationObject.uvs._updatable = true;
  39999. }
  40000. }
  40001. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40002. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  40003. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  40004. serializationObject.uv2s._updatable = true;
  40005. }
  40006. }
  40007. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  40008. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  40009. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  40010. serializationObject.uv3s._updatable = true;
  40011. }
  40012. }
  40013. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  40014. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  40015. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  40016. serializationObject.uv4s._updatable = true;
  40017. }
  40018. }
  40019. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  40020. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  40021. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  40022. serializationObject.uv5s._updatable = true;
  40023. }
  40024. }
  40025. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  40026. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  40027. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  40028. serializationObject.uv6s._updatable = true;
  40029. }
  40030. }
  40031. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40032. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40033. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  40034. serializationObject.colors._updatable = true;
  40035. }
  40036. }
  40037. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40038. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40039. serializationObject.matricesIndices._isExpanded = true;
  40040. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  40041. serializationObject.matricesIndices._updatable = true;
  40042. }
  40043. }
  40044. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40045. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  40046. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  40047. serializationObject.matricesWeights._updatable = true;
  40048. }
  40049. }
  40050. serializationObject.indices = this.getIndices();
  40051. return serializationObject;
  40052. };
  40053. // Statics
  40054. Geometry.ExtractFromMesh = function (mesh, id) {
  40055. var geometry = mesh._geometry;
  40056. if (!geometry) {
  40057. return null;
  40058. }
  40059. return geometry.copy(id);
  40060. };
  40061. /**
  40062. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  40063. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  40064. * Be aware Math.random() could cause collisions, but:
  40065. * "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"
  40066. */
  40067. Geometry.RandomId = function () {
  40068. return BABYLON.Tools.RandomId();
  40069. };
  40070. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  40071. var scene = mesh.getScene();
  40072. // Geometry
  40073. var geometryId = parsedGeometry.geometryId;
  40074. if (geometryId) {
  40075. var geometry = scene.getGeometryByID(geometryId);
  40076. if (geometry) {
  40077. geometry.applyToMesh(mesh);
  40078. }
  40079. }
  40080. else if (parsedGeometry instanceof ArrayBuffer) {
  40081. var binaryInfo = mesh._binaryInfo;
  40082. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  40083. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  40084. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  40085. }
  40086. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  40087. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  40088. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  40089. }
  40090. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40091. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40092. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40093. }
  40094. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40095. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40096. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40097. }
  40098. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40099. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40100. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40101. }
  40102. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40103. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40104. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40105. }
  40106. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40107. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  40108. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40109. }
  40110. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40111. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40112. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40113. }
  40114. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40115. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40116. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40117. }
  40118. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40119. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40120. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  40121. }
  40122. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40123. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40124. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40125. }
  40126. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40127. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40128. mesh.setIndices(indicesData);
  40129. }
  40130. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40131. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40132. mesh.subMeshes = [];
  40133. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40134. var materialIndex = subMeshesData[(i * 5) + 0];
  40135. var verticesStart = subMeshesData[(i * 5) + 1];
  40136. var verticesCount = subMeshesData[(i * 5) + 2];
  40137. var indexStart = subMeshesData[(i * 5) + 3];
  40138. var indexCount = subMeshesData[(i * 5) + 4];
  40139. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40140. }
  40141. }
  40142. }
  40143. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40144. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40145. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40146. if (parsedGeometry.uvs) {
  40147. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40148. }
  40149. if (parsedGeometry.uvs2) {
  40150. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40151. }
  40152. if (parsedGeometry.uvs3) {
  40153. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40154. }
  40155. if (parsedGeometry.uvs4) {
  40156. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40157. }
  40158. if (parsedGeometry.uvs5) {
  40159. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40160. }
  40161. if (parsedGeometry.uvs6) {
  40162. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40163. }
  40164. if (parsedGeometry.colors) {
  40165. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40166. }
  40167. if (parsedGeometry.matricesIndices) {
  40168. if (!parsedGeometry.matricesIndices._isExpanded) {
  40169. var floatIndices = [];
  40170. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40171. var matricesIndex = parsedGeometry.matricesIndices[i];
  40172. floatIndices.push(matricesIndex & 0x000000FF);
  40173. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40174. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40175. floatIndices.push(matricesIndex >> 24);
  40176. }
  40177. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40178. }
  40179. else {
  40180. delete parsedGeometry.matricesIndices._isExpanded;
  40181. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40182. }
  40183. }
  40184. if (parsedGeometry.matricesIndicesExtra) {
  40185. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40186. var floatIndices = [];
  40187. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40188. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40189. floatIndices.push(matricesIndex & 0x000000FF);
  40190. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40191. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40192. floatIndices.push(matricesIndex >> 24);
  40193. }
  40194. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40195. }
  40196. else {
  40197. delete parsedGeometry.matricesIndices._isExpanded;
  40198. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40199. }
  40200. }
  40201. if (parsedGeometry.matricesWeights) {
  40202. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40203. }
  40204. if (parsedGeometry.matricesWeightsExtra) {
  40205. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40206. }
  40207. mesh.setIndices(parsedGeometry.indices);
  40208. }
  40209. // SubMeshes
  40210. if (parsedGeometry.subMeshes) {
  40211. mesh.subMeshes = [];
  40212. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40213. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40214. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40215. }
  40216. }
  40217. // Flat shading
  40218. if (mesh._shouldGenerateFlatShading) {
  40219. mesh.convertToFlatShadedMesh();
  40220. delete mesh._shouldGenerateFlatShading;
  40221. }
  40222. // Update
  40223. mesh.computeWorldMatrix(true);
  40224. // Octree
  40225. if (scene['_selectionOctree']) {
  40226. scene['_selectionOctree'].addMesh(mesh);
  40227. }
  40228. };
  40229. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40230. if (scene.getGeometryByID(parsedVertexData.id)) {
  40231. return null; // null since geometry could be something else than a box...
  40232. }
  40233. var geometry = new Geometry(parsedVertexData.id, scene);
  40234. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40235. if (parsedVertexData.delayLoadingFile) {
  40236. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40237. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40238. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40239. geometry._delayInfo = [];
  40240. if (parsedVertexData.hasUVs) {
  40241. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40242. }
  40243. if (parsedVertexData.hasUVs2) {
  40244. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40245. }
  40246. if (parsedVertexData.hasUVs3) {
  40247. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40248. }
  40249. if (parsedVertexData.hasUVs4) {
  40250. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40251. }
  40252. if (parsedVertexData.hasUVs5) {
  40253. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40254. }
  40255. if (parsedVertexData.hasUVs6) {
  40256. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40257. }
  40258. if (parsedVertexData.hasColors) {
  40259. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40260. }
  40261. if (parsedVertexData.hasMatricesIndices) {
  40262. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40263. }
  40264. if (parsedVertexData.hasMatricesWeights) {
  40265. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40266. }
  40267. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40268. }
  40269. else {
  40270. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40271. }
  40272. scene.pushGeometry(geometry, true);
  40273. return geometry;
  40274. };
  40275. return Geometry;
  40276. }());
  40277. BABYLON.Geometry = Geometry;
  40278. /////// Primitives //////////////////////////////////////////////
  40279. (function (Geometry) {
  40280. var Primitives;
  40281. (function (Primitives) {
  40282. /// Abstract class
  40283. var _Primitive = (function (_super) {
  40284. __extends(_Primitive, _super);
  40285. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  40286. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  40287. _this._canBeRegenerated = _canBeRegenerated;
  40288. _this._beingRegenerated = true;
  40289. _this.regenerate();
  40290. _this._beingRegenerated = false;
  40291. return _this;
  40292. }
  40293. _Primitive.prototype.canBeRegenerated = function () {
  40294. return this._canBeRegenerated;
  40295. };
  40296. _Primitive.prototype.regenerate = function () {
  40297. if (!this._canBeRegenerated) {
  40298. return;
  40299. }
  40300. this._beingRegenerated = true;
  40301. this.setAllVerticesData(this._regenerateVertexData(), false);
  40302. this._beingRegenerated = false;
  40303. };
  40304. _Primitive.prototype.asNewGeometry = function (id) {
  40305. return _super.prototype.copy.call(this, id);
  40306. };
  40307. // overrides
  40308. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  40309. if (!this._beingRegenerated) {
  40310. return;
  40311. }
  40312. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40313. };
  40314. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  40315. if (!this._beingRegenerated) {
  40316. return;
  40317. }
  40318. _super.prototype.setVerticesData.call(this, kind, data, false);
  40319. };
  40320. // to override
  40321. // protected
  40322. _Primitive.prototype._regenerateVertexData = function () {
  40323. throw new Error("Abstract method");
  40324. };
  40325. _Primitive.prototype.copy = function (id) {
  40326. throw new Error("Must be overriden in sub-classes.");
  40327. };
  40328. _Primitive.prototype.serialize = function () {
  40329. var serializationObject = _super.prototype.serialize.call(this);
  40330. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40331. return serializationObject;
  40332. };
  40333. return _Primitive;
  40334. }(Geometry));
  40335. Primitives._Primitive = _Primitive;
  40336. var Ribbon = (function (_super) {
  40337. __extends(Ribbon, _super);
  40338. // Members
  40339. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  40340. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40341. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40342. _this.pathArray = pathArray;
  40343. _this.closeArray = closeArray;
  40344. _this.closePath = closePath;
  40345. _this.offset = offset;
  40346. _this.side = side;
  40347. return _this;
  40348. }
  40349. Ribbon.prototype._regenerateVertexData = function () {
  40350. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40351. };
  40352. Ribbon.prototype.copy = function (id) {
  40353. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  40354. };
  40355. return Ribbon;
  40356. }(_Primitive));
  40357. Primitives.Ribbon = Ribbon;
  40358. var Box = (function (_super) {
  40359. __extends(Box, _super);
  40360. // Members
  40361. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  40362. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40363. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40364. _this.size = size;
  40365. _this.side = side;
  40366. return _this;
  40367. }
  40368. Box.prototype._regenerateVertexData = function () {
  40369. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40370. };
  40371. Box.prototype.copy = function (id) {
  40372. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40373. };
  40374. Box.prototype.serialize = function () {
  40375. var serializationObject = _super.prototype.serialize.call(this);
  40376. serializationObject.size = this.size;
  40377. return serializationObject;
  40378. };
  40379. Box.Parse = function (parsedBox, scene) {
  40380. if (scene.getGeometryByID(parsedBox.id)) {
  40381. return null; // null since geometry could be something else than a box...
  40382. }
  40383. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40384. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40385. scene.pushGeometry(box, true);
  40386. return box;
  40387. };
  40388. return Box;
  40389. }(_Primitive));
  40390. Primitives.Box = Box;
  40391. var Sphere = (function (_super) {
  40392. __extends(Sphere, _super);
  40393. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  40394. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40395. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40396. _this.segments = segments;
  40397. _this.diameter = diameter;
  40398. _this.side = side;
  40399. return _this;
  40400. }
  40401. Sphere.prototype._regenerateVertexData = function () {
  40402. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40403. };
  40404. Sphere.prototype.copy = function (id) {
  40405. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40406. };
  40407. Sphere.prototype.serialize = function () {
  40408. var serializationObject = _super.prototype.serialize.call(this);
  40409. serializationObject.segments = this.segments;
  40410. serializationObject.diameter = this.diameter;
  40411. return serializationObject;
  40412. };
  40413. Sphere.Parse = function (parsedSphere, scene) {
  40414. if (scene.getGeometryByID(parsedSphere.id)) {
  40415. return null; // null since geometry could be something else than a sphere...
  40416. }
  40417. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40418. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40419. scene.pushGeometry(sphere, true);
  40420. return sphere;
  40421. };
  40422. return Sphere;
  40423. }(_Primitive));
  40424. Primitives.Sphere = Sphere;
  40425. var Disc = (function (_super) {
  40426. __extends(Disc, _super);
  40427. // Members
  40428. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  40429. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40430. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40431. _this.radius = radius;
  40432. _this.tessellation = tessellation;
  40433. _this.side = side;
  40434. return _this;
  40435. }
  40436. Disc.prototype._regenerateVertexData = function () {
  40437. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40438. };
  40439. Disc.prototype.copy = function (id) {
  40440. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40441. };
  40442. return Disc;
  40443. }(_Primitive));
  40444. Primitives.Disc = Disc;
  40445. var Cylinder = (function (_super) {
  40446. __extends(Cylinder, _super);
  40447. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  40448. if (subdivisions === void 0) { subdivisions = 1; }
  40449. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40450. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40451. _this.height = height;
  40452. _this.diameterTop = diameterTop;
  40453. _this.diameterBottom = diameterBottom;
  40454. _this.tessellation = tessellation;
  40455. _this.subdivisions = subdivisions;
  40456. _this.side = side;
  40457. return _this;
  40458. }
  40459. Cylinder.prototype._regenerateVertexData = function () {
  40460. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40461. };
  40462. Cylinder.prototype.copy = function (id) {
  40463. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40464. };
  40465. Cylinder.prototype.serialize = function () {
  40466. var serializationObject = _super.prototype.serialize.call(this);
  40467. serializationObject.height = this.height;
  40468. serializationObject.diameterTop = this.diameterTop;
  40469. serializationObject.diameterBottom = this.diameterBottom;
  40470. serializationObject.tessellation = this.tessellation;
  40471. return serializationObject;
  40472. };
  40473. Cylinder.Parse = function (parsedCylinder, scene) {
  40474. if (scene.getGeometryByID(parsedCylinder.id)) {
  40475. return null; // null since geometry could be something else than a cylinder...
  40476. }
  40477. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40478. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40479. scene.pushGeometry(cylinder, true);
  40480. return cylinder;
  40481. };
  40482. return Cylinder;
  40483. }(_Primitive));
  40484. Primitives.Cylinder = Cylinder;
  40485. var Torus = (function (_super) {
  40486. __extends(Torus, _super);
  40487. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  40488. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40489. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40490. _this.diameter = diameter;
  40491. _this.thickness = thickness;
  40492. _this.tessellation = tessellation;
  40493. _this.side = side;
  40494. return _this;
  40495. }
  40496. Torus.prototype._regenerateVertexData = function () {
  40497. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40498. };
  40499. Torus.prototype.copy = function (id) {
  40500. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40501. };
  40502. Torus.prototype.serialize = function () {
  40503. var serializationObject = _super.prototype.serialize.call(this);
  40504. serializationObject.diameter = this.diameter;
  40505. serializationObject.thickness = this.thickness;
  40506. serializationObject.tessellation = this.tessellation;
  40507. return serializationObject;
  40508. };
  40509. Torus.Parse = function (parsedTorus, scene) {
  40510. if (scene.getGeometryByID(parsedTorus.id)) {
  40511. return null; // null since geometry could be something else than a torus...
  40512. }
  40513. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40514. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40515. scene.pushGeometry(torus, true);
  40516. return torus;
  40517. };
  40518. return Torus;
  40519. }(_Primitive));
  40520. Primitives.Torus = Torus;
  40521. var Ground = (function (_super) {
  40522. __extends(Ground, _super);
  40523. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  40524. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40525. _this.width = width;
  40526. _this.height = height;
  40527. _this.subdivisions = subdivisions;
  40528. return _this;
  40529. }
  40530. Ground.prototype._regenerateVertexData = function () {
  40531. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40532. };
  40533. Ground.prototype.copy = function (id) {
  40534. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40535. };
  40536. Ground.prototype.serialize = function () {
  40537. var serializationObject = _super.prototype.serialize.call(this);
  40538. serializationObject.width = this.width;
  40539. serializationObject.height = this.height;
  40540. serializationObject.subdivisions = this.subdivisions;
  40541. return serializationObject;
  40542. };
  40543. Ground.Parse = function (parsedGround, scene) {
  40544. if (scene.getGeometryByID(parsedGround.id)) {
  40545. return null; // null since geometry could be something else than a ground...
  40546. }
  40547. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40548. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40549. scene.pushGeometry(ground, true);
  40550. return ground;
  40551. };
  40552. return Ground;
  40553. }(_Primitive));
  40554. Primitives.Ground = Ground;
  40555. var TiledGround = (function (_super) {
  40556. __extends(TiledGround, _super);
  40557. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  40558. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40559. _this.xmin = xmin;
  40560. _this.zmin = zmin;
  40561. _this.xmax = xmax;
  40562. _this.zmax = zmax;
  40563. _this.subdivisions = subdivisions;
  40564. _this.precision = precision;
  40565. return _this;
  40566. }
  40567. TiledGround.prototype._regenerateVertexData = function () {
  40568. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40569. };
  40570. TiledGround.prototype.copy = function (id) {
  40571. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40572. };
  40573. return TiledGround;
  40574. }(_Primitive));
  40575. Primitives.TiledGround = TiledGround;
  40576. var Plane = (function (_super) {
  40577. __extends(Plane, _super);
  40578. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  40579. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40580. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40581. _this.size = size;
  40582. _this.side = side;
  40583. return _this;
  40584. }
  40585. Plane.prototype._regenerateVertexData = function () {
  40586. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40587. };
  40588. Plane.prototype.copy = function (id) {
  40589. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40590. };
  40591. Plane.prototype.serialize = function () {
  40592. var serializationObject = _super.prototype.serialize.call(this);
  40593. serializationObject.size = this.size;
  40594. return serializationObject;
  40595. };
  40596. Plane.Parse = function (parsedPlane, scene) {
  40597. if (scene.getGeometryByID(parsedPlane.id)) {
  40598. return null; // null since geometry could be something else than a ground...
  40599. }
  40600. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40601. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40602. scene.pushGeometry(plane, true);
  40603. return plane;
  40604. };
  40605. return Plane;
  40606. }(_Primitive));
  40607. Primitives.Plane = Plane;
  40608. var TorusKnot = (function (_super) {
  40609. __extends(TorusKnot, _super);
  40610. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  40611. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40612. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40613. _this.radius = radius;
  40614. _this.tube = tube;
  40615. _this.radialSegments = radialSegments;
  40616. _this.tubularSegments = tubularSegments;
  40617. _this.p = p;
  40618. _this.q = q;
  40619. _this.side = side;
  40620. return _this;
  40621. }
  40622. TorusKnot.prototype._regenerateVertexData = function () {
  40623. 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 });
  40624. };
  40625. TorusKnot.prototype.copy = function (id) {
  40626. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40627. };
  40628. TorusKnot.prototype.serialize = function () {
  40629. var serializationObject = _super.prototype.serialize.call(this);
  40630. serializationObject.radius = this.radius;
  40631. serializationObject.tube = this.tube;
  40632. serializationObject.radialSegments = this.radialSegments;
  40633. serializationObject.tubularSegments = this.tubularSegments;
  40634. serializationObject.p = this.p;
  40635. serializationObject.q = this.q;
  40636. return serializationObject;
  40637. };
  40638. ;
  40639. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  40640. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40641. return null; // null since geometry could be something else than a ground...
  40642. }
  40643. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40644. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40645. scene.pushGeometry(torusKnot, true);
  40646. return torusKnot;
  40647. };
  40648. return TorusKnot;
  40649. }(_Primitive));
  40650. Primitives.TorusKnot = TorusKnot;
  40651. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  40652. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  40653. })(BABYLON || (BABYLON = {}));
  40654. //# sourceMappingURL=babylon.geometry.js.map
  40655. /// <reference path="babylon.mesh.ts" />
  40656. var BABYLON;
  40657. (function (BABYLON) {
  40658. var GroundMesh = (function (_super) {
  40659. __extends(GroundMesh, _super);
  40660. function GroundMesh(name, scene) {
  40661. var _this = _super.call(this, name, scene) || this;
  40662. _this.generateOctree = false;
  40663. _this._worldInverse = new BABYLON.Matrix();
  40664. return _this;
  40665. }
  40666. GroundMesh.prototype.getClassName = function () {
  40667. return "GroundMesh";
  40668. };
  40669. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  40670. get: function () {
  40671. return Math.min(this._subdivisionsX, this._subdivisionsY);
  40672. },
  40673. enumerable: true,
  40674. configurable: true
  40675. });
  40676. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  40677. get: function () {
  40678. return this._subdivisionsX;
  40679. },
  40680. enumerable: true,
  40681. configurable: true
  40682. });
  40683. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  40684. get: function () {
  40685. return this._subdivisionsY;
  40686. },
  40687. enumerable: true,
  40688. configurable: true
  40689. });
  40690. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  40691. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  40692. this._subdivisionsX = chunksCount;
  40693. this._subdivisionsY = chunksCount;
  40694. this.subdivide(chunksCount);
  40695. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  40696. };
  40697. /**
  40698. * Returns a height (y) value in the Worl system :
  40699. * the ground altitude at the coordinates (x, z) expressed in the World system.
  40700. * Returns the ground y position if (x, z) are outside the ground surface.
  40701. */
  40702. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  40703. var world = this.getWorldMatrix();
  40704. var invMat = BABYLON.Tmp.Matrix[5];
  40705. world.invertToRef(invMat);
  40706. var tmpVect = BABYLON.Tmp.Vector3[8];
  40707. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  40708. x = tmpVect.x;
  40709. z = tmpVect.z;
  40710. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  40711. return this.position.y;
  40712. }
  40713. if (!this._heightQuads || this._heightQuads.length == 0) {
  40714. this._initHeightQuads();
  40715. this._computeHeightQuads();
  40716. }
  40717. var facet = this._getFacetAt(x, z);
  40718. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  40719. // return y in the World system
  40720. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  40721. return tmpVect.y;
  40722. };
  40723. /**
  40724. * Returns a normalized vector (Vector3) orthogonal to the ground
  40725. * at the ground coordinates (x, z) expressed in the World system.
  40726. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  40727. */
  40728. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  40729. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  40730. this.getNormalAtCoordinatesToRef(x, z, normal);
  40731. return normal;
  40732. };
  40733. /**
  40734. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  40735. * at the ground coordinates (x, z) expressed in the World system.
  40736. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  40737. * Returns the GroundMesh.
  40738. */
  40739. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  40740. var world = this.getWorldMatrix();
  40741. var tmpMat = BABYLON.Tmp.Matrix[5];
  40742. world.invertToRef(tmpMat);
  40743. var tmpVect = BABYLON.Tmp.Vector3[8];
  40744. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  40745. x = tmpVect.x;
  40746. z = tmpVect.z;
  40747. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  40748. return this;
  40749. }
  40750. if (!this._heightQuads || this._heightQuads.length == 0) {
  40751. this._initHeightQuads();
  40752. this._computeHeightQuads();
  40753. }
  40754. var facet = this._getFacetAt(x, z);
  40755. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  40756. return this;
  40757. };
  40758. /**
  40759. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  40760. * if the ground has been updated.
  40761. * This can be used in the render loop.
  40762. * Returns the GroundMesh.
  40763. */
  40764. GroundMesh.prototype.updateCoordinateHeights = function () {
  40765. if (!this._heightQuads || this._heightQuads.length == 0) {
  40766. this._initHeightQuads();
  40767. }
  40768. this._computeHeightQuads();
  40769. return this;
  40770. };
  40771. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  40772. GroundMesh.prototype._getFacetAt = function (x, z) {
  40773. // retrieve col and row from x, z coordinates in the ground local system
  40774. var subdivisionsX = this._subdivisionsX;
  40775. var subdivisionsY = this._subdivisionsY;
  40776. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  40777. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  40778. var quad = this._heightQuads[row * this._subdivisionsX + col];
  40779. var facet;
  40780. if (z < quad.slope.x * x + quad.slope.y) {
  40781. facet = quad.facet1;
  40782. }
  40783. else {
  40784. facet = quad.facet2;
  40785. }
  40786. return facet;
  40787. };
  40788. // Creates and populates the heightMap array with "facet" elements :
  40789. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  40790. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  40791. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  40792. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  40793. // Returns the GroundMesh.
  40794. GroundMesh.prototype._initHeightQuads = function () {
  40795. var subdivisionsX = this._subdivisionsX;
  40796. var subdivisionsY = this._subdivisionsY;
  40797. this._heightQuads = new Array();
  40798. for (var row = 0; row < subdivisionsY; row++) {
  40799. for (var col = 0; col < subdivisionsX; col++) {
  40800. 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) };
  40801. this._heightQuads[row * subdivisionsX + col] = quad;
  40802. }
  40803. }
  40804. return this;
  40805. };
  40806. // Compute each quad element values and update the the heightMap array :
  40807. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  40808. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  40809. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  40810. // Returns the GroundMesh.
  40811. GroundMesh.prototype._computeHeightQuads = function () {
  40812. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40813. var v1 = BABYLON.Tmp.Vector3[3];
  40814. var v2 = BABYLON.Tmp.Vector3[2];
  40815. var v3 = BABYLON.Tmp.Vector3[1];
  40816. var v4 = BABYLON.Tmp.Vector3[0];
  40817. var v1v2 = BABYLON.Tmp.Vector3[4];
  40818. var v1v3 = BABYLON.Tmp.Vector3[5];
  40819. var v1v4 = BABYLON.Tmp.Vector3[6];
  40820. var norm1 = BABYLON.Tmp.Vector3[7];
  40821. var norm2 = BABYLON.Tmp.Vector3[8];
  40822. var i = 0;
  40823. var j = 0;
  40824. var k = 0;
  40825. var cd = 0; // 2D slope coefficient : z = cd * x + h
  40826. var h = 0;
  40827. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  40828. var d2 = 0;
  40829. var subdivisionsX = this._subdivisionsX;
  40830. var subdivisionsY = this._subdivisionsY;
  40831. for (var row = 0; row < subdivisionsY; row++) {
  40832. for (var col = 0; col < subdivisionsX; col++) {
  40833. i = col * 3;
  40834. j = row * (subdivisionsX + 1) * 3;
  40835. k = (row + 1) * (subdivisionsX + 1) * 3;
  40836. v1.x = positions[j + i];
  40837. v1.y = positions[j + i + 1];
  40838. v1.z = positions[j + i + 2];
  40839. v2.x = positions[j + i + 3];
  40840. v2.y = positions[j + i + 4];
  40841. v2.z = positions[j + i + 5];
  40842. v3.x = positions[k + i];
  40843. v3.y = positions[k + i + 1];
  40844. v3.z = positions[k + i + 2];
  40845. v4.x = positions[k + i + 3];
  40846. v4.y = positions[k + i + 4];
  40847. v4.z = positions[k + i + 5];
  40848. // 2D slope V1V4
  40849. cd = (v4.z - v1.z) / (v4.x - v1.x);
  40850. h = v1.z - cd * v1.x; // v1 belongs to the slope
  40851. // facet equations :
  40852. // we compute each facet normal vector
  40853. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  40854. // we compute the value d by applying the equation to v1 which belongs to the plane
  40855. // then we store the facet equation in a Vector4
  40856. v2.subtractToRef(v1, v1v2);
  40857. v3.subtractToRef(v1, v1v3);
  40858. v4.subtractToRef(v1, v1v4);
  40859. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  40860. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  40861. norm1.normalize();
  40862. norm2.normalize();
  40863. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  40864. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  40865. var quad = this._heightQuads[row * subdivisionsX + col];
  40866. quad.slope.copyFromFloats(cd, h);
  40867. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  40868. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  40869. }
  40870. }
  40871. return this;
  40872. };
  40873. return GroundMesh;
  40874. }(BABYLON.Mesh));
  40875. BABYLON.GroundMesh = GroundMesh;
  40876. })(BABYLON || (BABYLON = {}));
  40877. //# sourceMappingURL=babylon.groundMesh.js.map
  40878. /// <reference path="babylon.mesh.ts" />
  40879. var BABYLON;
  40880. (function (BABYLON) {
  40881. var LinesMesh = (function (_super) {
  40882. __extends(LinesMesh, _super);
  40883. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  40884. if (parent === void 0) { parent = null; }
  40885. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  40886. _this.color = new BABYLON.Color3(1, 1, 1);
  40887. _this.alpha = 1;
  40888. _this._positionBuffer = {};
  40889. if (source) {
  40890. _this.color = source.color.clone();
  40891. _this.alpha = source.alpha;
  40892. }
  40893. _this._intersectionThreshold = 0.1;
  40894. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  40895. attributes: [BABYLON.VertexBuffer.PositionKind],
  40896. uniforms: ["worldViewProjection", "color"],
  40897. needAlphaBlending: true
  40898. });
  40899. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  40900. return _this;
  40901. }
  40902. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  40903. /**
  40904. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  40905. * This margin is expressed in world space coordinates, so its value may vary.
  40906. * Default value is 0.1
  40907. * @returns the intersection Threshold value.
  40908. */
  40909. get: function () {
  40910. return this._intersectionThreshold;
  40911. },
  40912. /**
  40913. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  40914. * This margin is expressed in world space coordinates, so its value may vary.
  40915. * @param value the new threshold to apply
  40916. */
  40917. set: function (value) {
  40918. if (this._intersectionThreshold === value) {
  40919. return;
  40920. }
  40921. this._intersectionThreshold = value;
  40922. if (this.geometry) {
  40923. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  40924. }
  40925. },
  40926. enumerable: true,
  40927. configurable: true
  40928. });
  40929. /**
  40930. * Returns the string "LineMesh"
  40931. */
  40932. LinesMesh.prototype.getClassName = function () {
  40933. return "LinesMesh";
  40934. };
  40935. Object.defineProperty(LinesMesh.prototype, "material", {
  40936. get: function () {
  40937. return this._colorShader;
  40938. },
  40939. enumerable: true,
  40940. configurable: true
  40941. });
  40942. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  40943. get: function () {
  40944. return false;
  40945. },
  40946. enumerable: true,
  40947. configurable: true
  40948. });
  40949. LinesMesh.prototype.createInstance = function (name) {
  40950. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  40951. return null;
  40952. };
  40953. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  40954. var engine = this.getScene().getEngine();
  40955. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  40956. // VBOs
  40957. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  40958. // Color
  40959. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  40960. return this;
  40961. };
  40962. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  40963. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  40964. return this;
  40965. }
  40966. var engine = this.getScene().getEngine();
  40967. // Draw order
  40968. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  40969. return this;
  40970. };
  40971. LinesMesh.prototype.dispose = function (doNotRecurse) {
  40972. this._colorShader.dispose();
  40973. _super.prototype.dispose.call(this, doNotRecurse);
  40974. };
  40975. /**
  40976. * Returns a new LineMesh object cloned from the current one.
  40977. */
  40978. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  40979. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  40980. };
  40981. return LinesMesh;
  40982. }(BABYLON.Mesh));
  40983. BABYLON.LinesMesh = LinesMesh;
  40984. })(BABYLON || (BABYLON = {}));
  40985. //# sourceMappingURL=babylon.linesMesh.js.map
  40986. var BABYLON;
  40987. (function (BABYLON) {
  40988. var DefaultLoadingScreen = (function () {
  40989. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  40990. if (_loadingText === void 0) { _loadingText = ""; }
  40991. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  40992. var _this = this;
  40993. this._renderingCanvas = _renderingCanvas;
  40994. this._loadingText = _loadingText;
  40995. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  40996. // Resize
  40997. this._resizeLoadingUI = function () {
  40998. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  40999. _this._loadingDiv.style.position = "absolute";
  41000. _this._loadingDiv.style.left = canvasRect.left + "px";
  41001. _this._loadingDiv.style.top = canvasRect.top + "px";
  41002. _this._loadingDiv.style.width = canvasRect.width + "px";
  41003. _this._loadingDiv.style.height = canvasRect.height + "px";
  41004. };
  41005. }
  41006. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  41007. var _this = this;
  41008. if (this._loadingDiv) {
  41009. // Do not add a loading screen if there is already one
  41010. return;
  41011. }
  41012. this._loadingDiv = document.createElement("div");
  41013. this._loadingDiv.id = "babylonjsLoadingDiv";
  41014. this._loadingDiv.style.opacity = "0";
  41015. this._loadingDiv.style.transition = "opacity 1.5s ease";
  41016. // Loading text
  41017. this._loadingTextDiv = document.createElement("div");
  41018. this._loadingTextDiv.style.position = "absolute";
  41019. this._loadingTextDiv.style.left = "0";
  41020. this._loadingTextDiv.style.top = "50%";
  41021. this._loadingTextDiv.style.marginTop = "80px";
  41022. this._loadingTextDiv.style.width = "100%";
  41023. this._loadingTextDiv.style.height = "20px";
  41024. this._loadingTextDiv.style.fontFamily = "Arial";
  41025. this._loadingTextDiv.style.fontSize = "14px";
  41026. this._loadingTextDiv.style.color = "white";
  41027. this._loadingTextDiv.style.textAlign = "center";
  41028. this._loadingTextDiv.innerHTML = "Loading";
  41029. this._loadingDiv.appendChild(this._loadingTextDiv);
  41030. //set the predefined text
  41031. this._loadingTextDiv.innerHTML = this._loadingText;
  41032. // Loading img
  41033. var imgBack = new Image();
  41034. 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==";
  41035. imgBack.style.position = "absolute";
  41036. imgBack.style.left = "50%";
  41037. imgBack.style.top = "50%";
  41038. imgBack.style.marginLeft = "-50px";
  41039. imgBack.style.marginTop = "-50px";
  41040. imgBack.style.transition = "transform 1.0s ease";
  41041. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  41042. var deg = 360;
  41043. var onTransitionEnd = function () {
  41044. deg += 360;
  41045. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  41046. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  41047. };
  41048. imgBack.addEventListener("transitionend", onTransitionEnd);
  41049. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  41050. this._loadingDiv.appendChild(imgBack);
  41051. // front image
  41052. var imgFront = new Image();
  41053. 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=";
  41054. imgFront.style.position = "absolute";
  41055. imgFront.style.left = "50%";
  41056. imgFront.style.top = "50%";
  41057. imgFront.style.marginLeft = "-50px";
  41058. imgFront.style.marginTop = "-50px";
  41059. this._loadingDiv.appendChild(imgFront);
  41060. this._resizeLoadingUI();
  41061. window.addEventListener("resize", this._resizeLoadingUI);
  41062. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  41063. document.body.appendChild(this._loadingDiv);
  41064. setTimeout(function () {
  41065. _this._loadingDiv.style.opacity = "1";
  41066. imgBack.style.transform = "rotateZ(360deg)";
  41067. imgBack.style.webkitTransform = "rotateZ(360deg)";
  41068. }, 0);
  41069. };
  41070. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  41071. var _this = this;
  41072. if (!this._loadingDiv) {
  41073. return;
  41074. }
  41075. var onTransitionEnd = function () {
  41076. if (!_this._loadingDiv) {
  41077. return;
  41078. }
  41079. document.body.removeChild(_this._loadingDiv);
  41080. window.removeEventListener("resize", _this._resizeLoadingUI);
  41081. _this._loadingDiv = null;
  41082. };
  41083. this._loadingDiv.style.opacity = "0";
  41084. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  41085. };
  41086. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  41087. set: function (text) {
  41088. this._loadingText = text;
  41089. if (this._loadingTextDiv) {
  41090. this._loadingTextDiv.innerHTML = this._loadingText;
  41091. }
  41092. },
  41093. enumerable: true,
  41094. configurable: true
  41095. });
  41096. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  41097. get: function () {
  41098. return this._loadingDivBackgroundColor;
  41099. },
  41100. set: function (color) {
  41101. this._loadingDivBackgroundColor = color;
  41102. if (!this._loadingDiv) {
  41103. return;
  41104. }
  41105. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  41106. },
  41107. enumerable: true,
  41108. configurable: true
  41109. });
  41110. return DefaultLoadingScreen;
  41111. }());
  41112. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  41113. })(BABYLON || (BABYLON = {}));
  41114. //# sourceMappingURL=babylon.loadingScreen.js.map
  41115. var BABYLON;
  41116. (function (BABYLON) {
  41117. var AudioEngine = (function () {
  41118. function AudioEngine() {
  41119. this._audioContext = null;
  41120. this._audioContextInitialized = false;
  41121. this.canUseWebAudio = false;
  41122. this.WarnedWebAudioUnsupported = false;
  41123. this.unlocked = false;
  41124. this.isMP3supported = false;
  41125. this.isOGGsupported = false;
  41126. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  41127. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  41128. this.canUseWebAudio = true;
  41129. }
  41130. var audioElem = document.createElement('audio');
  41131. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  41132. this.isMP3supported = true;
  41133. }
  41134. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  41135. this.isOGGsupported = true;
  41136. }
  41137. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  41138. this._unlockiOSaudio();
  41139. }
  41140. else {
  41141. this.unlocked = true;
  41142. }
  41143. }
  41144. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  41145. get: function () {
  41146. if (!this._audioContextInitialized) {
  41147. this._initializeAudioContext();
  41148. }
  41149. return this._audioContext;
  41150. },
  41151. enumerable: true,
  41152. configurable: true
  41153. });
  41154. AudioEngine.prototype._unlockiOSaudio = function () {
  41155. var _this = this;
  41156. var unlockaudio = function () {
  41157. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  41158. var source = _this.audioContext.createBufferSource();
  41159. source.buffer = buffer;
  41160. source.connect(_this.audioContext.destination);
  41161. source.start(0);
  41162. setTimeout(function () {
  41163. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  41164. _this.unlocked = true;
  41165. window.removeEventListener('touchend', unlockaudio, false);
  41166. if (_this.onAudioUnlocked) {
  41167. _this.onAudioUnlocked();
  41168. }
  41169. }
  41170. }, 0);
  41171. };
  41172. window.addEventListener('touchend', unlockaudio, false);
  41173. };
  41174. AudioEngine.prototype._initializeAudioContext = function () {
  41175. try {
  41176. if (this.canUseWebAudio) {
  41177. this._audioContext = new AudioContext();
  41178. // create a global volume gain node
  41179. this.masterGain = this._audioContext.createGain();
  41180. this.masterGain.gain.value = 1;
  41181. this.masterGain.connect(this._audioContext.destination);
  41182. this._audioContextInitialized = true;
  41183. }
  41184. }
  41185. catch (e) {
  41186. this.canUseWebAudio = false;
  41187. BABYLON.Tools.Error("Web Audio: " + e.message);
  41188. }
  41189. };
  41190. AudioEngine.prototype.dispose = function () {
  41191. if (this.canUseWebAudio && this._audioContextInitialized) {
  41192. if (this._connectedAnalyser) {
  41193. this._connectedAnalyser.stopDebugCanvas();
  41194. this._connectedAnalyser.dispose();
  41195. this.masterGain.disconnect();
  41196. this.masterGain.connect(this._audioContext.destination);
  41197. this._connectedAnalyser = null;
  41198. }
  41199. this.masterGain.gain.value = 1;
  41200. }
  41201. this.WarnedWebAudioUnsupported = false;
  41202. };
  41203. AudioEngine.prototype.getGlobalVolume = function () {
  41204. if (this.canUseWebAudio && this._audioContextInitialized) {
  41205. return this.masterGain.gain.value;
  41206. }
  41207. else {
  41208. return -1;
  41209. }
  41210. };
  41211. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  41212. if (this.canUseWebAudio && this._audioContextInitialized) {
  41213. this.masterGain.gain.value = newVolume;
  41214. }
  41215. };
  41216. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  41217. if (this._connectedAnalyser) {
  41218. this._connectedAnalyser.stopDebugCanvas();
  41219. }
  41220. if (this.canUseWebAudio && this._audioContextInitialized) {
  41221. this._connectedAnalyser = analyser;
  41222. this.masterGain.disconnect();
  41223. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  41224. }
  41225. };
  41226. return AudioEngine;
  41227. }());
  41228. BABYLON.AudioEngine = AudioEngine;
  41229. })(BABYLON || (BABYLON = {}));
  41230. //# sourceMappingURL=babylon.audioEngine.js.map
  41231. var BABYLON;
  41232. (function (BABYLON) {
  41233. var Sound = (function () {
  41234. /**
  41235. * Create a sound and attach it to a scene
  41236. * @param name Name of your sound
  41237. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  41238. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  41239. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  41240. */
  41241. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  41242. var _this = this;
  41243. this.autoplay = false;
  41244. this.loop = false;
  41245. this.useCustomAttenuation = false;
  41246. this.spatialSound = false;
  41247. this.refDistance = 1;
  41248. this.rolloffFactor = 1;
  41249. this.maxDistance = 100;
  41250. this.distanceModel = "linear";
  41251. this._panningModel = "equalpower";
  41252. this._playbackRate = 1;
  41253. this._streaming = false;
  41254. this._startTime = 0;
  41255. this._startOffset = 0;
  41256. this._position = BABYLON.Vector3.Zero();
  41257. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  41258. this._volume = 1;
  41259. this._isLoaded = false;
  41260. this._isReadyToPlay = false;
  41261. this.isPlaying = false;
  41262. this.isPaused = false;
  41263. this._isDirectional = false;
  41264. // Used if you'd like to create a directional sound.
  41265. // If not set, the sound will be omnidirectional
  41266. this._coneInnerAngle = 360;
  41267. this._coneOuterAngle = 360;
  41268. this._coneOuterGain = 0;
  41269. this._isOutputConnected = false;
  41270. this._urlType = "Unknown";
  41271. this.name = name;
  41272. this._scene = scene;
  41273. this._readyToPlayCallback = readyToPlayCallback;
  41274. // Default custom attenuation function is a linear attenuation
  41275. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  41276. if (currentDistance < maxDistance) {
  41277. return currentVolume * (1 - currentDistance / maxDistance);
  41278. }
  41279. else {
  41280. return 0;
  41281. }
  41282. };
  41283. if (options) {
  41284. this.autoplay = options.autoplay || false;
  41285. this.loop = options.loop || false;
  41286. // if volume === 0, we need another way to check this option
  41287. if (options.volume !== undefined) {
  41288. this._volume = options.volume;
  41289. }
  41290. this.spatialSound = options.spatialSound || false;
  41291. this.maxDistance = options.maxDistance || 100;
  41292. this.useCustomAttenuation = options.useCustomAttenuation || false;
  41293. this.rolloffFactor = options.rolloffFactor || 1;
  41294. this.refDistance = options.refDistance || 1;
  41295. this.distanceModel = options.distanceModel || "linear";
  41296. this._playbackRate = options.playbackRate || 1;
  41297. this._streaming = options.streaming || false;
  41298. }
  41299. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41300. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  41301. this._soundGain.gain.value = this._volume;
  41302. this._inputAudioNode = this._soundGain;
  41303. this._ouputAudioNode = this._soundGain;
  41304. if (this.spatialSound) {
  41305. this._createSpatialParameters();
  41306. }
  41307. this._scene.mainSoundTrack.AddSound(this);
  41308. var validParameter = true;
  41309. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  41310. if (urlOrArrayBuffer) {
  41311. if (typeof (urlOrArrayBuffer) === "string")
  41312. this._urlType = "String";
  41313. if (Array.isArray(urlOrArrayBuffer))
  41314. this._urlType = "Array";
  41315. if (urlOrArrayBuffer instanceof ArrayBuffer)
  41316. this._urlType = "ArrayBuffer";
  41317. var urls = [];
  41318. var codecSupportedFound = false;
  41319. switch (this._urlType) {
  41320. case "ArrayBuffer":
  41321. if (urlOrArrayBuffer.byteLength > 0) {
  41322. codecSupportedFound = true;
  41323. this._soundLoaded(urlOrArrayBuffer);
  41324. }
  41325. break;
  41326. case "String":
  41327. urls.push(urlOrArrayBuffer);
  41328. case "Array":
  41329. if (urls.length === 0)
  41330. urls = urlOrArrayBuffer;
  41331. // If we found a supported format, we load it immediately and stop the loop
  41332. for (var i = 0; i < urls.length; i++) {
  41333. var url = urls[i];
  41334. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  41335. codecSupportedFound = true;
  41336. }
  41337. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  41338. codecSupportedFound = true;
  41339. }
  41340. if (url.indexOf(".wav", url.length - 4) !== -1) {
  41341. codecSupportedFound = true;
  41342. }
  41343. if (codecSupportedFound) {
  41344. // Loading sound using XHR2
  41345. if (!this._streaming) {
  41346. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  41347. }
  41348. else {
  41349. this._htmlAudioElement = new Audio(url);
  41350. this._htmlAudioElement.controls = false;
  41351. this._htmlAudioElement.loop = this.loop;
  41352. this._htmlAudioElement.crossOrigin = "anonymous";
  41353. this._htmlAudioElement.preload = "auto";
  41354. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  41355. _this._isReadyToPlay = true;
  41356. if (_this.autoplay) {
  41357. _this.play();
  41358. }
  41359. if (_this._readyToPlayCallback) {
  41360. _this._readyToPlayCallback();
  41361. }
  41362. });
  41363. document.body.appendChild(this._htmlAudioElement);
  41364. }
  41365. break;
  41366. }
  41367. }
  41368. break;
  41369. default:
  41370. validParameter = false;
  41371. break;
  41372. }
  41373. if (!validParameter) {
  41374. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  41375. }
  41376. else {
  41377. if (!codecSupportedFound) {
  41378. this._isReadyToPlay = true;
  41379. // Simulating a ready to play event to avoid breaking code path
  41380. if (this._readyToPlayCallback) {
  41381. window.setTimeout(function () {
  41382. _this._readyToPlayCallback();
  41383. }, 1000);
  41384. }
  41385. }
  41386. }
  41387. }
  41388. }
  41389. else {
  41390. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  41391. this._scene.mainSoundTrack.AddSound(this);
  41392. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  41393. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  41394. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  41395. }
  41396. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  41397. if (this._readyToPlayCallback) {
  41398. window.setTimeout(function () {
  41399. _this._readyToPlayCallback();
  41400. }, 1000);
  41401. }
  41402. }
  41403. }
  41404. Sound.prototype.dispose = function () {
  41405. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  41406. if (this.isPlaying) {
  41407. this.stop();
  41408. }
  41409. this._isReadyToPlay = false;
  41410. if (this.soundTrackId === -1) {
  41411. this._scene.mainSoundTrack.RemoveSound(this);
  41412. }
  41413. else {
  41414. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  41415. }
  41416. if (this._soundGain) {
  41417. this._soundGain.disconnect();
  41418. this._soundGain = null;
  41419. }
  41420. if (this._soundPanner) {
  41421. this._soundPanner.disconnect();
  41422. this._soundPanner = null;
  41423. }
  41424. if (this._soundSource) {
  41425. this._soundSource.disconnect();
  41426. this._soundSource = null;
  41427. }
  41428. this._audioBuffer = null;
  41429. if (this._htmlAudioElement) {
  41430. this._htmlAudioElement.pause();
  41431. this._htmlAudioElement.src = "";
  41432. document.body.removeChild(this._htmlAudioElement);
  41433. }
  41434. if (this._connectedMesh) {
  41435. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  41436. this._connectedMesh = null;
  41437. }
  41438. }
  41439. };
  41440. Sound.prototype.isReady = function () {
  41441. return this._isReadyToPlay;
  41442. };
  41443. Sound.prototype._soundLoaded = function (audioData) {
  41444. var _this = this;
  41445. this._isLoaded = true;
  41446. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  41447. _this._audioBuffer = buffer;
  41448. _this._isReadyToPlay = true;
  41449. if (_this.autoplay) {
  41450. _this.play();
  41451. }
  41452. if (_this._readyToPlayCallback) {
  41453. _this._readyToPlayCallback();
  41454. }
  41455. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  41456. };
  41457. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  41458. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41459. this._audioBuffer = audioBuffer;
  41460. this._isReadyToPlay = true;
  41461. }
  41462. };
  41463. Sound.prototype.updateOptions = function (options) {
  41464. if (options) {
  41465. this.loop = options.loop || this.loop;
  41466. this.maxDistance = options.maxDistance || this.maxDistance;
  41467. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  41468. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  41469. this.refDistance = options.refDistance || this.refDistance;
  41470. this.distanceModel = options.distanceModel || this.distanceModel;
  41471. this._playbackRate = options.playbackRate || this._playbackRate;
  41472. this._updateSpatialParameters();
  41473. if (this.isPlaying) {
  41474. if (this._streaming) {
  41475. this._htmlAudioElement.playbackRate = this._playbackRate;
  41476. }
  41477. else {
  41478. this._soundSource.playbackRate.value = this._playbackRate;
  41479. }
  41480. }
  41481. }
  41482. };
  41483. Sound.prototype._createSpatialParameters = function () {
  41484. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41485. if (this._scene.headphone) {
  41486. this._panningModel = "HRTF";
  41487. }
  41488. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  41489. this._updateSpatialParameters();
  41490. this._soundPanner.connect(this._ouputAudioNode);
  41491. this._inputAudioNode = this._soundPanner;
  41492. }
  41493. };
  41494. Sound.prototype._updateSpatialParameters = function () {
  41495. if (this.spatialSound) {
  41496. if (this.useCustomAttenuation) {
  41497. // Tricks to disable in a way embedded Web Audio attenuation
  41498. this._soundPanner.distanceModel = "linear";
  41499. this._soundPanner.maxDistance = Number.MAX_VALUE;
  41500. this._soundPanner.refDistance = 1;
  41501. this._soundPanner.rolloffFactor = 1;
  41502. this._soundPanner.panningModel = this._panningModel;
  41503. }
  41504. else {
  41505. this._soundPanner.distanceModel = this.distanceModel;
  41506. this._soundPanner.maxDistance = this.maxDistance;
  41507. this._soundPanner.refDistance = this.refDistance;
  41508. this._soundPanner.rolloffFactor = this.rolloffFactor;
  41509. this._soundPanner.panningModel = this._panningModel;
  41510. }
  41511. }
  41512. };
  41513. Sound.prototype.switchPanningModelToHRTF = function () {
  41514. this._panningModel = "HRTF";
  41515. this._switchPanningModel();
  41516. };
  41517. Sound.prototype.switchPanningModelToEqualPower = function () {
  41518. this._panningModel = "equalpower";
  41519. this._switchPanningModel();
  41520. };
  41521. Sound.prototype._switchPanningModel = function () {
  41522. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  41523. this._soundPanner.panningModel = this._panningModel;
  41524. }
  41525. };
  41526. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  41527. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41528. if (this._isOutputConnected) {
  41529. this._ouputAudioNode.disconnect();
  41530. }
  41531. this._ouputAudioNode.connect(soundTrackAudioNode);
  41532. this._isOutputConnected = true;
  41533. }
  41534. };
  41535. /**
  41536. * Transform this sound into a directional source
  41537. * @param coneInnerAngle Size of the inner cone in degree
  41538. * @param coneOuterAngle Size of the outer cone in degree
  41539. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  41540. */
  41541. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  41542. if (coneOuterAngle < coneInnerAngle) {
  41543. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  41544. return;
  41545. }
  41546. this._coneInnerAngle = coneInnerAngle;
  41547. this._coneOuterAngle = coneOuterAngle;
  41548. this._coneOuterGain = coneOuterGain;
  41549. this._isDirectional = true;
  41550. if (this.isPlaying && this.loop) {
  41551. this.stop();
  41552. this.play();
  41553. }
  41554. };
  41555. Sound.prototype.setPosition = function (newPosition) {
  41556. this._position = newPosition;
  41557. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  41558. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  41559. }
  41560. };
  41561. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  41562. this._localDirection = newLocalDirection;
  41563. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  41564. this._updateDirection();
  41565. }
  41566. };
  41567. Sound.prototype._updateDirection = function () {
  41568. var mat = this._connectedMesh.getWorldMatrix();
  41569. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  41570. direction.normalize();
  41571. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  41572. };
  41573. Sound.prototype.updateDistanceFromListener = function () {
  41574. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  41575. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  41576. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  41577. }
  41578. };
  41579. Sound.prototype.setAttenuationFunction = function (callback) {
  41580. this._customAttenuationFunction = callback;
  41581. };
  41582. /**
  41583. * Play the sound
  41584. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  41585. * @param offset (optional) Start the sound setting it at a specific time
  41586. */
  41587. Sound.prototype.play = function (time, offset) {
  41588. var _this = this;
  41589. if (this._isReadyToPlay && this._scene.audioEnabled) {
  41590. try {
  41591. if (this._startOffset < 0) {
  41592. time = -this._startOffset;
  41593. this._startOffset = 0;
  41594. }
  41595. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  41596. if (!this._soundSource || !this._streamingSource) {
  41597. if (this.spatialSound) {
  41598. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  41599. if (this._isDirectional) {
  41600. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  41601. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  41602. this._soundPanner.coneOuterGain = this._coneOuterGain;
  41603. if (this._connectedMesh) {
  41604. this._updateDirection();
  41605. }
  41606. else {
  41607. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  41608. }
  41609. }
  41610. }
  41611. }
  41612. if (this._streaming) {
  41613. if (!this._streamingSource) {
  41614. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  41615. this._htmlAudioElement.onended = function () { _this._onended(); };
  41616. this._htmlAudioElement.playbackRate = this._playbackRate;
  41617. }
  41618. this._streamingSource.disconnect();
  41619. this._streamingSource.connect(this._inputAudioNode);
  41620. this._htmlAudioElement.play();
  41621. }
  41622. else {
  41623. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  41624. this._soundSource.buffer = this._audioBuffer;
  41625. this._soundSource.connect(this._inputAudioNode);
  41626. this._soundSource.loop = this.loop;
  41627. this._soundSource.playbackRate.value = this._playbackRate;
  41628. this._soundSource.onended = function () { _this._onended(); };
  41629. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  41630. }
  41631. this._startTime = startTime;
  41632. this.isPlaying = true;
  41633. this.isPaused = false;
  41634. }
  41635. catch (ex) {
  41636. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  41637. }
  41638. }
  41639. };
  41640. Sound.prototype._onended = function () {
  41641. this.isPlaying = false;
  41642. if (this.onended) {
  41643. this.onended();
  41644. }
  41645. };
  41646. /**
  41647. * Stop the sound
  41648. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  41649. */
  41650. Sound.prototype.stop = function (time) {
  41651. if (this.isPlaying) {
  41652. if (this._streaming) {
  41653. this._htmlAudioElement.pause();
  41654. // Test needed for Firefox or it will generate an Invalid State Error
  41655. if (this._htmlAudioElement.currentTime > 0) {
  41656. this._htmlAudioElement.currentTime = 0;
  41657. }
  41658. }
  41659. else {
  41660. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  41661. this._soundSource.stop(stopTime);
  41662. this._soundSource.onended = null;
  41663. if (!this.isPaused) {
  41664. this._startOffset = 0;
  41665. }
  41666. }
  41667. this.isPlaying = false;
  41668. }
  41669. };
  41670. Sound.prototype.pause = function () {
  41671. if (this.isPlaying) {
  41672. this.isPaused = true;
  41673. if (this._streaming) {
  41674. this._htmlAudioElement.pause();
  41675. }
  41676. else {
  41677. this.stop(0);
  41678. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  41679. }
  41680. }
  41681. };
  41682. Sound.prototype.setVolume = function (newVolume, time) {
  41683. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41684. if (time) {
  41685. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  41686. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  41687. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  41688. }
  41689. else {
  41690. this._soundGain.gain.value = newVolume;
  41691. }
  41692. }
  41693. this._volume = newVolume;
  41694. };
  41695. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  41696. this._playbackRate = newPlaybackRate;
  41697. if (this.isPlaying) {
  41698. if (this._streaming) {
  41699. this._htmlAudioElement.playbackRate = this._playbackRate;
  41700. }
  41701. else {
  41702. this._soundSource.playbackRate.value = this._playbackRate;
  41703. }
  41704. }
  41705. };
  41706. Sound.prototype.getVolume = function () {
  41707. return this._volume;
  41708. };
  41709. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  41710. var _this = this;
  41711. if (this._connectedMesh) {
  41712. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  41713. this._registerFunc = null;
  41714. }
  41715. this._connectedMesh = meshToConnectTo;
  41716. if (!this.spatialSound) {
  41717. this.spatialSound = true;
  41718. this._createSpatialParameters();
  41719. if (this.isPlaying && this.loop) {
  41720. this.stop();
  41721. this.play();
  41722. }
  41723. }
  41724. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  41725. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  41726. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  41727. };
  41728. Sound.prototype.detachFromMesh = function () {
  41729. if (this._connectedMesh) {
  41730. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  41731. this._registerFunc = null;
  41732. this._connectedMesh = null;
  41733. }
  41734. };
  41735. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  41736. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  41737. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  41738. this._updateDirection();
  41739. }
  41740. };
  41741. Sound.prototype.clone = function () {
  41742. var _this = this;
  41743. if (!this._streaming) {
  41744. var setBufferAndRun = function () {
  41745. if (_this._isReadyToPlay) {
  41746. clonedSound._audioBuffer = _this.getAudioBuffer();
  41747. clonedSound._isReadyToPlay = true;
  41748. if (clonedSound.autoplay) {
  41749. clonedSound.play();
  41750. }
  41751. }
  41752. else {
  41753. window.setTimeout(setBufferAndRun, 300);
  41754. }
  41755. };
  41756. var currentOptions = {
  41757. autoplay: this.autoplay, loop: this.loop,
  41758. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  41759. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  41760. refDistance: this.refDistance, distanceModel: this.distanceModel
  41761. };
  41762. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  41763. if (this.useCustomAttenuation) {
  41764. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  41765. }
  41766. clonedSound.setPosition(this._position);
  41767. clonedSound.setPlaybackRate(this._playbackRate);
  41768. setBufferAndRun();
  41769. return clonedSound;
  41770. }
  41771. else {
  41772. return null;
  41773. }
  41774. };
  41775. Sound.prototype.getAudioBuffer = function () {
  41776. return this._audioBuffer;
  41777. };
  41778. Sound.prototype.serialize = function () {
  41779. var serializationObject = {
  41780. name: this.name,
  41781. url: this.name,
  41782. autoplay: this.autoplay,
  41783. loop: this.loop,
  41784. volume: this._volume,
  41785. spatialSound: this.spatialSound,
  41786. maxDistance: this.maxDistance,
  41787. rolloffFactor: this.rolloffFactor,
  41788. refDistance: this.refDistance,
  41789. distanceModel: this.distanceModel,
  41790. playbackRate: this._playbackRate,
  41791. panningModel: this._panningModel,
  41792. soundTrackId: this.soundTrackId
  41793. };
  41794. if (this.spatialSound) {
  41795. if (this._connectedMesh)
  41796. serializationObject.connectedMeshId = this._connectedMesh.id;
  41797. serializationObject.position = this._position.asArray();
  41798. serializationObject.refDistance = this.refDistance;
  41799. serializationObject.distanceModel = this.distanceModel;
  41800. serializationObject.isDirectional = this._isDirectional;
  41801. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  41802. serializationObject.coneInnerAngle = this._coneInnerAngle;
  41803. serializationObject.coneOuterAngle = this._coneOuterAngle;
  41804. serializationObject.coneOuterGain = this._coneOuterGain;
  41805. }
  41806. return serializationObject;
  41807. };
  41808. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  41809. var soundName = parsedSound.name;
  41810. var soundUrl;
  41811. if (parsedSound.url) {
  41812. soundUrl = rootUrl + parsedSound.url;
  41813. }
  41814. else {
  41815. soundUrl = rootUrl + soundName;
  41816. }
  41817. var options = {
  41818. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  41819. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  41820. rolloffFactor: parsedSound.rolloffFactor,
  41821. refDistance: parsedSound.refDistance,
  41822. distanceModel: parsedSound.distanceModel,
  41823. playbackRate: parsedSound.playbackRate
  41824. };
  41825. var newSound;
  41826. if (!sourceSound) {
  41827. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  41828. scene._addPendingData(newSound);
  41829. }
  41830. else {
  41831. var setBufferAndRun = function () {
  41832. if (sourceSound._isReadyToPlay) {
  41833. newSound._audioBuffer = sourceSound.getAudioBuffer();
  41834. newSound._isReadyToPlay = true;
  41835. if (newSound.autoplay) {
  41836. newSound.play();
  41837. }
  41838. }
  41839. else {
  41840. window.setTimeout(setBufferAndRun, 300);
  41841. }
  41842. };
  41843. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  41844. setBufferAndRun();
  41845. }
  41846. if (parsedSound.position) {
  41847. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  41848. newSound.setPosition(soundPosition);
  41849. }
  41850. if (parsedSound.isDirectional) {
  41851. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  41852. if (parsedSound.localDirectionToMesh) {
  41853. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  41854. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  41855. }
  41856. }
  41857. if (parsedSound.connectedMeshId) {
  41858. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  41859. if (connectedMesh) {
  41860. newSound.attachToMesh(connectedMesh);
  41861. }
  41862. }
  41863. return newSound;
  41864. };
  41865. return Sound;
  41866. }());
  41867. BABYLON.Sound = Sound;
  41868. })(BABYLON || (BABYLON = {}));
  41869. //# sourceMappingURL=babylon.sound.js.map
  41870. var BABYLON;
  41871. (function (BABYLON) {
  41872. var SoundTrack = (function () {
  41873. function SoundTrack(scene, options) {
  41874. this.id = -1;
  41875. this._isMainTrack = false;
  41876. this._isInitialized = false;
  41877. this._scene = scene;
  41878. this.soundCollection = new Array();
  41879. this._options = options;
  41880. if (!this._isMainTrack) {
  41881. this._scene.soundTracks.push(this);
  41882. this.id = this._scene.soundTracks.length - 1;
  41883. }
  41884. }
  41885. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  41886. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41887. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  41888. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  41889. if (this._options) {
  41890. if (this._options.volume) {
  41891. this._outputAudioNode.gain.value = this._options.volume;
  41892. }
  41893. if (this._options.mainTrack) {
  41894. this._isMainTrack = this._options.mainTrack;
  41895. }
  41896. }
  41897. this._isInitialized = true;
  41898. }
  41899. };
  41900. SoundTrack.prototype.dispose = function () {
  41901. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41902. if (this._connectedAnalyser) {
  41903. this._connectedAnalyser.stopDebugCanvas();
  41904. }
  41905. while (this.soundCollection.length) {
  41906. this.soundCollection[0].dispose();
  41907. }
  41908. if (this._outputAudioNode) {
  41909. this._outputAudioNode.disconnect();
  41910. }
  41911. this._outputAudioNode = null;
  41912. }
  41913. };
  41914. SoundTrack.prototype.AddSound = function (sound) {
  41915. if (!this._isInitialized) {
  41916. this._initializeSoundTrackAudioGraph();
  41917. }
  41918. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41919. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  41920. }
  41921. if (sound.soundTrackId) {
  41922. if (sound.soundTrackId === -1) {
  41923. this._scene.mainSoundTrack.RemoveSound(sound);
  41924. }
  41925. else {
  41926. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  41927. }
  41928. }
  41929. this.soundCollection.push(sound);
  41930. sound.soundTrackId = this.id;
  41931. };
  41932. SoundTrack.prototype.RemoveSound = function (sound) {
  41933. var index = this.soundCollection.indexOf(sound);
  41934. if (index !== -1) {
  41935. this.soundCollection.splice(index, 1);
  41936. }
  41937. };
  41938. SoundTrack.prototype.setVolume = function (newVolume) {
  41939. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41940. this._outputAudioNode.gain.value = newVolume;
  41941. }
  41942. };
  41943. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  41944. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41945. for (var i = 0; i < this.soundCollection.length; i++) {
  41946. this.soundCollection[i].switchPanningModelToHRTF();
  41947. }
  41948. }
  41949. };
  41950. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  41951. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41952. for (var i = 0; i < this.soundCollection.length; i++) {
  41953. this.soundCollection[i].switchPanningModelToEqualPower();
  41954. }
  41955. }
  41956. };
  41957. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  41958. if (this._connectedAnalyser) {
  41959. this._connectedAnalyser.stopDebugCanvas();
  41960. }
  41961. this._connectedAnalyser = analyser;
  41962. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41963. this._outputAudioNode.disconnect();
  41964. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  41965. }
  41966. };
  41967. return SoundTrack;
  41968. }());
  41969. BABYLON.SoundTrack = SoundTrack;
  41970. })(BABYLON || (BABYLON = {}));
  41971. //# sourceMappingURL=babylon.soundtrack.js.map
  41972. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  41973. /// <reference path="..\Math\babylon.math.ts" />
  41974. var BABYLON;
  41975. (function (BABYLON) {
  41976. /**
  41977. * Special Glow Blur post process only blurring the alpha channel
  41978. * It enforces keeping the most luminous color in the color channel.
  41979. */
  41980. var GlowBlurPostProcess = (function (_super) {
  41981. __extends(GlowBlurPostProcess, _super);
  41982. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  41983. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  41984. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  41985. _this.direction = direction;
  41986. _this.blurWidth = blurWidth;
  41987. _this.onApplyObservable.add(function (effect) {
  41988. effect.setFloat2("screenSize", _this.width, _this.height);
  41989. effect.setVector2("direction", _this.direction);
  41990. effect.setFloat("blurWidth", _this.blurWidth);
  41991. });
  41992. return _this;
  41993. }
  41994. return GlowBlurPostProcess;
  41995. }(BABYLON.PostProcess));
  41996. /**
  41997. * The highlight layer Helps adding a glow effect around a mesh.
  41998. *
  41999. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  42000. * glowy meshes to your scene.
  42001. *
  42002. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  42003. */
  42004. var HighlightLayer = (function () {
  42005. /**
  42006. * Instantiates a new highlight Layer and references it to the scene..
  42007. * @param name The name of the layer
  42008. * @param scene The scene to use the layer in
  42009. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  42010. */
  42011. function HighlightLayer(name, scene, options) {
  42012. this._vertexBuffers = {};
  42013. this._mainTextureDesiredSize = { width: 0, height: 0 };
  42014. this._meshes = {};
  42015. this._maxSize = 0;
  42016. this._shouldRender = false;
  42017. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  42018. this._excludedMeshes = {};
  42019. /**
  42020. * Specifies whether or not the inner glow is ACTIVE in the layer.
  42021. */
  42022. this.innerGlow = true;
  42023. /**
  42024. * Specifies whether or not the outer glow is ACTIVE in the layer.
  42025. */
  42026. this.outerGlow = true;
  42027. /**
  42028. * Specifies wether the highlight layer is enabled or not.
  42029. */
  42030. this.isEnabled = true;
  42031. /**
  42032. * An event triggered when the highlight layer has been disposed.
  42033. * @type {BABYLON.Observable}
  42034. */
  42035. this.onDisposeObservable = new BABYLON.Observable();
  42036. /**
  42037. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  42038. * @type {BABYLON.Observable}
  42039. */
  42040. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  42041. /**
  42042. * An event triggered when the highlight layer is being blurred.
  42043. * @type {BABYLON.Observable}
  42044. */
  42045. this.onBeforeBlurObservable = new BABYLON.Observable();
  42046. /**
  42047. * An event triggered when the highlight layer has been blurred.
  42048. * @type {BABYLON.Observable}
  42049. */
  42050. this.onAfterBlurObservable = new BABYLON.Observable();
  42051. /**
  42052. * An event triggered when the glowing blurred texture is being merged in the scene.
  42053. * @type {BABYLON.Observable}
  42054. */
  42055. this.onBeforeComposeObservable = new BABYLON.Observable();
  42056. /**
  42057. * An event triggered when the glowing blurred texture has been merged in the scene.
  42058. * @type {BABYLON.Observable}
  42059. */
  42060. this.onAfterComposeObservable = new BABYLON.Observable();
  42061. /**
  42062. * An event triggered when the highlight layer changes its size.
  42063. * @type {BABYLON.Observable}
  42064. */
  42065. this.onSizeChangedObservable = new BABYLON.Observable();
  42066. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  42067. var engine = scene.getEngine();
  42068. this._engine = engine;
  42069. this._maxSize = this._engine.getCaps().maxTextureSize;
  42070. this._scene.highlightLayers.push(this);
  42071. // Warn on stencil.
  42072. if (!this._engine.isStencilEnable) {
  42073. 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 }");
  42074. }
  42075. // Adapt options
  42076. this._options = options || {
  42077. mainTextureRatio: 0.25,
  42078. blurTextureSizeRatio: 0.5,
  42079. blurHorizontalSize: 1,
  42080. blurVerticalSize: 1,
  42081. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  42082. };
  42083. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  42084. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  42085. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  42086. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  42087. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  42088. // VBO
  42089. var vertices = [];
  42090. vertices.push(1, 1);
  42091. vertices.push(-1, 1);
  42092. vertices.push(-1, -1);
  42093. vertices.push(1, -1);
  42094. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  42095. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  42096. // Indices
  42097. var indices = [];
  42098. indices.push(0);
  42099. indices.push(1);
  42100. indices.push(2);
  42101. indices.push(0);
  42102. indices.push(2);
  42103. indices.push(3);
  42104. this._indexBuffer = engine.createIndexBuffer(indices);
  42105. // Effect
  42106. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  42107. // Render target
  42108. this.setMainTextureSize();
  42109. // Create Textures and post processes
  42110. this.createTextureAndPostProcesses();
  42111. }
  42112. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  42113. /**
  42114. * Gets the horizontal size of the blur.
  42115. */
  42116. get: function () {
  42117. return this._horizontalBlurPostprocess.blurWidth;
  42118. },
  42119. /**
  42120. * Specifies the horizontal size of the blur.
  42121. */
  42122. set: function (value) {
  42123. this._horizontalBlurPostprocess.blurWidth = value;
  42124. },
  42125. enumerable: true,
  42126. configurable: true
  42127. });
  42128. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  42129. /**
  42130. * Gets the vertical size of the blur.
  42131. */
  42132. get: function () {
  42133. return this._verticalBlurPostprocess.blurWidth;
  42134. },
  42135. /**
  42136. * Specifies the vertical size of the blur.
  42137. */
  42138. set: function (value) {
  42139. this._verticalBlurPostprocess.blurWidth = value;
  42140. },
  42141. enumerable: true,
  42142. configurable: true
  42143. });
  42144. Object.defineProperty(HighlightLayer.prototype, "camera", {
  42145. /**
  42146. * Gets the camera attached to the layer.
  42147. */
  42148. get: function () {
  42149. return this._options.camera;
  42150. },
  42151. enumerable: true,
  42152. configurable: true
  42153. });
  42154. /**
  42155. * Creates the render target textures and post processes used in the highlight layer.
  42156. */
  42157. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  42158. var _this = this;
  42159. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  42160. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  42161. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  42162. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  42163. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  42164. width: this._mainTextureDesiredSize.width,
  42165. height: this._mainTextureDesiredSize.height
  42166. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  42167. this._mainTexture.activeCamera = this._options.camera;
  42168. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42169. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42170. this._mainTexture.anisotropicFilteringLevel = 1;
  42171. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  42172. this._mainTexture.renderParticles = false;
  42173. this._mainTexture.renderList = null;
  42174. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  42175. width: blurTextureWidth,
  42176. height: blurTextureHeight
  42177. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  42178. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42179. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42180. this._blurTexture.anisotropicFilteringLevel = 16;
  42181. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  42182. this._blurTexture.renderParticles = false;
  42183. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42184. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  42185. effect.setTexture("textureSampler", _this._mainTexture);
  42186. });
  42187. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  42188. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42189. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  42190. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  42191. });
  42192. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42193. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  42194. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  42195. });
  42196. }
  42197. else {
  42198. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42199. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  42200. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  42201. });
  42202. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42203. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  42204. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  42205. });
  42206. }
  42207. this._mainTexture.onAfterUnbindObservable.add(function () {
  42208. _this.onBeforeBlurObservable.notifyObservers(_this);
  42209. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  42210. _this.onAfterBlurObservable.notifyObservers(_this);
  42211. });
  42212. // Custom render function
  42213. var renderSubMesh = function (subMesh) {
  42214. var mesh = subMesh.getRenderingMesh();
  42215. var scene = _this._scene;
  42216. var engine = scene.getEngine();
  42217. // Culling
  42218. engine.setState(subMesh.getMaterial().backFaceCulling);
  42219. // Managing instances
  42220. var batch = mesh._getInstancesRenderList(subMesh._id);
  42221. if (batch.mustReturn) {
  42222. return;
  42223. }
  42224. // Excluded Mesh
  42225. if (_this._excludedMeshes[mesh.uniqueId]) {
  42226. return;
  42227. }
  42228. ;
  42229. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  42230. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  42231. var material = subMesh.getMaterial();
  42232. var emissiveTexture = null;
  42233. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  42234. emissiveTexture = material.emissiveTexture;
  42235. }
  42236. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  42237. engine.enableEffect(_this._glowMapGenerationEffect);
  42238. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  42239. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  42240. if (highlightLayerMesh) {
  42241. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  42242. }
  42243. else {
  42244. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  42245. }
  42246. // Alpha test
  42247. if (material && material.needAlphaTesting()) {
  42248. var alphaTexture = material.getAlphaTestTexture();
  42249. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  42250. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  42251. }
  42252. // Glow emissive only
  42253. if (emissiveTexture) {
  42254. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  42255. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  42256. }
  42257. // Bones
  42258. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42259. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  42260. }
  42261. // Draw
  42262. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  42263. }
  42264. else {
  42265. // Need to reset refresh rate of the shadowMap
  42266. _this._mainTexture.resetRefreshCounter();
  42267. }
  42268. };
  42269. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  42270. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  42271. var index;
  42272. for (index = 0; index < opaqueSubMeshes.length; index++) {
  42273. renderSubMesh(opaqueSubMeshes.data[index]);
  42274. }
  42275. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  42276. renderSubMesh(alphaTestSubMeshes.data[index]);
  42277. }
  42278. for (index = 0; index < transparentSubMeshes.length; index++) {
  42279. renderSubMesh(transparentSubMeshes.data[index]);
  42280. }
  42281. };
  42282. this._mainTexture.onClearObservable.add(function (engine) {
  42283. engine.clear(HighlightLayer.neutralColor, true, true, true);
  42284. });
  42285. };
  42286. /**
  42287. * Checks for the readiness of the element composing the layer.
  42288. * @param subMesh the mesh to check for
  42289. * @param useInstances specify wether or not to use instances to render the mesh
  42290. * @param emissiveTexture the associated emissive texture used to generate the glow
  42291. * @return true if ready otherwise, false
  42292. */
  42293. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  42294. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  42295. return false;
  42296. }
  42297. var defines = [];
  42298. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42299. var mesh = subMesh.getMesh();
  42300. var material = subMesh.getMaterial();
  42301. var uv1 = false;
  42302. var uv2 = false;
  42303. // Alpha test
  42304. if (material && material.needAlphaTesting()) {
  42305. var alphaTexture = material.getAlphaTestTexture();
  42306. if (alphaTexture) {
  42307. defines.push("#define ALPHATEST");
  42308. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  42309. alphaTexture.coordinatesIndex === 1) {
  42310. defines.push("#define DIFFUSEUV2");
  42311. uv2 = true;
  42312. }
  42313. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42314. defines.push("#define DIFFUSEUV1");
  42315. uv1 = true;
  42316. }
  42317. }
  42318. }
  42319. // Emissive
  42320. if (emissiveTexture) {
  42321. defines.push("#define EMISSIVE");
  42322. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  42323. emissiveTexture.coordinatesIndex === 1) {
  42324. defines.push("#define EMISSIVEUV2");
  42325. uv2 = true;
  42326. }
  42327. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42328. defines.push("#define EMISSIVEUV1");
  42329. uv1 = true;
  42330. }
  42331. }
  42332. if (uv1) {
  42333. attribs.push(BABYLON.VertexBuffer.UVKind);
  42334. defines.push("#define UV1");
  42335. }
  42336. if (uv2) {
  42337. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42338. defines.push("#define UV2");
  42339. }
  42340. // Bones
  42341. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42342. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42343. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42344. if (mesh.numBoneInfluencers > 4) {
  42345. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42346. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42347. }
  42348. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  42349. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  42350. }
  42351. else {
  42352. defines.push("#define NUM_BONE_INFLUENCERS 0");
  42353. }
  42354. // Instances
  42355. if (useInstances) {
  42356. defines.push("#define INSTANCES");
  42357. attribs.push("world0");
  42358. attribs.push("world1");
  42359. attribs.push("world2");
  42360. attribs.push("world3");
  42361. }
  42362. // Get correct effect
  42363. var join = defines.join("\n");
  42364. if (this._cachedDefines !== join) {
  42365. this._cachedDefines = join;
  42366. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  42367. }
  42368. return this._glowMapGenerationEffect.isReady();
  42369. };
  42370. /**
  42371. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  42372. */
  42373. HighlightLayer.prototype.render = function () {
  42374. var currentEffect = this._glowMapMergeEffect;
  42375. // Check
  42376. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  42377. return;
  42378. var engine = this._scene.getEngine();
  42379. this.onBeforeComposeObservable.notifyObservers(this);
  42380. // Render
  42381. engine.enableEffect(currentEffect);
  42382. engine.setState(false);
  42383. // Cache
  42384. var previousStencilBuffer = engine.getStencilBuffer();
  42385. var previousStencilFunction = engine.getStencilFunction();
  42386. var previousStencilMask = engine.getStencilMask();
  42387. var previousAlphaMode = engine.getAlphaMode();
  42388. // Texture
  42389. currentEffect.setTexture("textureSampler", this._blurTexture);
  42390. // VBOs
  42391. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  42392. // Draw order
  42393. engine.setAlphaMode(this._options.alphaBlendingMode);
  42394. engine.setStencilMask(0x00);
  42395. engine.setStencilBuffer(true);
  42396. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  42397. if (this.outerGlow) {
  42398. currentEffect.setFloat("offset", 0);
  42399. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  42400. engine.draw(true, 0, 6);
  42401. }
  42402. if (this.innerGlow) {
  42403. currentEffect.setFloat("offset", 1);
  42404. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  42405. engine.draw(true, 0, 6);
  42406. }
  42407. // Restore Cache
  42408. engine.setStencilFunction(previousStencilFunction);
  42409. engine.setStencilMask(previousStencilMask);
  42410. engine.setAlphaMode(previousAlphaMode);
  42411. engine.setStencilBuffer(previousStencilBuffer);
  42412. this.onAfterComposeObservable.notifyObservers(this);
  42413. // Handle size changes.
  42414. var size = this._mainTexture.getSize();
  42415. this.setMainTextureSize();
  42416. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  42417. // Recreate RTT and post processes on size change.
  42418. this.onSizeChangedObservable.notifyObservers(this);
  42419. this.disposeTextureAndPostProcesses();
  42420. this.createTextureAndPostProcesses();
  42421. }
  42422. };
  42423. /**
  42424. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  42425. * @param mesh The mesh to exclude from the highlight layer
  42426. */
  42427. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  42428. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  42429. if (!meshExcluded) {
  42430. this._excludedMeshes[mesh.uniqueId] = {
  42431. mesh: mesh,
  42432. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  42433. mesh.getEngine().setStencilBuffer(false);
  42434. }),
  42435. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  42436. mesh.getEngine().setStencilBuffer(true);
  42437. }),
  42438. };
  42439. }
  42440. };
  42441. /**
  42442. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  42443. * @param mesh The mesh to highlight
  42444. */
  42445. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  42446. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  42447. if (meshExcluded) {
  42448. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  42449. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  42450. }
  42451. this._excludedMeshes[mesh.uniqueId] = undefined;
  42452. };
  42453. /**
  42454. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  42455. * @param mesh The mesh to highlight
  42456. * @param color The color of the highlight
  42457. * @param glowEmissiveOnly Extract the glow from the emissive texture
  42458. */
  42459. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  42460. var _this = this;
  42461. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  42462. var meshHighlight = this._meshes[mesh.uniqueId];
  42463. if (meshHighlight) {
  42464. meshHighlight.color = color;
  42465. }
  42466. else {
  42467. this._meshes[mesh.uniqueId] = {
  42468. mesh: mesh,
  42469. color: color,
  42470. // Lambda required for capture due to Observable this context
  42471. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  42472. if (_this._excludedMeshes[mesh.uniqueId]) {
  42473. _this.defaultStencilReference(mesh);
  42474. }
  42475. else {
  42476. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  42477. }
  42478. }),
  42479. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  42480. glowEmissiveOnly: glowEmissiveOnly
  42481. };
  42482. }
  42483. this._shouldRender = true;
  42484. };
  42485. /**
  42486. * Remove a mesh from the highlight layer in order to make it stop glowing.
  42487. * @param mesh The mesh to highlight
  42488. */
  42489. HighlightLayer.prototype.removeMesh = function (mesh) {
  42490. var meshHighlight = this._meshes[mesh.uniqueId];
  42491. if (meshHighlight) {
  42492. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  42493. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  42494. }
  42495. this._meshes[mesh.uniqueId] = undefined;
  42496. this._shouldRender = false;
  42497. for (var meshHighlightToCheck in this._meshes) {
  42498. if (meshHighlightToCheck) {
  42499. this._shouldRender = true;
  42500. break;
  42501. }
  42502. }
  42503. };
  42504. /**
  42505. * Returns true if the layer contains information to display, otherwise false.
  42506. */
  42507. HighlightLayer.prototype.shouldRender = function () {
  42508. return this.isEnabled && this._shouldRender;
  42509. };
  42510. /**
  42511. * Sets the main texture desired size which is the closest power of two
  42512. * of the engine canvas size.
  42513. */
  42514. HighlightLayer.prototype.setMainTextureSize = function () {
  42515. if (this._options.mainTextureFixedSize) {
  42516. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  42517. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  42518. }
  42519. else {
  42520. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  42521. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  42522. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  42523. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  42524. }
  42525. };
  42526. /**
  42527. * Force the stencil to the normal expected value for none glowing parts
  42528. */
  42529. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  42530. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  42531. };
  42532. /**
  42533. * Dispose only the render target textures and post process.
  42534. */
  42535. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  42536. this._blurTexture.dispose();
  42537. this._mainTexture.dispose();
  42538. this._downSamplePostprocess.dispose();
  42539. this._horizontalBlurPostprocess.dispose();
  42540. this._verticalBlurPostprocess.dispose();
  42541. };
  42542. /**
  42543. * Dispose the highlight layer and free resources.
  42544. */
  42545. HighlightLayer.prototype.dispose = function () {
  42546. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  42547. if (vertexBuffer) {
  42548. vertexBuffer.dispose();
  42549. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  42550. }
  42551. if (this._indexBuffer) {
  42552. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  42553. this._indexBuffer = null;
  42554. }
  42555. // Clean textures and post processes
  42556. this.disposeTextureAndPostProcesses();
  42557. // Clean mesh references
  42558. for (var id in this._meshes) {
  42559. var meshHighlight = this._meshes[id];
  42560. if (meshHighlight && meshHighlight.mesh) {
  42561. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  42562. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  42563. }
  42564. }
  42565. this._meshes = null;
  42566. for (var id in this._excludedMeshes) {
  42567. var meshHighlight = this._excludedMeshes[id];
  42568. if (meshHighlight) {
  42569. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  42570. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  42571. }
  42572. }
  42573. this._excludedMeshes = null;
  42574. // Remove from scene
  42575. var index = this._scene.highlightLayers.indexOf(this, 0);
  42576. if (index > -1) {
  42577. this._scene.highlightLayers.splice(index, 1);
  42578. }
  42579. // Callback
  42580. this.onDisposeObservable.notifyObservers(this);
  42581. this.onDisposeObservable.clear();
  42582. this.onBeforeRenderMainTextureObservable.clear();
  42583. this.onBeforeBlurObservable.clear();
  42584. this.onBeforeComposeObservable.clear();
  42585. this.onAfterComposeObservable.clear();
  42586. this.onSizeChangedObservable.clear();
  42587. };
  42588. return HighlightLayer;
  42589. }());
  42590. /**
  42591. * The neutral color used during the preparation of the glow effect.
  42592. * This is black by default as the blend operation is a blend operation.
  42593. */
  42594. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  42595. /**
  42596. * Stencil value used for glowing meshes.
  42597. */
  42598. HighlightLayer.glowingMeshStencilReference = 0x02;
  42599. /**
  42600. * Stencil value used for the other meshes in the scene.
  42601. */
  42602. HighlightLayer.normalMeshStencilReference = 0x01;
  42603. BABYLON.HighlightLayer = HighlightLayer;
  42604. })(BABYLON || (BABYLON = {}));
  42605. //# sourceMappingURL=babylon.highlightlayer.js.map
  42606. var BABYLON;
  42607. (function (BABYLON) {
  42608. var SIMDVector3 = (function () {
  42609. function SIMDVector3() {
  42610. }
  42611. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  42612. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  42613. };
  42614. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  42615. var m = transformation.m;
  42616. var m0 = SIMD.Float32x4.load(m, 0);
  42617. var m1 = SIMD.Float32x4.load(m, 4);
  42618. var m2 = SIMD.Float32x4.load(m, 8);
  42619. var m3 = SIMD.Float32x4.load(m, 12);
  42620. 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));
  42621. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  42622. result.x = SIMD.Float32x4.extractLane(r, 0);
  42623. result.y = SIMD.Float32x4.extractLane(r, 1);
  42624. result.z = SIMD.Float32x4.extractLane(r, 2);
  42625. };
  42626. return SIMDVector3;
  42627. }());
  42628. var SIMDMatrix = (function () {
  42629. function SIMDMatrix() {
  42630. }
  42631. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  42632. var tm = this.m;
  42633. var om = other.m;
  42634. var m0 = SIMD.Float32x4.load(om, 0);
  42635. var m1 = SIMD.Float32x4.load(om, 4);
  42636. var m2 = SIMD.Float32x4.load(om, 8);
  42637. var m3 = SIMD.Float32x4.load(om, 12);
  42638. for (var i = 0; i < 16; i += 4) {
  42639. 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)))));
  42640. }
  42641. return this;
  42642. };
  42643. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  42644. var src = this.m;
  42645. var dest = other.m;
  42646. // Load the 4 rows
  42647. var src0 = SIMD.Float32x4.load(src, 0);
  42648. var src1 = SIMD.Float32x4.load(src, 4);
  42649. var src2 = SIMD.Float32x4.load(src, 8);
  42650. var src3 = SIMD.Float32x4.load(src, 12);
  42651. // Transpose the source matrix. Sort of. Not a true transpose operation
  42652. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  42653. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  42654. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  42655. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  42656. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  42657. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  42658. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  42659. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  42660. // This is a true transposition, but it will lead to an incorrect result
  42661. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  42662. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  42663. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  42664. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  42665. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  42666. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  42667. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  42668. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  42669. // ----
  42670. tmp1 = SIMD.Float32x4.mul(row2, row3);
  42671. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  42672. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  42673. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  42674. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  42675. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  42676. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  42677. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  42678. // ----
  42679. tmp1 = SIMD.Float32x4.mul(row1, row2);
  42680. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  42681. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  42682. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  42683. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  42684. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  42685. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  42686. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  42687. // ----
  42688. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  42689. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  42690. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  42691. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  42692. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  42693. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  42694. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  42695. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  42696. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  42697. // ----
  42698. tmp1 = SIMD.Float32x4.mul(row0, row1);
  42699. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  42700. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  42701. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  42702. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  42703. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  42704. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  42705. // ----
  42706. tmp1 = SIMD.Float32x4.mul(row0, row3);
  42707. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  42708. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  42709. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  42710. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  42711. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  42712. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  42713. // ----
  42714. tmp1 = SIMD.Float32x4.mul(row0, row2);
  42715. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  42716. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  42717. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  42718. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  42719. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  42720. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  42721. // Compute determinant
  42722. var det = SIMD.Float32x4.mul(row0, minor0);
  42723. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  42724. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  42725. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  42726. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  42727. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  42728. // These shuffles aren't necessary if the faulty transposition is done
  42729. // up at the top of this function.
  42730. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  42731. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  42732. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  42733. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  42734. // Compute final values by multiplying with 1/det
  42735. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  42736. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  42737. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  42738. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  42739. return this;
  42740. };
  42741. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  42742. var out = result.m;
  42743. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  42744. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  42745. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  42746. // cc.kmVec3Subtract(f, pCenter, pEye);
  42747. var f = SIMD.Float32x4.sub(center, eye);
  42748. // cc.kmVec3Normalize(f, f);
  42749. var tmp = SIMD.Float32x4.mul(f, f);
  42750. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  42751. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  42752. // cc.kmVec3Assign(up, pUp);
  42753. // cc.kmVec3Normalize(up, up);
  42754. tmp = SIMD.Float32x4.mul(up, up);
  42755. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  42756. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  42757. // cc.kmVec3Cross(s, f, up);
  42758. 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)));
  42759. // cc.kmVec3Normalize(s, s);
  42760. tmp = SIMD.Float32x4.mul(s, s);
  42761. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  42762. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  42763. // cc.kmVec3Cross(u, s, f);
  42764. 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)));
  42765. // cc.kmVec3Normalize(s, s);
  42766. tmp = SIMD.Float32x4.mul(s, s);
  42767. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  42768. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  42769. var zero = SIMD.Float32x4.splat(0.0);
  42770. s = SIMD.Float32x4.neg(s);
  42771. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  42772. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  42773. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  42774. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  42775. 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);
  42776. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  42777. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  42778. 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)))));
  42779. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  42780. 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)))));
  42781. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  42782. 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)))));
  42783. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  42784. 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)))));
  42785. };
  42786. return SIMDMatrix;
  42787. }());
  42788. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  42789. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  42790. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  42791. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  42792. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  42793. var SIMDHelper = (function () {
  42794. function SIMDHelper() {
  42795. }
  42796. Object.defineProperty(SIMDHelper, "IsEnabled", {
  42797. get: function () {
  42798. return SIMDHelper._isEnabled;
  42799. },
  42800. enumerable: true,
  42801. configurable: true
  42802. });
  42803. SIMDHelper.DisableSIMD = function () {
  42804. // Replace functions
  42805. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  42806. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  42807. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  42808. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  42809. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  42810. SIMDHelper._isEnabled = false;
  42811. };
  42812. SIMDHelper.EnableSIMD = function () {
  42813. if (self.SIMD === undefined) {
  42814. return;
  42815. }
  42816. // check if polyfills needed
  42817. if (!self.Math.fround) {
  42818. self.Math.fround = (function (array) { return function (x) {
  42819. return array[0] = x, array[0];
  42820. }; })(new Float32Array(1));
  42821. }
  42822. if (!self.Math.imul) {
  42823. self.Math.imul = function (a, b) {
  42824. var ah = (a >>> 16) & 0xffff;
  42825. var al = a & 0xffff;
  42826. var bh = (b >>> 16) & 0xffff;
  42827. var bl = b & 0xffff;
  42828. // the shift by 0 fixes the sign on the high part
  42829. // the final |0 converts the unsigned value into a signed value
  42830. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  42831. };
  42832. }
  42833. // Replace functions
  42834. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  42835. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  42836. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  42837. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  42838. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  42839. SIMDHelper._isEnabled = true;
  42840. };
  42841. return SIMDHelper;
  42842. }());
  42843. SIMDHelper._isEnabled = false;
  42844. BABYLON.SIMDHelper = SIMDHelper;
  42845. })(BABYLON || (BABYLON = {}));
  42846. //# sourceMappingURL=babylon.math.SIMD.js.map
  42847. var BABYLON;
  42848. (function (BABYLON) {
  42849. /**
  42850. * This class describe a rectangle that were added to the map.
  42851. * You have access to its coordinates either in pixel or normalized (UV)
  42852. */
  42853. var PackedRect = (function () {
  42854. function PackedRect(root, parent, pos, size) {
  42855. this._pos = pos;
  42856. this._size = size;
  42857. this._root = root;
  42858. this._parent = parent;
  42859. this._contentSize = null;
  42860. this._bottomNode = null;
  42861. this._leftNode = null;
  42862. this._initialSize = null;
  42863. this._rightNode = null;
  42864. }
  42865. Object.defineProperty(PackedRect.prototype, "pos", {
  42866. /**
  42867. * @returns the position of this node into the map
  42868. */
  42869. get: function () {
  42870. return this._pos;
  42871. },
  42872. enumerable: true,
  42873. configurable: true
  42874. });
  42875. Object.defineProperty(PackedRect.prototype, "contentSize", {
  42876. /**
  42877. * @returns the size of the rectangle this node handles
  42878. */
  42879. get: function () {
  42880. return this._contentSize;
  42881. },
  42882. enumerable: true,
  42883. configurable: true
  42884. });
  42885. Object.defineProperty(PackedRect.prototype, "UVs", {
  42886. /**
  42887. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  42888. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  42889. */
  42890. get: function () {
  42891. return this.getUVsForCustomSize(this._root._size);
  42892. },
  42893. enumerable: true,
  42894. configurable: true
  42895. });
  42896. /**
  42897. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations) and then using only a part of the PackRect.
  42898. * This method will return the UVs for this part by given the custom size of what you really use
  42899. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  42900. */
  42901. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  42902. var mainWidth = this._root._size.width;
  42903. var mainHeight = this._root._size.height;
  42904. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  42905. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  42906. var uvs = new Array();
  42907. uvs.push(topLeft);
  42908. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  42909. uvs.push(rightBottom);
  42910. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  42911. return uvs;
  42912. };
  42913. /**
  42914. * Free this rectangle from the map.
  42915. * Call this method when you no longer need the rectangle to be in the map.
  42916. */
  42917. PackedRect.prototype.freeContent = function () {
  42918. if (!this.contentSize) {
  42919. return;
  42920. }
  42921. this._contentSize = null;
  42922. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  42923. this.attemptDefrag();
  42924. };
  42925. Object.defineProperty(PackedRect.prototype, "isUsed", {
  42926. get: function () {
  42927. return this._contentSize != null || this._leftNode != null;
  42928. },
  42929. enumerable: true,
  42930. configurable: true
  42931. });
  42932. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  42933. var node = this.findNode(contentSize);
  42934. // Not enough space...
  42935. if (!node) {
  42936. return null;
  42937. }
  42938. node.splitNode(contentSize);
  42939. return node;
  42940. };
  42941. PackedRect.prototype.findNode = function (size) {
  42942. var resNode = null;
  42943. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  42944. if (this.isUsed) {
  42945. if (this._leftNode) {
  42946. resNode = this._leftNode.findNode(size);
  42947. }
  42948. if (!resNode && this._rightNode) {
  42949. resNode = this._rightNode.findNode(size);
  42950. }
  42951. if (!resNode && this._bottomNode) {
  42952. resNode = this._bottomNode.findNode(size);
  42953. }
  42954. }
  42955. else if (this._initialSize) {
  42956. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  42957. resNode = this;
  42958. }
  42959. else {
  42960. return null;
  42961. }
  42962. }
  42963. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  42964. resNode = this;
  42965. }
  42966. return resNode;
  42967. };
  42968. PackedRect.prototype.splitNode = function (contentSize) {
  42969. // 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)
  42970. if (!this._contentSize && this._initialSize) {
  42971. this._contentSize = contentSize.clone();
  42972. 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));
  42973. return this._leftNode.splitNode(contentSize);
  42974. }
  42975. else {
  42976. this._contentSize = contentSize.clone();
  42977. this._initialSize = contentSize.clone();
  42978. if (contentSize.width !== this._size.width) {
  42979. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + contentSize.width, this._pos.y), new BABYLON.Size(this._size.width - contentSize.width, contentSize.height));
  42980. }
  42981. if (contentSize.height !== this._size.height) {
  42982. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + contentSize.height), new BABYLON.Size(this._size.width, this._size.height - contentSize.height));
  42983. }
  42984. return this;
  42985. }
  42986. };
  42987. PackedRect.prototype.attemptDefrag = function () {
  42988. if (!this.isUsed && this.isRecursiveFree) {
  42989. this.clearNode();
  42990. if (this._parent) {
  42991. this._parent.attemptDefrag();
  42992. }
  42993. }
  42994. };
  42995. PackedRect.prototype.clearNode = function () {
  42996. this._initialSize = null;
  42997. this._rightNode = null;
  42998. this._bottomNode = null;
  42999. };
  43000. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  43001. get: function () {
  43002. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  43003. },
  43004. enumerable: true,
  43005. configurable: true
  43006. });
  43007. PackedRect.prototype.evalFreeSize = function (size) {
  43008. var levelSize = 0;
  43009. if (!this.isUsed) {
  43010. if (this._initialSize) {
  43011. levelSize = this._initialSize.surface;
  43012. }
  43013. else {
  43014. levelSize = this._size.surface;
  43015. }
  43016. }
  43017. if (this._rightNode) {
  43018. levelSize += this._rightNode.evalFreeSize(0);
  43019. }
  43020. if (this._bottomNode) {
  43021. levelSize += this._bottomNode.evalFreeSize(0);
  43022. }
  43023. return levelSize + size;
  43024. };
  43025. return PackedRect;
  43026. }());
  43027. BABYLON.PackedRect = PackedRect;
  43028. /**
  43029. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  43030. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  43031. * 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.
  43032. */
  43033. var RectPackingMap = (function (_super) {
  43034. __extends(RectPackingMap, _super);
  43035. /**
  43036. * Create an instance of the object with a dimension using the given size
  43037. * @param size The dimension of the rectangle that will contain all the sub ones.
  43038. */
  43039. function RectPackingMap(size) {
  43040. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  43041. _this._root = _this;
  43042. return _this;
  43043. }
  43044. /**
  43045. * Add a rectangle, finding the best location to store it into the map
  43046. * @param size the dimension of the rectangle to store
  43047. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  43048. */
  43049. RectPackingMap.prototype.addRect = function (size) {
  43050. var node = this.findAndSplitNode(size);
  43051. return node;
  43052. };
  43053. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  43054. /**
  43055. * Return the current space free normalized between [0;1]
  43056. * @returns {}
  43057. */
  43058. get: function () {
  43059. var freeSize = 0;
  43060. freeSize = this.evalFreeSize(freeSize);
  43061. return freeSize / (this._size.width * this._size.height);
  43062. },
  43063. enumerable: true,
  43064. configurable: true
  43065. });
  43066. return RectPackingMap;
  43067. }(PackedRect));
  43068. BABYLON.RectPackingMap = RectPackingMap;
  43069. })(BABYLON || (BABYLON = {}));
  43070. //# sourceMappingURL=babylon.rectPackingMap.js.map
  43071. var BABYLON;
  43072. (function (BABYLON) {
  43073. var DynamicFloatArrayElementInfo = (function () {
  43074. function DynamicFloatArrayElementInfo() {
  43075. }
  43076. return DynamicFloatArrayElementInfo;
  43077. }());
  43078. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  43079. /**
  43080. * 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.
  43081. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  43082. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  43083. * 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.
  43084. * 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.
  43085. * 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".
  43086. */
  43087. var DynamicFloatArray = (function () {
  43088. /**
  43089. * Construct an instance of the dynamic float array
  43090. * @param stride size of one element in float (i.e. not bytes!)
  43091. * @param initialElementCount the number of available entries at construction
  43092. */
  43093. function DynamicFloatArray(stride, initialElementCount) {
  43094. this.compareValueOffset = null;
  43095. this.sortingAscending = true;
  43096. this._stride = stride;
  43097. this.buffer = new Float32Array(stride * initialElementCount);
  43098. this._lastUsed = 0;
  43099. this._firstFree = 0;
  43100. this._allEntries = new Array(initialElementCount);
  43101. this._freeEntries = new Array(initialElementCount);
  43102. for (var i = 0; i < initialElementCount; i++) {
  43103. var element = new DynamicFloatArrayElementInfo();
  43104. element.offset = i * stride;
  43105. this._allEntries[i] = element;
  43106. this._freeEntries[initialElementCount - i - 1] = element;
  43107. }
  43108. }
  43109. /**
  43110. * Allocate an element in the array.
  43111. * @return the element info instance that contains the offset into the main buffer of the element's location.
  43112. * Beware, this offset may change when you call pack()
  43113. */
  43114. DynamicFloatArray.prototype.allocElement = function () {
  43115. if (this._freeEntries.length === 0) {
  43116. this._growBuffer();
  43117. }
  43118. var el = this._freeEntries.pop();
  43119. this._lastUsed = Math.max(el.offset, this._lastUsed);
  43120. if (el.offset === this._firstFree) {
  43121. if (this._freeEntries.length > 0) {
  43122. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  43123. }
  43124. else {
  43125. this._firstFree += this._stride;
  43126. }
  43127. }
  43128. return el;
  43129. };
  43130. /**
  43131. * Free the element corresponding to the given element info
  43132. * @param elInfo the element that describe the allocated element
  43133. */
  43134. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  43135. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  43136. this._freeEntries.push(elInfo);
  43137. };
  43138. /**
  43139. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  43140. * 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().
  43141. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  43142. */
  43143. DynamicFloatArray.prototype.pack = function () {
  43144. // no free slot? no need to pack
  43145. if (this._freeEntries.length === 0) {
  43146. return this.buffer;
  43147. }
  43148. // If the buffer is already packed the last used will always be lower than the first free
  43149. // 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.
  43150. if (this._lastUsed < this._firstFree) {
  43151. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  43152. return elementsBuffer_1;
  43153. }
  43154. var s = this._stride;
  43155. // 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
  43156. var lastFree = new DynamicFloatArrayElementInfo();
  43157. lastFree.offset = this.totalElementCount * s;
  43158. this._freeEntries.push(lastFree);
  43159. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  43160. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  43161. var firstFreeSlotOffset = sortedFree[0].offset;
  43162. var freeZoneSize = 1;
  43163. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  43164. var prevOffset = sortedFree[0].offset;
  43165. for (var i = 1; i < sortedFree.length; i++) {
  43166. // 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
  43167. if (firstFreeSlotOffset >= occupiedZoneSize) {
  43168. break;
  43169. }
  43170. var curFree = sortedFree[i];
  43171. var curOffset = curFree.offset;
  43172. // Compute the distance between this offset and the previous
  43173. var distance = curOffset - prevOffset;
  43174. // If the distance is the stride size, they are adjacent, it good, move to the next
  43175. if (distance === s) {
  43176. // Free zone is one element bigger
  43177. ++freeZoneSize;
  43178. // as we're about to iterate to the next, the cur becomes the previous...
  43179. prevOffset = curOffset;
  43180. continue;
  43181. }
  43182. // Distance is bigger, which means there's x element between the previous free and this one
  43183. var usedRange = (distance / s) - 1;
  43184. // Two cases the free zone is smaller than the data to move or bigger
  43185. // Copy what can fit in the free zone
  43186. var curMoveOffset = curOffset - s;
  43187. var copyCount = Math.min(freeZoneSize, usedRange);
  43188. for (var j = 0; j < copyCount; j++) {
  43189. var freeI = firstFreeSlotOffset / s;
  43190. var curI = curMoveOffset / s;
  43191. var moveEl = sortedAll[curI];
  43192. this._moveElement(moveEl, firstFreeSlotOffset);
  43193. var replacedEl = sortedAll[freeI];
  43194. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  43195. replacedEl.offset = curMoveOffset;
  43196. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  43197. sortedAll[freeI] = moveEl;
  43198. sortedAll[curI] = replacedEl;
  43199. curMoveOffset -= s;
  43200. firstFreeSlotOffset += s;
  43201. }
  43202. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  43203. if (freeZoneSize <= usedRange) {
  43204. firstFreeSlotOffset = curMoveOffset + s;
  43205. freeZoneSize = 1 + copyCount;
  43206. }
  43207. else {
  43208. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  43209. }
  43210. // as we're about to iterate to the next, the cur becomes the previous...
  43211. prevOffset = curOffset;
  43212. }
  43213. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  43214. this._lastUsed = firstFreeSlotOffset - s;
  43215. this._firstFree = firstFreeSlotOffset;
  43216. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  43217. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  43218. this._allEntries = sortedAll;
  43219. return elementsBuffer;
  43220. };
  43221. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  43222. for (var i = 0; i < this._stride; i++) {
  43223. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  43224. }
  43225. element.offset = destOffset;
  43226. };
  43227. DynamicFloatArray.prototype._growBuffer = function () {
  43228. // Allocate the new buffer with 50% more entries, copy the content of the current one
  43229. var newElCount = Math.floor(this.totalElementCount * 1.5);
  43230. var newBuffer = new Float32Array(newElCount * this._stride);
  43231. newBuffer.set(this.buffer);
  43232. var curCount = this.totalElementCount;
  43233. var addedCount = newElCount - this.totalElementCount;
  43234. for (var i = 0; i < addedCount; i++) {
  43235. var element = new DynamicFloatArrayElementInfo();
  43236. element.offset = (curCount + i) * this.stride;
  43237. this._allEntries.push(element);
  43238. this._freeEntries[addedCount - i - 1] = element;
  43239. }
  43240. this._firstFree = curCount * this.stride;
  43241. this.buffer = newBuffer;
  43242. };
  43243. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  43244. /**
  43245. * Get the total count of entries that can fit in the current buffer
  43246. * @returns the elements count
  43247. */
  43248. get: function () {
  43249. return this._allEntries.length;
  43250. },
  43251. enumerable: true,
  43252. configurable: true
  43253. });
  43254. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  43255. /**
  43256. * Get the count of free entries that can still be allocated without resizing the buffer
  43257. * @returns the free elements count
  43258. */
  43259. get: function () {
  43260. return this._freeEntries.length;
  43261. },
  43262. enumerable: true,
  43263. configurable: true
  43264. });
  43265. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  43266. /**
  43267. * Get the count of allocated elements
  43268. * @returns the allocated elements count
  43269. */
  43270. get: function () {
  43271. return this._allEntries.length - this._freeEntries.length;
  43272. },
  43273. enumerable: true,
  43274. configurable: true
  43275. });
  43276. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  43277. /**
  43278. * Return the size of one element in float
  43279. * @returns the size in float
  43280. */
  43281. get: function () {
  43282. return this._stride;
  43283. },
  43284. enumerable: true,
  43285. configurable: true
  43286. });
  43287. DynamicFloatArray.prototype.sort = function () {
  43288. var _this = this;
  43289. if (!this.compareValueOffset) {
  43290. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  43291. }
  43292. var count = this.usedElementCount;
  43293. // Do we have to (re)create the sort table?
  43294. if (!this._sortTable || this._sortTable.length < count) {
  43295. // 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...
  43296. var newCount = Math.min(this.totalElementCount, count * 2);
  43297. this._sortTable = new Array(newCount);
  43298. }
  43299. if (!this._sortedTable || this._sortedTable.length !== count) {
  43300. this._sortedTable = new Array(count);
  43301. }
  43302. // Because, you know...
  43303. this.pack();
  43304. //let stride = this.stride;
  43305. //for (let i = 0; i < count; i++) {
  43306. // let si = this._sortTable[i];
  43307. // if (!si) {
  43308. // si = new SortInfo();
  43309. // this._sortTable[i] = si;
  43310. // }
  43311. // si.entry = this._allEntries[i];
  43312. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  43313. // si.swapedOffset = null;
  43314. // this._sortedTable[i] = si;
  43315. //}
  43316. var curOffset = 0;
  43317. var stride = this.stride;
  43318. for (var i = 0; i < count; i++, curOffset += stride) {
  43319. var si = this._sortTable[i];
  43320. if (!si) {
  43321. si = new SortInfo();
  43322. this._sortTable[i] = si;
  43323. }
  43324. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  43325. si.offset = curOffset;
  43326. si.swapedOffset = null;
  43327. this._sortedTable[i] = si;
  43328. }
  43329. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  43330. if (this.sortingAscending) {
  43331. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  43332. }
  43333. else {
  43334. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  43335. }
  43336. var swapElements = function (src, dst) {
  43337. for (var i = 0; i < stride; i++) {
  43338. var tps = _this.buffer[dst + i];
  43339. _this.buffer[dst + i] = _this.buffer[src + i];
  43340. _this.buffer[src + i] = tps;
  43341. }
  43342. };
  43343. // 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:
  43344. // 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),
  43345. // and I still want something with a good algorithm complexity.
  43346. // 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,
  43347. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  43348. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  43349. // 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
  43350. // until we find a SortInfo object without a swapedOffset which means we got the right location
  43351. // 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
  43352. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  43353. for (var i = 0; i < count; i++) {
  43354. // Get the element to move
  43355. var sourceSI = this._sortedTable[i];
  43356. var destSI = this._sortTable[i];
  43357. var sourceOff = sourceSI.offset;
  43358. // If the source changed location, find the new one
  43359. if (sourceSI.swapedOffset) {
  43360. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  43361. var curSI = sourceSI;
  43362. while (curSI.swapedOffset) {
  43363. curSI = this._sortTable[curSI.swapedOffset / stride];
  43364. }
  43365. // Finally get the right location
  43366. sourceOff = curSI.offset;
  43367. }
  43368. // Tag the element being replaced with its new location
  43369. destSI.swapedOffset = sourceOff;
  43370. // Swap elements (only if needed)
  43371. if (sourceOff !== destSI.offset) {
  43372. swapElements(sourceOff, destSI.offset);
  43373. }
  43374. // Update the offset in the corresponding DFAE
  43375. //sourceSI.entry.offset = destSI.entry.offset;
  43376. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  43377. }
  43378. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  43379. return true;
  43380. };
  43381. return DynamicFloatArray;
  43382. }());
  43383. BABYLON.DynamicFloatArray = DynamicFloatArray;
  43384. var SortInfo = (function () {
  43385. function SortInfo() {
  43386. this.compareData = this.offset = this.swapedOffset = null;
  43387. }
  43388. return SortInfo;
  43389. }());
  43390. })(BABYLON || (BABYLON = {}));
  43391. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  43392. var BABYLON;
  43393. (function (BABYLON) {
  43394. var MapTexture = (function (_super) {
  43395. __extends(MapTexture, _super);
  43396. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  43397. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43398. if (useMipMap === void 0) { useMipMap = false; }
  43399. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  43400. _this.name = name;
  43401. _this._size = size;
  43402. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43403. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43404. // Create the rectPackMap that will allocate portion of the texture
  43405. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  43406. // Create the texture that will store the content
  43407. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  43408. return _this;
  43409. }
  43410. /**
  43411. * Allocate a rectangle of a given size in the texture map
  43412. * @param size the size of the rectangle to allocation
  43413. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  43414. */
  43415. MapTexture.prototype.allocateRect = function (size) {
  43416. return this._rectPackingMap.addRect(size);
  43417. };
  43418. /**
  43419. * Free a given rectangle from the texture map
  43420. * @param rectInfo the instance corresponding to the rect to free.
  43421. */
  43422. MapTexture.prototype.freeRect = function (rectInfo) {
  43423. if (rectInfo) {
  43424. rectInfo.freeContent();
  43425. }
  43426. };
  43427. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  43428. /**
  43429. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  43430. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  43431. * @returns {}
  43432. */
  43433. get: function () {
  43434. return this._rectPackingMap.freeSpace;
  43435. },
  43436. enumerable: true,
  43437. configurable: true
  43438. });
  43439. /**
  43440. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  43441. * 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.
  43442. * Don't forget to call unbindTexture when you're done rendering
  43443. * @param rect the zone to render to
  43444. * @param clear true to clear the portion's color/depth data
  43445. */
  43446. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  43447. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  43448. };
  43449. /**
  43450. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  43451. * 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.
  43452. * Don't forget to call unbindTexture when you're done rendering
  43453. * @param pos the position into the texture
  43454. * @param size the portion to fit the clip space to
  43455. * @param clear true to clear the portion's color/depth data
  43456. */
  43457. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  43458. var engine = this.getScene().getEngine();
  43459. engine.bindFramebuffer(this._texture);
  43460. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  43461. if (clear) {
  43462. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  43463. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  43464. }
  43465. };
  43466. /**
  43467. * Unbind the texture map from the rendering engine.
  43468. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  43469. * @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.
  43470. */
  43471. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  43472. // Dump ?
  43473. if (dumpForDebug) {
  43474. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  43475. }
  43476. var engine = this.getScene().getEngine();
  43477. if (this._replacedViewport) {
  43478. engine.setViewport(this._replacedViewport);
  43479. this._replacedViewport = null;
  43480. }
  43481. engine.unBindFramebuffer(this._texture);
  43482. };
  43483. Object.defineProperty(MapTexture.prototype, "canRescale", {
  43484. get: function () {
  43485. return false;
  43486. },
  43487. enumerable: true,
  43488. configurable: true
  43489. });
  43490. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  43491. // Anyway, there's not much point to use this method for this kind of texture I guess
  43492. MapTexture.prototype.clone = function () {
  43493. return null;
  43494. };
  43495. return MapTexture;
  43496. }(BABYLON.Texture));
  43497. BABYLON.MapTexture = MapTexture;
  43498. })(BABYLON || (BABYLON = {}));
  43499. //# sourceMappingURL=babylon.mapTexture.js.map
  43500. var BABYLON;
  43501. (function (BABYLON) {
  43502. var ShaderMaterial = (function (_super) {
  43503. __extends(ShaderMaterial, _super);
  43504. function ShaderMaterial(name, scene, shaderPath, options) {
  43505. var _this = _super.call(this, name, scene) || this;
  43506. _this._textures = {};
  43507. _this._textureArrays = {};
  43508. _this._floats = {};
  43509. _this._floatsArrays = {};
  43510. _this._colors3 = {};
  43511. _this._colors4 = {};
  43512. _this._vectors2 = {};
  43513. _this._vectors3 = {};
  43514. _this._vectors4 = {};
  43515. _this._matrices = {};
  43516. _this._matrices3x3 = {};
  43517. _this._matrices2x2 = {};
  43518. _this._vectors3Arrays = {};
  43519. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  43520. _this._shaderPath = shaderPath;
  43521. options.needAlphaBlending = options.needAlphaBlending || false;
  43522. options.needAlphaTesting = options.needAlphaTesting || false;
  43523. options.attributes = options.attributes || ["position", "normal", "uv"];
  43524. options.uniforms = options.uniforms || ["worldViewProjection"];
  43525. options.samplers = options.samplers || [];
  43526. options.defines = options.defines || [];
  43527. _this._options = options;
  43528. return _this;
  43529. }
  43530. ShaderMaterial.prototype.getClassName = function () {
  43531. return "ShaderMaterial";
  43532. };
  43533. ShaderMaterial.prototype.needAlphaBlending = function () {
  43534. return this._options.needAlphaBlending;
  43535. };
  43536. ShaderMaterial.prototype.needAlphaTesting = function () {
  43537. return this._options.needAlphaTesting;
  43538. };
  43539. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  43540. if (this._options.uniforms.indexOf(uniformName) === -1) {
  43541. this._options.uniforms.push(uniformName);
  43542. }
  43543. };
  43544. ShaderMaterial.prototype.setTexture = function (name, texture) {
  43545. if (this._options.samplers.indexOf(name) === -1) {
  43546. this._options.samplers.push(name);
  43547. }
  43548. this._textures[name] = texture;
  43549. return this;
  43550. };
  43551. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  43552. if (this._options.samplers.indexOf(name) === -1) {
  43553. this._options.samplers.push(name);
  43554. }
  43555. this._checkUniform(name);
  43556. this._textureArrays[name] = textures;
  43557. return this;
  43558. };
  43559. ShaderMaterial.prototype.setFloat = function (name, value) {
  43560. this._checkUniform(name);
  43561. this._floats[name] = value;
  43562. return this;
  43563. };
  43564. ShaderMaterial.prototype.setFloats = function (name, value) {
  43565. this._checkUniform(name);
  43566. this._floatsArrays[name] = value;
  43567. return this;
  43568. };
  43569. ShaderMaterial.prototype.setColor3 = function (name, value) {
  43570. this._checkUniform(name);
  43571. this._colors3[name] = value;
  43572. return this;
  43573. };
  43574. ShaderMaterial.prototype.setColor4 = function (name, value) {
  43575. this._checkUniform(name);
  43576. this._colors4[name] = value;
  43577. return this;
  43578. };
  43579. ShaderMaterial.prototype.setVector2 = function (name, value) {
  43580. this._checkUniform(name);
  43581. this._vectors2[name] = value;
  43582. return this;
  43583. };
  43584. ShaderMaterial.prototype.setVector3 = function (name, value) {
  43585. this._checkUniform(name);
  43586. this._vectors3[name] = value;
  43587. return this;
  43588. };
  43589. ShaderMaterial.prototype.setVector4 = function (name, value) {
  43590. this._checkUniform(name);
  43591. this._vectors4[name] = value;
  43592. return this;
  43593. };
  43594. ShaderMaterial.prototype.setMatrix = function (name, value) {
  43595. this._checkUniform(name);
  43596. this._matrices[name] = value;
  43597. return this;
  43598. };
  43599. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  43600. this._checkUniform(name);
  43601. this._matrices3x3[name] = value;
  43602. return this;
  43603. };
  43604. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  43605. this._checkUniform(name);
  43606. this._matrices2x2[name] = value;
  43607. return this;
  43608. };
  43609. ShaderMaterial.prototype.setArray3 = function (name, value) {
  43610. this._checkUniform(name);
  43611. this._vectors3Arrays[name] = value;
  43612. return this;
  43613. };
  43614. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  43615. if (!mesh) {
  43616. return true;
  43617. }
  43618. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  43619. return false;
  43620. }
  43621. return false;
  43622. };
  43623. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  43624. var scene = this.getScene();
  43625. var engine = scene.getEngine();
  43626. if (!this.checkReadyOnEveryCall) {
  43627. if (this._renderId === scene.getRenderId()) {
  43628. if (this._checkCache(scene, mesh, useInstances)) {
  43629. return true;
  43630. }
  43631. }
  43632. }
  43633. // Instances
  43634. var defines = [];
  43635. var fallbacks = new BABYLON.EffectFallbacks();
  43636. if (useInstances) {
  43637. defines.push("#define INSTANCES");
  43638. }
  43639. for (var index = 0; index < this._options.defines.length; index++) {
  43640. defines.push(this._options.defines[index]);
  43641. }
  43642. // Bones
  43643. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  43644. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43645. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43646. fallbacks.addCPUSkinningFallback(0, mesh);
  43647. }
  43648. // Alpha test
  43649. if (engine.getAlphaTesting()) {
  43650. defines.push("#define ALPHATEST");
  43651. }
  43652. var previousEffect = this._effect;
  43653. var join = defines.join("\n");
  43654. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  43655. if (!this._effect.isReady()) {
  43656. return false;
  43657. }
  43658. if (previousEffect !== this._effect) {
  43659. scene.resetCachedMaterial();
  43660. }
  43661. this._renderId = scene.getRenderId();
  43662. return true;
  43663. };
  43664. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43665. var scene = this.getScene();
  43666. if (this._options.uniforms.indexOf("world") !== -1) {
  43667. this._effect.setMatrix("world", world);
  43668. }
  43669. if (this._options.uniforms.indexOf("worldView") !== -1) {
  43670. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  43671. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  43672. }
  43673. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  43674. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  43675. }
  43676. };
  43677. ShaderMaterial.prototype.bind = function (world, mesh) {
  43678. // Std values
  43679. this.bindOnlyWorldMatrix(world);
  43680. if (this.getScene().getCachedMaterial() !== this) {
  43681. if (this._options.uniforms.indexOf("view") !== -1) {
  43682. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  43683. }
  43684. if (this._options.uniforms.indexOf("projection") !== -1) {
  43685. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  43686. }
  43687. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  43688. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  43689. }
  43690. // Bones
  43691. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  43692. var name;
  43693. // Texture
  43694. for (name in this._textures) {
  43695. this._effect.setTexture(name, this._textures[name]);
  43696. }
  43697. // Texture arrays
  43698. for (name in this._textureArrays) {
  43699. this._effect.setTextureArray(name, this._textureArrays[name]);
  43700. }
  43701. // Float
  43702. for (name in this._floats) {
  43703. this._effect.setFloat(name, this._floats[name]);
  43704. }
  43705. // Float s
  43706. for (name in this._floatsArrays) {
  43707. this._effect.setArray(name, this._floatsArrays[name]);
  43708. }
  43709. // Color3
  43710. for (name in this._colors3) {
  43711. this._effect.setColor3(name, this._colors3[name]);
  43712. }
  43713. // Color4
  43714. for (name in this._colors4) {
  43715. var color = this._colors4[name];
  43716. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  43717. }
  43718. // Vector2
  43719. for (name in this._vectors2) {
  43720. this._effect.setVector2(name, this._vectors2[name]);
  43721. }
  43722. // Vector3
  43723. for (name in this._vectors3) {
  43724. this._effect.setVector3(name, this._vectors3[name]);
  43725. }
  43726. // Vector4
  43727. for (name in this._vectors4) {
  43728. this._effect.setVector4(name, this._vectors4[name]);
  43729. }
  43730. // Matrix
  43731. for (name in this._matrices) {
  43732. this._effect.setMatrix(name, this._matrices[name]);
  43733. }
  43734. // Matrix 3x3
  43735. for (name in this._matrices3x3) {
  43736. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  43737. }
  43738. // Matrix 2x2
  43739. for (name in this._matrices2x2) {
  43740. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  43741. }
  43742. // Vector3Array
  43743. for (name in this._vectors3Arrays) {
  43744. this._effect.setArray3(name, this._vectors3Arrays[name]);
  43745. }
  43746. }
  43747. _super.prototype.bind.call(this, world, mesh);
  43748. };
  43749. ShaderMaterial.prototype.clone = function (name) {
  43750. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  43751. return newShaderMaterial;
  43752. };
  43753. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43754. if (forceDisposeTextures) {
  43755. var name;
  43756. for (name in this._textures) {
  43757. this._textures[name].dispose();
  43758. }
  43759. for (name in this._textureArrays) {
  43760. var array = this._textureArrays[name];
  43761. for (var index = 0; index < array.length; index++) {
  43762. array[index].dispose();
  43763. }
  43764. }
  43765. }
  43766. this._textures = {};
  43767. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43768. };
  43769. ShaderMaterial.prototype.serialize = function () {
  43770. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43771. serializationObject.customType = "BABYLON.ShaderMaterial";
  43772. serializationObject.options = this._options;
  43773. serializationObject.shaderPath = this._shaderPath;
  43774. var name;
  43775. // Texture
  43776. serializationObject.textures = {};
  43777. for (name in this._textures) {
  43778. serializationObject.textures[name] = this._textures[name].serialize();
  43779. }
  43780. // Texture arrays
  43781. serializationObject.textureArrays = {};
  43782. for (name in this._textureArrays) {
  43783. serializationObject.textureArrays[name] = [];
  43784. var array = this._textureArrays[name];
  43785. for (var index = 0; index < array.length; index++) {
  43786. serializationObject.textureArrays[name].push(array[index].serialize());
  43787. }
  43788. }
  43789. // Float
  43790. serializationObject.floats = {};
  43791. for (name in this._floats) {
  43792. serializationObject.floats[name] = this._floats[name];
  43793. }
  43794. // Float s
  43795. serializationObject.floatArrays = {};
  43796. for (name in this._floatsArrays) {
  43797. serializationObject.floatArrays[name] = this._floatsArrays[name];
  43798. }
  43799. // Color3
  43800. serializationObject.colors3 = {};
  43801. for (name in this._colors3) {
  43802. serializationObject.colors3[name] = this._colors3[name].asArray();
  43803. }
  43804. // Color4
  43805. serializationObject.colors4 = {};
  43806. for (name in this._colors4) {
  43807. serializationObject.colors4[name] = this._colors4[name].asArray();
  43808. }
  43809. // Vector2
  43810. serializationObject.vectors2 = {};
  43811. for (name in this._vectors2) {
  43812. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  43813. }
  43814. // Vector3
  43815. serializationObject.vectors3 = {};
  43816. for (name in this._vectors3) {
  43817. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  43818. }
  43819. // Vector4
  43820. serializationObject.vectors4 = {};
  43821. for (name in this._vectors4) {
  43822. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  43823. }
  43824. // Matrix
  43825. serializationObject.matrices = {};
  43826. for (name in this._matrices) {
  43827. serializationObject.matrices[name] = this._matrices[name].asArray();
  43828. }
  43829. // Matrix 3x3
  43830. serializationObject.matrices3x3 = {};
  43831. for (name in this._matrices3x3) {
  43832. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  43833. }
  43834. // Matrix 2x2
  43835. serializationObject.matrices2x2 = {};
  43836. for (name in this._matrices2x2) {
  43837. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  43838. }
  43839. // Vector3Array
  43840. serializationObject.vectors3Arrays = {};
  43841. for (name in this._vectors3Arrays) {
  43842. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  43843. }
  43844. return serializationObject;
  43845. };
  43846. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  43847. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  43848. var name;
  43849. // Texture
  43850. for (name in source.textures) {
  43851. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  43852. }
  43853. // Texture arrays
  43854. for (name in source.textureArrays) {
  43855. var array = source.textureArrays[name];
  43856. var textureArray = new Array();
  43857. for (var index = 0; index < array.length; index++) {
  43858. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  43859. }
  43860. material.setTextureArray(name, textureArray);
  43861. }
  43862. // Float
  43863. for (name in source.floats) {
  43864. material.setFloat(name, source.floats[name]);
  43865. }
  43866. // Float s
  43867. for (name in source.floatsArrays) {
  43868. material.setFloats(name, source.floatsArrays[name]);
  43869. }
  43870. // Color3
  43871. for (name in source.colors3) {
  43872. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  43873. }
  43874. // Color4
  43875. for (name in source.colors4) {
  43876. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  43877. }
  43878. // Vector2
  43879. for (name in source.vectors2) {
  43880. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  43881. }
  43882. // Vector3
  43883. for (name in source.vectors3) {
  43884. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  43885. }
  43886. // Vector4
  43887. for (name in source.vectors4) {
  43888. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  43889. }
  43890. // Matrix
  43891. for (name in source.matrices) {
  43892. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  43893. }
  43894. // Matrix 3x3
  43895. for (name in source.matrices3x3) {
  43896. material.setMatrix3x3(name, source.matrices3x3[name]);
  43897. }
  43898. // Matrix 2x2
  43899. for (name in source.matrices2x2) {
  43900. material.setMatrix2x2(name, source.matrices2x2[name]);
  43901. }
  43902. // Vector3Array
  43903. for (name in source.vectors3Arrays) {
  43904. material.setArray3(name, source.vectors3Arrays[name]);
  43905. }
  43906. return material;
  43907. };
  43908. return ShaderMaterial;
  43909. }(BABYLON.Material));
  43910. BABYLON.ShaderMaterial = ShaderMaterial;
  43911. })(BABYLON || (BABYLON = {}));
  43912. //# sourceMappingURL=babylon.shaderMaterial.js.map
  43913. var BABYLON;
  43914. (function (BABYLON) {
  43915. var Internals;
  43916. (function (Internals) {
  43917. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  43918. // All values and structures referenced from:
  43919. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  43920. var DDS_MAGIC = 0x20534444;
  43921. 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;
  43922. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  43923. 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;
  43924. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  43925. function FourCCToInt32(value) {
  43926. return value.charCodeAt(0) +
  43927. (value.charCodeAt(1) << 8) +
  43928. (value.charCodeAt(2) << 16) +
  43929. (value.charCodeAt(3) << 24);
  43930. }
  43931. function Int32ToFourCC(value) {
  43932. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  43933. }
  43934. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  43935. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  43936. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  43937. var headerLengthInt = 31; // The header length in 32 bit ints
  43938. // Offsets into the header array
  43939. var off_magic = 0;
  43940. var off_size = 1;
  43941. var off_flags = 2;
  43942. var off_height = 3;
  43943. var off_width = 4;
  43944. var off_mipmapCount = 7;
  43945. var off_pfFlags = 20;
  43946. var off_pfFourCC = 21;
  43947. var off_RGBbpp = 22;
  43948. var off_RMask = 23;
  43949. var off_GMask = 24;
  43950. var off_BMask = 25;
  43951. var off_AMask = 26;
  43952. var off_caps1 = 27;
  43953. var off_caps2 = 28;
  43954. ;
  43955. var DDSTools = (function () {
  43956. function DDSTools() {
  43957. }
  43958. DDSTools.GetDDSInfo = function (arrayBuffer) {
  43959. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  43960. var mipmapCount = 1;
  43961. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  43962. mipmapCount = Math.max(1, header[off_mipmapCount]);
  43963. }
  43964. return {
  43965. width: header[off_width],
  43966. height: header[off_height],
  43967. mipmapCount: mipmapCount,
  43968. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  43969. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  43970. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  43971. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  43972. };
  43973. };
  43974. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  43975. var byteArray = new Uint8Array(dataLength);
  43976. var srcData = new Uint8Array(arrayBuffer);
  43977. var index = 0;
  43978. for (var y = height - 1; y >= 0; y--) {
  43979. for (var x = 0; x < width; x++) {
  43980. var srcPos = dataOffset + (x + y * width) * 4;
  43981. byteArray[index + 2] = srcData[srcPos];
  43982. byteArray[index + 1] = srcData[srcPos + 1];
  43983. byteArray[index] = srcData[srcPos + 2];
  43984. byteArray[index + 3] = srcData[srcPos + 3];
  43985. index += 4;
  43986. }
  43987. }
  43988. return byteArray;
  43989. };
  43990. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  43991. var byteArray = new Uint8Array(dataLength);
  43992. var srcData = new Uint8Array(arrayBuffer);
  43993. var index = 0;
  43994. for (var y = height - 1; y >= 0; y--) {
  43995. for (var x = 0; x < width; x++) {
  43996. var srcPos = dataOffset + (x + y * width) * 3;
  43997. byteArray[index + 2] = srcData[srcPos];
  43998. byteArray[index + 1] = srcData[srcPos + 1];
  43999. byteArray[index] = srcData[srcPos + 2];
  44000. index += 3;
  44001. }
  44002. }
  44003. return byteArray;
  44004. };
  44005. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  44006. var byteArray = new Uint8Array(dataLength);
  44007. var srcData = new Uint8Array(arrayBuffer);
  44008. var index = 0;
  44009. for (var y = height - 1; y >= 0; y--) {
  44010. for (var x = 0; x < width; x++) {
  44011. var srcPos = dataOffset + (x + y * width);
  44012. byteArray[index] = srcData[srcPos];
  44013. index++;
  44014. }
  44015. }
  44016. return byteArray;
  44017. };
  44018. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  44019. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  44020. if (header[off_magic] != DDS_MAGIC) {
  44021. BABYLON.Tools.Error("Invalid magic number in DDS header");
  44022. return;
  44023. }
  44024. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  44025. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  44026. return;
  44027. }
  44028. if (info.isFourCC) {
  44029. fourCC = header[off_pfFourCC];
  44030. switch (fourCC) {
  44031. case FOURCC_DXT1:
  44032. blockBytes = 8;
  44033. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  44034. break;
  44035. case FOURCC_DXT3:
  44036. blockBytes = 16;
  44037. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  44038. break;
  44039. case FOURCC_DXT5:
  44040. blockBytes = 16;
  44041. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  44042. break;
  44043. default:
  44044. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  44045. return;
  44046. }
  44047. }
  44048. mipmapCount = 1;
  44049. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  44050. mipmapCount = Math.max(1, header[off_mipmapCount]);
  44051. }
  44052. var bpp = header[off_RGBbpp];
  44053. for (var face = 0; face < faces; face++) {
  44054. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  44055. width = header[off_width];
  44056. height = header[off_height];
  44057. dataOffset = header[off_size] + 4;
  44058. for (i = 0; i < mipmapCount; ++i) {
  44059. if (info.isRGB) {
  44060. if (bpp === 24) {
  44061. dataLength = width * height * 3;
  44062. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  44063. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  44064. }
  44065. else {
  44066. dataLength = width * height * 4;
  44067. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  44068. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  44069. }
  44070. }
  44071. else if (info.isLuminance) {
  44072. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  44073. var unpaddedRowSize = width;
  44074. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  44075. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  44076. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  44077. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  44078. }
  44079. else {
  44080. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  44081. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  44082. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  44083. }
  44084. dataOffset += dataLength;
  44085. width *= 0.5;
  44086. height *= 0.5;
  44087. width = Math.max(1.0, width);
  44088. height = Math.max(1.0, height);
  44089. }
  44090. }
  44091. };
  44092. return DDSTools;
  44093. }());
  44094. Internals.DDSTools = DDSTools;
  44095. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  44096. })(BABYLON || (BABYLON = {}));
  44097. //# sourceMappingURL=babylon.tools.dds.js.map
  44098. var BABYLON;
  44099. (function (BABYLON) {
  44100. var Internals;
  44101. (function (Internals) {
  44102. /**
  44103. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  44104. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  44105. */
  44106. var KhronosTextureContainer = (function () {
  44107. /**
  44108. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  44109. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  44110. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  44111. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  44112. */
  44113. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  44114. this.arrayBuffer = arrayBuffer;
  44115. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  44116. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  44117. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  44118. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  44119. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  44120. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  44121. BABYLON.Tools.Error("texture missing KTX identifier");
  44122. return;
  44123. }
  44124. // load the reset of the header in native 32 bit int
  44125. var header = new Int32Array(this.arrayBuffer, 12, 13);
  44126. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  44127. var oppositeEndianess = header[0] === 0x01020304;
  44128. // read all the header elements in order they exist in the file, without modification (sans endainness)
  44129. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  44130. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  44131. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  44132. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  44133. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  44134. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  44135. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  44136. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  44137. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  44138. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  44139. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  44140. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  44141. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  44142. if (this.glType !== 0) {
  44143. BABYLON.Tools.Error("only compressed formats currently supported");
  44144. return;
  44145. }
  44146. else {
  44147. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  44148. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  44149. }
  44150. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  44151. BABYLON.Tools.Error("only 2D textures currently supported");
  44152. return;
  44153. }
  44154. if (this.numberOfArrayElements !== 0) {
  44155. BABYLON.Tools.Error("texture arrays not currently supported");
  44156. return;
  44157. }
  44158. if (this.numberOfFaces !== facesExpected) {
  44159. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  44160. return;
  44161. }
  44162. // we now have a completely validated file, so could use existence of loadType as success
  44163. // would need to make this more elaborate & adjust checks above to support more than one load type
  44164. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  44165. }
  44166. // not as fast hardware based, but will probably never need to use
  44167. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  44168. return ((val & 0xFF) << 24)
  44169. | ((val & 0xFF00) << 8)
  44170. | ((val >> 8) & 0xFF00)
  44171. | ((val >> 24) & 0xFF);
  44172. };
  44173. /**
  44174. * It is assumed that the texture has already been created & is currently bound
  44175. */
  44176. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  44177. switch (this.loadType) {
  44178. case KhronosTextureContainer.COMPRESSED_2D:
  44179. this._upload2DCompressedLevels(gl, loadMipmaps);
  44180. break;
  44181. case KhronosTextureContainer.TEX_2D:
  44182. case KhronosTextureContainer.COMPRESSED_3D:
  44183. case KhronosTextureContainer.TEX_3D:
  44184. }
  44185. };
  44186. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  44187. // initialize width & height for level 1
  44188. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  44189. var width = this.pixelWidth;
  44190. var height = this.pixelHeight;
  44191. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  44192. for (var level = 0; level < mipmapCount; level++) {
  44193. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  44194. for (var face = 0; face < this.numberOfFaces; face++) {
  44195. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  44196. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  44197. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  44198. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  44199. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  44200. }
  44201. width = Math.max(1.0, width * 0.5);
  44202. height = Math.max(1.0, height * 0.5);
  44203. }
  44204. };
  44205. return KhronosTextureContainer;
  44206. }());
  44207. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  44208. // load types
  44209. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  44210. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  44211. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  44212. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  44213. Internals.KhronosTextureContainer = KhronosTextureContainer;
  44214. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  44215. })(BABYLON || (BABYLON = {}));
  44216. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  44217. var BABYLON;
  44218. (function (BABYLON) {
  44219. var CannonJSPlugin = (function () {
  44220. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  44221. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  44222. if (iterations === void 0) { iterations = 10; }
  44223. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  44224. this.name = "CannonJSPlugin";
  44225. this._physicsMaterials = [];
  44226. this._fixedTimeStep = 1 / 60;
  44227. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  44228. this._currentCollisionGroup = 2;
  44229. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  44230. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  44231. this._tmpPosition = BABYLON.Vector3.Zero();
  44232. this._tmpQuaternion = new BABYLON.Quaternion();
  44233. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  44234. this._tmpDeltaRotation = new BABYLON.Quaternion();
  44235. this._tmpUnityRotation = new BABYLON.Quaternion();
  44236. if (!this.isSupported()) {
  44237. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  44238. return;
  44239. }
  44240. this.world = new CANNON.World();
  44241. this.world.broadphase = new CANNON.NaiveBroadphase();
  44242. this.world.solver.iterations = iterations;
  44243. }
  44244. CannonJSPlugin.prototype.setGravity = function (gravity) {
  44245. this.world.gravity.copy(gravity);
  44246. };
  44247. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  44248. this._fixedTimeStep = timeStep;
  44249. };
  44250. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  44251. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  44252. };
  44253. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  44254. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  44255. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  44256. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  44257. };
  44258. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  44259. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  44260. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  44261. impostor.physicsBody.applyForce(impulse, worldPoint);
  44262. };
  44263. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  44264. //parent-child relationship. Does this impostor has a parent impostor?
  44265. if (impostor.parent) {
  44266. if (impostor.physicsBody) {
  44267. this.removePhysicsBody(impostor);
  44268. //TODO is that needed?
  44269. impostor.forceUpdate();
  44270. }
  44271. return;
  44272. }
  44273. //should a new body be created for this impostor?
  44274. if (impostor.isBodyInitRequired()) {
  44275. var shape = this._createShape(impostor);
  44276. //unregister events, if body is being changed
  44277. var oldBody = impostor.physicsBody;
  44278. if (oldBody) {
  44279. this.removePhysicsBody(impostor);
  44280. }
  44281. //create the body and material
  44282. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  44283. var bodyCreationObject = {
  44284. mass: impostor.getParam("mass"),
  44285. material: material
  44286. };
  44287. // A simple extend, in case native options were used.
  44288. var nativeOptions = impostor.getParam("nativeOptions");
  44289. for (var key in nativeOptions) {
  44290. if (nativeOptions.hasOwnProperty(key)) {
  44291. bodyCreationObject[key] = nativeOptions[key];
  44292. }
  44293. }
  44294. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  44295. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  44296. this.world.addEventListener("preStep", impostor.beforeStep);
  44297. this.world.addEventListener("postStep", impostor.afterStep);
  44298. impostor.physicsBody.addShape(shape);
  44299. this.world.add(impostor.physicsBody);
  44300. //try to keep the body moving in the right direction by taking old properties.
  44301. //Should be tested!
  44302. if (oldBody) {
  44303. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  44304. impostor.physicsBody[param].copy(oldBody[param]);
  44305. });
  44306. }
  44307. this._processChildMeshes(impostor);
  44308. }
  44309. //now update the body's transformation
  44310. this._updatePhysicsBodyTransformation(impostor);
  44311. };
  44312. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  44313. var _this = this;
  44314. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  44315. if (meshChildren.length) {
  44316. var processMesh = function (localPosition, mesh) {
  44317. var childImpostor = mesh.getPhysicsImpostor();
  44318. if (childImpostor) {
  44319. var parent = childImpostor.parent;
  44320. if (parent !== mainImpostor) {
  44321. var localPosition = mesh.position;
  44322. if (childImpostor.physicsBody) {
  44323. _this.removePhysicsBody(childImpostor);
  44324. childImpostor.physicsBody = null;
  44325. }
  44326. childImpostor.parent = mainImpostor;
  44327. childImpostor.resetUpdateFlags();
  44328. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  44329. //Add the mass of the children.
  44330. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  44331. }
  44332. }
  44333. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  44334. };
  44335. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  44336. }
  44337. };
  44338. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  44339. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  44340. this.world.removeEventListener("preStep", impostor.beforeStep);
  44341. this.world.removeEventListener("postStep", impostor.afterStep);
  44342. this.world.remove(impostor.physicsBody);
  44343. };
  44344. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  44345. var mainBody = impostorJoint.mainImpostor.physicsBody;
  44346. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  44347. if (!mainBody || !connectedBody) {
  44348. return;
  44349. }
  44350. var constraint;
  44351. var jointData = impostorJoint.joint.jointData;
  44352. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  44353. var constraintData = {
  44354. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  44355. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  44356. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  44357. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  44358. maxForce: jointData.nativeParams.maxForce,
  44359. collideConnected: !!jointData.collision
  44360. };
  44361. switch (impostorJoint.joint.type) {
  44362. case BABYLON.PhysicsJoint.HingeJoint:
  44363. case BABYLON.PhysicsJoint.Hinge2Joint:
  44364. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  44365. break;
  44366. case BABYLON.PhysicsJoint.DistanceJoint:
  44367. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  44368. break;
  44369. case BABYLON.PhysicsJoint.SpringJoint:
  44370. var springData = jointData;
  44371. constraint = new CANNON.Spring(mainBody, connectedBody, {
  44372. restLength: springData.length,
  44373. stiffness: springData.stiffness,
  44374. damping: springData.damping,
  44375. localAnchorA: constraintData.pivotA,
  44376. localAnchorB: constraintData.pivotB
  44377. });
  44378. break;
  44379. case BABYLON.PhysicsJoint.LockJoint:
  44380. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  44381. break;
  44382. case BABYLON.PhysicsJoint.PointToPointJoint:
  44383. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  44384. default:
  44385. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  44386. break;
  44387. }
  44388. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  44389. constraint.collideConnected = !!jointData.collision;
  44390. impostorJoint.joint.physicsJoint = constraint;
  44391. //don't add spring as constraint, as it is not one.
  44392. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  44393. this.world.addConstraint(constraint);
  44394. }
  44395. else {
  44396. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  44397. constraint.applyForce();
  44398. });
  44399. }
  44400. };
  44401. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  44402. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  44403. };
  44404. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  44405. var index;
  44406. var mat;
  44407. for (index = 0; index < this._physicsMaterials.length; index++) {
  44408. mat = this._physicsMaterials[index];
  44409. if (mat.friction === friction && mat.restitution === restitution) {
  44410. return mat;
  44411. }
  44412. }
  44413. var currentMat = new CANNON.Material(name);
  44414. currentMat.friction = friction;
  44415. currentMat.restitution = restitution;
  44416. this._physicsMaterials.push(currentMat);
  44417. return currentMat;
  44418. };
  44419. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  44420. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  44421. };
  44422. CannonJSPlugin.prototype._createShape = function (impostor) {
  44423. var object = impostor.object;
  44424. var returnValue;
  44425. var extendSize = impostor.getObjectExtendSize();
  44426. switch (impostor.type) {
  44427. case BABYLON.PhysicsEngine.SphereImpostor:
  44428. var radiusX = extendSize.x;
  44429. var radiusY = extendSize.y;
  44430. var radiusZ = extendSize.z;
  44431. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  44432. break;
  44433. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  44434. case BABYLON.PhysicsImpostor.CylinderImpostor:
  44435. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  44436. break;
  44437. case BABYLON.PhysicsImpostor.BoxImpostor:
  44438. var box = extendSize.scale(0.5);
  44439. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  44440. break;
  44441. case BABYLON.PhysicsImpostor.PlaneImpostor:
  44442. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  44443. returnValue = new CANNON.Plane();
  44444. break;
  44445. case BABYLON.PhysicsImpostor.MeshImpostor:
  44446. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  44447. var rawFaces = object.getIndices ? object.getIndices() : [];
  44448. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  44449. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  44450. break;
  44451. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  44452. returnValue = this._createHeightmap(object);
  44453. break;
  44454. case BABYLON.PhysicsImpostor.ParticleImpostor:
  44455. returnValue = new CANNON.Particle();
  44456. break;
  44457. }
  44458. return returnValue;
  44459. };
  44460. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  44461. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44462. var matrix = [];
  44463. //For now pointDepth will not be used and will be automatically calculated.
  44464. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  44465. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  44466. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  44467. var elementSize = dim * 2 / arraySize;
  44468. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  44469. for (var i = 0; i < pos.length; i = i + 3) {
  44470. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  44471. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  44472. var y = pos[i + 1] + minY;
  44473. if (!matrix[x]) {
  44474. matrix[x] = [];
  44475. }
  44476. if (!matrix[x][z]) {
  44477. matrix[x][z] = y;
  44478. }
  44479. matrix[x][z] = Math.max(y, matrix[x][z]);
  44480. }
  44481. for (var x = 0; x <= arraySize; ++x) {
  44482. if (!matrix[x]) {
  44483. var loc = 1;
  44484. while (!matrix[(x + loc) % arraySize]) {
  44485. loc++;
  44486. }
  44487. matrix[x] = matrix[(x + loc) % arraySize].slice();
  44488. }
  44489. for (var z = 0; z <= arraySize; ++z) {
  44490. if (!matrix[x][z]) {
  44491. var loc = 1;
  44492. var newValue;
  44493. while (newValue === undefined) {
  44494. newValue = matrix[x][(z + loc++) % arraySize];
  44495. }
  44496. matrix[x][z] = newValue;
  44497. }
  44498. }
  44499. }
  44500. var shape = new CANNON.Heightfield(matrix, {
  44501. elementSize: elementSize
  44502. });
  44503. //For future reference, needed for body transformation
  44504. shape.minY = minY;
  44505. return shape;
  44506. };
  44507. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  44508. var object = impostor.object;
  44509. //make sure it is updated...
  44510. object.computeWorldMatrix && object.computeWorldMatrix(true);
  44511. // The delta between the mesh position and the mesh bounding box center
  44512. var center = impostor.getObjectCenter();
  44513. var extendSize = impostor.getObjectExtendSize();
  44514. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  44515. this._tmpPosition.copyFrom(center);
  44516. var quaternion = object.rotationQuaternion;
  44517. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  44518. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  44519. //-90 DEG in X, precalculated
  44520. quaternion = quaternion.multiply(this._minus90X);
  44521. //Invert! (Precalculated, 90 deg in X)
  44522. //No need to clone. this will never change.
  44523. impostor.setDeltaRotation(this._plus90X);
  44524. }
  44525. //If it is a heightfield, if should be centered.
  44526. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  44527. var mesh = object;
  44528. //calculate the correct body position:
  44529. var rotationQuaternion = mesh.rotationQuaternion;
  44530. mesh.rotationQuaternion = this._tmpUnityRotation;
  44531. mesh.computeWorldMatrix(true);
  44532. //get original center with no rotation
  44533. var c = center.clone();
  44534. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  44535. //rotation is back
  44536. mesh.rotationQuaternion = rotationQuaternion;
  44537. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  44538. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  44539. mesh.setPivotMatrix(p);
  44540. mesh.computeWorldMatrix(true);
  44541. //calculate the translation
  44542. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  44543. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  44544. //add it inverted to the delta
  44545. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  44546. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  44547. mesh.setPivotMatrix(oldPivot);
  44548. mesh.computeWorldMatrix(true);
  44549. }
  44550. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  44551. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  44552. this._tmpPosition.copyFrom(object.position);
  44553. }
  44554. impostor.setDeltaPosition(this._tmpDeltaPosition);
  44555. //Now update the impostor object
  44556. impostor.physicsBody.position.copy(this._tmpPosition);
  44557. impostor.physicsBody.quaternion.copy(quaternion);
  44558. };
  44559. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  44560. impostor.object.position.copyFrom(impostor.physicsBody.position);
  44561. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  44562. };
  44563. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  44564. impostor.physicsBody.position.copy(newPosition);
  44565. impostor.physicsBody.quaternion.copy(newRotation);
  44566. };
  44567. CannonJSPlugin.prototype.isSupported = function () {
  44568. return window.CANNON !== undefined;
  44569. };
  44570. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  44571. impostor.physicsBody.velocity.copy(velocity);
  44572. };
  44573. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  44574. impostor.physicsBody.angularVelocity.copy(velocity);
  44575. };
  44576. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  44577. var v = impostor.physicsBody.velocity;
  44578. if (!v)
  44579. return null;
  44580. return new BABYLON.Vector3(v.x, v.y, v.z);
  44581. };
  44582. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  44583. var v = impostor.physicsBody.angularVelocity;
  44584. if (!v)
  44585. return null;
  44586. return new BABYLON.Vector3(v.x, v.y, v.z);
  44587. };
  44588. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  44589. impostor.physicsBody.mass = mass;
  44590. impostor.physicsBody.updateMassProperties();
  44591. };
  44592. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  44593. impostor.physicsBody.sleep();
  44594. };
  44595. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  44596. impostor.physicsBody.wakeUp();
  44597. };
  44598. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  44599. joint.physicsJoint.distance = maxDistance;
  44600. };
  44601. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  44602. if (!motorIndex) {
  44603. joint.physicsJoint.enableMotor();
  44604. }
  44605. };
  44606. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  44607. if (!motorIndex) {
  44608. joint.physicsJoint.disableMotor();
  44609. }
  44610. };
  44611. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  44612. if (!motorIndex) {
  44613. joint.physicsJoint.enableMotor();
  44614. joint.physicsJoint.setMotorSpeed(speed);
  44615. if (maxForce) {
  44616. this.setLimit(joint, maxForce);
  44617. }
  44618. }
  44619. };
  44620. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  44621. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  44622. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  44623. };
  44624. CannonJSPlugin.prototype.dispose = function () {
  44625. //nothing to do, actually.
  44626. };
  44627. return CannonJSPlugin;
  44628. }());
  44629. BABYLON.CannonJSPlugin = CannonJSPlugin;
  44630. })(BABYLON || (BABYLON = {}));
  44631. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  44632. var BABYLON;
  44633. (function (BABYLON) {
  44634. var OimoJSPlugin = (function () {
  44635. function OimoJSPlugin(iterations) {
  44636. this.name = "OimoJSPlugin";
  44637. this._tmpImpostorsArray = [];
  44638. this._tmpPositionVector = BABYLON.Vector3.Zero();
  44639. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  44640. this.world.worldscale(1);
  44641. this.world.clear();
  44642. //making sure no stats are calculated
  44643. this.world.isNoStat = true;
  44644. }
  44645. OimoJSPlugin.prototype.setGravity = function (gravity) {
  44646. this.world.gravity.copy(gravity);
  44647. };
  44648. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  44649. this.world.timeStep = timeStep;
  44650. };
  44651. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  44652. var _this = this;
  44653. impostors.forEach(function (impostor) {
  44654. impostor.beforeStep();
  44655. });
  44656. this.world.step();
  44657. impostors.forEach(function (impostor) {
  44658. impostor.afterStep();
  44659. //update the ordered impostors array
  44660. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  44661. });
  44662. //check for collisions
  44663. var contact = this.world.contacts;
  44664. while (contact !== null) {
  44665. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  44666. contact = contact.next;
  44667. continue;
  44668. }
  44669. //is this body colliding with any other? get the impostor
  44670. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  44671. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  44672. if (!mainImpostor || !collidingImpostor) {
  44673. contact = contact.next;
  44674. continue;
  44675. }
  44676. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  44677. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  44678. contact = contact.next;
  44679. }
  44680. };
  44681. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  44682. var mass = impostor.physicsBody.massInfo.mass;
  44683. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  44684. };
  44685. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  44686. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  44687. this.applyImpulse(impostor, force, contactPoint);
  44688. };
  44689. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  44690. var _this = this;
  44691. //parent-child relationship. Does this impostor has a parent impostor?
  44692. if (impostor.parent) {
  44693. if (impostor.physicsBody) {
  44694. this.removePhysicsBody(impostor);
  44695. //TODO is that needed?
  44696. impostor.forceUpdate();
  44697. }
  44698. return;
  44699. }
  44700. if (impostor.isBodyInitRequired()) {
  44701. var bodyConfig = {
  44702. name: impostor.uniqueId,
  44703. //Oimo must have mass, also for static objects.
  44704. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  44705. size: [],
  44706. type: [],
  44707. pos: [],
  44708. rot: [],
  44709. move: impostor.getParam("mass") !== 0,
  44710. //Supporting older versions of Oimo
  44711. world: this.world
  44712. };
  44713. var impostors = [impostor];
  44714. var addToArray = function (parent) {
  44715. if (!parent.getChildMeshes)
  44716. return;
  44717. parent.getChildMeshes().forEach(function (m) {
  44718. if (m.physicsImpostor) {
  44719. impostors.push(m.physicsImpostor);
  44720. m.physicsImpostor._init();
  44721. }
  44722. });
  44723. };
  44724. addToArray(impostor.object);
  44725. var checkWithEpsilon_1 = function (value) {
  44726. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  44727. };
  44728. impostors.forEach(function (i) {
  44729. //get the correct bounding box
  44730. var oldQuaternion = i.object.rotationQuaternion;
  44731. var rot = new OIMO.Euler().setFromQuaternion({
  44732. x: impostor.object.rotationQuaternion.x,
  44733. y: impostor.object.rotationQuaternion.y,
  44734. z: impostor.object.rotationQuaternion.z,
  44735. s: impostor.object.rotationQuaternion.w
  44736. });
  44737. var extendSize = i.getObjectExtendSize();
  44738. if (i === impostor) {
  44739. var center = impostor.getObjectCenter();
  44740. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  44741. //Can also use Array.prototype.push.apply
  44742. bodyConfig.pos.push(center.x);
  44743. bodyConfig.pos.push(center.y);
  44744. bodyConfig.pos.push(center.z);
  44745. //tmp solution
  44746. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  44747. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  44748. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  44749. }
  44750. else {
  44751. bodyConfig.pos.push(i.object.position.x);
  44752. bodyConfig.pos.push(i.object.position.y);
  44753. bodyConfig.pos.push(i.object.position.z);
  44754. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  44755. bodyConfig.rot.push(0);
  44756. bodyConfig.rot.push(0);
  44757. bodyConfig.rot.push(0);
  44758. }
  44759. // register mesh
  44760. switch (i.type) {
  44761. case BABYLON.PhysicsImpostor.ParticleImpostor:
  44762. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  44763. case BABYLON.PhysicsImpostor.SphereImpostor:
  44764. var radiusX = extendSize.x;
  44765. var radiusY = extendSize.y;
  44766. var radiusZ = extendSize.z;
  44767. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  44768. bodyConfig.type.push('sphere');
  44769. //due to the way oimo works with compounds, add 3 times
  44770. bodyConfig.size.push(size);
  44771. bodyConfig.size.push(size);
  44772. bodyConfig.size.push(size);
  44773. break;
  44774. case BABYLON.PhysicsImpostor.CylinderImpostor:
  44775. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  44776. var sizeY = checkWithEpsilon_1(extendSize.y);
  44777. bodyConfig.type.push('cylinder');
  44778. bodyConfig.size.push(sizeX);
  44779. bodyConfig.size.push(sizeY);
  44780. //due to the way oimo works with compounds, add one more value.
  44781. bodyConfig.size.push(sizeY);
  44782. break;
  44783. case BABYLON.PhysicsImpostor.PlaneImpostor:
  44784. case BABYLON.PhysicsImpostor.BoxImpostor:
  44785. default:
  44786. var sizeX = checkWithEpsilon_1(extendSize.x);
  44787. var sizeY = checkWithEpsilon_1(extendSize.y);
  44788. var sizeZ = checkWithEpsilon_1(extendSize.z);
  44789. bodyConfig.type.push('box');
  44790. bodyConfig.size.push(sizeX);
  44791. bodyConfig.size.push(sizeY);
  44792. bodyConfig.size.push(sizeZ);
  44793. break;
  44794. }
  44795. //actually not needed, but hey...
  44796. i.object.rotationQuaternion = oldQuaternion;
  44797. });
  44798. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  44799. }
  44800. else {
  44801. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  44802. }
  44803. impostor.setDeltaPosition(this._tmpPositionVector);
  44804. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  44805. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  44806. };
  44807. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  44808. //impostor.physicsBody.dispose();
  44809. //Same as : (older oimo versions)
  44810. this.world.removeRigidBody(impostor.physicsBody);
  44811. };
  44812. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  44813. var mainBody = impostorJoint.mainImpostor.physicsBody;
  44814. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  44815. if (!mainBody || !connectedBody) {
  44816. return;
  44817. }
  44818. var jointData = impostorJoint.joint.jointData;
  44819. var options = jointData.nativeParams || {};
  44820. var type;
  44821. var nativeJointData = {
  44822. body1: mainBody,
  44823. body2: connectedBody,
  44824. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  44825. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  44826. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  44827. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  44828. min: options.min,
  44829. max: options.max,
  44830. collision: options.collision || jointData.collision,
  44831. spring: options.spring,
  44832. //supporting older version of Oimo
  44833. world: this.world
  44834. };
  44835. switch (impostorJoint.joint.type) {
  44836. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  44837. type = "jointBall";
  44838. break;
  44839. case BABYLON.PhysicsJoint.SpringJoint:
  44840. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  44841. var springData = jointData;
  44842. nativeJointData.min = springData.length || nativeJointData.min;
  44843. //Max should also be set, just make sure it is at least min
  44844. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  44845. case BABYLON.PhysicsJoint.DistanceJoint:
  44846. type = "jointDistance";
  44847. nativeJointData.max = jointData.maxDistance;
  44848. break;
  44849. case BABYLON.PhysicsJoint.PrismaticJoint:
  44850. type = "jointPrisme";
  44851. break;
  44852. case BABYLON.PhysicsJoint.SliderJoint:
  44853. type = "jointSlide";
  44854. break;
  44855. case BABYLON.PhysicsJoint.WheelJoint:
  44856. type = "jointWheel";
  44857. break;
  44858. case BABYLON.PhysicsJoint.HingeJoint:
  44859. default:
  44860. type = "jointHinge";
  44861. break;
  44862. }
  44863. nativeJointData.type = type;
  44864. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  44865. };
  44866. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  44867. //Bug in Oimo prevents us from disposing a joint in the playground
  44868. //joint.joint.physicsJoint.dispose();
  44869. //So we will bruteforce it!
  44870. try {
  44871. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  44872. }
  44873. catch (e) {
  44874. BABYLON.Tools.Warn(e);
  44875. }
  44876. };
  44877. OimoJSPlugin.prototype.isSupported = function () {
  44878. return OIMO !== undefined;
  44879. };
  44880. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  44881. if (!impostor.physicsBody.sleeping) {
  44882. //TODO check that
  44883. if (impostor.physicsBody.shapes.next) {
  44884. var parentShape = this._getLastShape(impostor.physicsBody);
  44885. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  44886. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  44887. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  44888. }
  44889. else {
  44890. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  44891. }
  44892. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  44893. impostor.object.rotationQuaternion.normalize();
  44894. }
  44895. };
  44896. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  44897. var body = impostor.physicsBody;
  44898. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  44899. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  44900. body.syncShapes();
  44901. body.awake();
  44902. };
  44903. OimoJSPlugin.prototype._getLastShape = function (body) {
  44904. var lastShape = body.shapes;
  44905. while (lastShape.next) {
  44906. lastShape = lastShape.next;
  44907. }
  44908. return lastShape;
  44909. };
  44910. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  44911. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  44912. };
  44913. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  44914. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  44915. };
  44916. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  44917. var v = impostor.physicsBody.linearVelocity;
  44918. if (!v)
  44919. return null;
  44920. return new BABYLON.Vector3(v.x, v.y, v.z);
  44921. };
  44922. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  44923. var v = impostor.physicsBody.angularVelocity;
  44924. if (!v)
  44925. return null;
  44926. return new BABYLON.Vector3(v.x, v.y, v.z);
  44927. };
  44928. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  44929. var staticBody = mass === 0;
  44930. //this will actually set the body's density and not its mass.
  44931. //But this is how oimo treats the mass variable.
  44932. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  44933. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  44934. };
  44935. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  44936. impostor.physicsBody.sleep();
  44937. };
  44938. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  44939. impostor.physicsBody.awake();
  44940. };
  44941. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  44942. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  44943. if (minDistance !== void 0) {
  44944. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  44945. }
  44946. };
  44947. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  44948. //TODO separate rotational and transational motors.
  44949. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  44950. if (motor) {
  44951. motor.setMotor(speed, maxForce);
  44952. }
  44953. };
  44954. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  44955. //TODO separate rotational and transational motors.
  44956. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  44957. if (motor) {
  44958. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  44959. }
  44960. };
  44961. OimoJSPlugin.prototype.dispose = function () {
  44962. this.world.clear();
  44963. };
  44964. return OimoJSPlugin;
  44965. }());
  44966. BABYLON.OimoJSPlugin = OimoJSPlugin;
  44967. })(BABYLON || (BABYLON = {}));
  44968. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  44969. var BABYLON;
  44970. (function (BABYLON) {
  44971. var DisplayPassPostProcess = (function (_super) {
  44972. __extends(DisplayPassPostProcess, _super);
  44973. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  44974. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  44975. }
  44976. return DisplayPassPostProcess;
  44977. }(BABYLON.PostProcess));
  44978. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  44979. })(BABYLON || (BABYLON = {}));
  44980. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  44981. var BABYLON;
  44982. (function (BABYLON) {
  44983. var SimplificationSettings = (function () {
  44984. function SimplificationSettings(quality, distance, optimizeMesh) {
  44985. this.quality = quality;
  44986. this.distance = distance;
  44987. this.optimizeMesh = optimizeMesh;
  44988. }
  44989. return SimplificationSettings;
  44990. }());
  44991. BABYLON.SimplificationSettings = SimplificationSettings;
  44992. var SimplificationQueue = (function () {
  44993. function SimplificationQueue() {
  44994. this.running = false;
  44995. this._simplificationArray = [];
  44996. }
  44997. SimplificationQueue.prototype.addTask = function (task) {
  44998. this._simplificationArray.push(task);
  44999. };
  45000. SimplificationQueue.prototype.executeNext = function () {
  45001. var task = this._simplificationArray.pop();
  45002. if (task) {
  45003. this.running = true;
  45004. this.runSimplification(task);
  45005. }
  45006. else {
  45007. this.running = false;
  45008. }
  45009. };
  45010. SimplificationQueue.prototype.runSimplification = function (task) {
  45011. var _this = this;
  45012. if (task.parallelProcessing) {
  45013. //parallel simplifier
  45014. task.settings.forEach(function (setting) {
  45015. var simplifier = _this.getSimplifier(task);
  45016. simplifier.simplify(setting, function (newMesh) {
  45017. task.mesh.addLODLevel(setting.distance, newMesh);
  45018. newMesh.isVisible = true;
  45019. //check if it is the last
  45020. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  45021. //all done, run the success callback.
  45022. task.successCallback();
  45023. }
  45024. _this.executeNext();
  45025. });
  45026. });
  45027. }
  45028. else {
  45029. //single simplifier.
  45030. var simplifier = this.getSimplifier(task);
  45031. var runDecimation = function (setting, callback) {
  45032. simplifier.simplify(setting, function (newMesh) {
  45033. task.mesh.addLODLevel(setting.distance, newMesh);
  45034. newMesh.isVisible = true;
  45035. //run the next quality level
  45036. callback();
  45037. });
  45038. };
  45039. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  45040. runDecimation(task.settings[loop.index], function () {
  45041. loop.executeNext();
  45042. });
  45043. }, function () {
  45044. //execution ended, run the success callback.
  45045. if (task.successCallback) {
  45046. task.successCallback();
  45047. }
  45048. _this.executeNext();
  45049. });
  45050. }
  45051. };
  45052. SimplificationQueue.prototype.getSimplifier = function (task) {
  45053. switch (task.simplificationType) {
  45054. case SimplificationType.QUADRATIC:
  45055. default:
  45056. return new QuadraticErrorSimplification(task.mesh);
  45057. }
  45058. };
  45059. return SimplificationQueue;
  45060. }());
  45061. BABYLON.SimplificationQueue = SimplificationQueue;
  45062. /**
  45063. * The implemented types of simplification.
  45064. * At the moment only Quadratic Error Decimation is implemented.
  45065. */
  45066. var SimplificationType;
  45067. (function (SimplificationType) {
  45068. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  45069. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  45070. var DecimationTriangle = (function () {
  45071. function DecimationTriangle(vertices) {
  45072. this.vertices = vertices;
  45073. this.error = new Array(4);
  45074. this.deleted = false;
  45075. this.isDirty = false;
  45076. this.deletePending = false;
  45077. this.borderFactor = 0;
  45078. }
  45079. return DecimationTriangle;
  45080. }());
  45081. BABYLON.DecimationTriangle = DecimationTriangle;
  45082. var DecimationVertex = (function () {
  45083. function DecimationVertex(position, id) {
  45084. this.position = position;
  45085. this.id = id;
  45086. this.isBorder = true;
  45087. this.q = new QuadraticMatrix();
  45088. this.triangleCount = 0;
  45089. this.triangleStart = 0;
  45090. this.originalOffsets = [];
  45091. }
  45092. DecimationVertex.prototype.updatePosition = function (newPosition) {
  45093. this.position.copyFrom(newPosition);
  45094. };
  45095. return DecimationVertex;
  45096. }());
  45097. BABYLON.DecimationVertex = DecimationVertex;
  45098. var QuadraticMatrix = (function () {
  45099. function QuadraticMatrix(data) {
  45100. this.data = new Array(10);
  45101. for (var i = 0; i < 10; ++i) {
  45102. if (data && data[i]) {
  45103. this.data[i] = data[i];
  45104. }
  45105. else {
  45106. this.data[i] = 0;
  45107. }
  45108. }
  45109. }
  45110. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  45111. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  45112. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  45113. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  45114. return det;
  45115. };
  45116. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  45117. for (var i = 0; i < 10; ++i) {
  45118. this.data[i] += matrix.data[i];
  45119. }
  45120. };
  45121. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  45122. for (var i = 0; i < 10; ++i) {
  45123. this.data[i] += data[i];
  45124. }
  45125. };
  45126. QuadraticMatrix.prototype.add = function (matrix) {
  45127. var m = new QuadraticMatrix();
  45128. for (var i = 0; i < 10; ++i) {
  45129. m.data[i] = this.data[i] + matrix.data[i];
  45130. }
  45131. return m;
  45132. };
  45133. QuadraticMatrix.FromData = function (a, b, c, d) {
  45134. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  45135. };
  45136. //returning an array to avoid garbage collection
  45137. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  45138. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  45139. };
  45140. return QuadraticMatrix;
  45141. }());
  45142. BABYLON.QuadraticMatrix = QuadraticMatrix;
  45143. var Reference = (function () {
  45144. function Reference(vertexId, triangleId) {
  45145. this.vertexId = vertexId;
  45146. this.triangleId = triangleId;
  45147. }
  45148. return Reference;
  45149. }());
  45150. BABYLON.Reference = Reference;
  45151. /**
  45152. * An implementation of the Quadratic Error simplification algorithm.
  45153. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  45154. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  45155. * @author RaananW
  45156. */
  45157. var QuadraticErrorSimplification = (function () {
  45158. function QuadraticErrorSimplification(_mesh) {
  45159. this._mesh = _mesh;
  45160. this.initialized = false;
  45161. this.syncIterations = 5000;
  45162. this.aggressiveness = 7;
  45163. this.decimationIterations = 100;
  45164. this.boundingBoxEpsilon = BABYLON.Epsilon;
  45165. }
  45166. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  45167. var _this = this;
  45168. this.initDecimatedMesh();
  45169. //iterating through the submeshes array, one after the other.
  45170. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  45171. _this.initWithMesh(loop.index, function () {
  45172. _this.runDecimation(settings, loop.index, function () {
  45173. loop.executeNext();
  45174. });
  45175. }, settings.optimizeMesh);
  45176. }, function () {
  45177. setTimeout(function () {
  45178. successCallback(_this._reconstructedMesh);
  45179. }, 0);
  45180. });
  45181. };
  45182. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  45183. var _this = this;
  45184. var gCount = 0;
  45185. triangle.vertices.forEach(function (vertex) {
  45186. var count = 0;
  45187. var vPos = vertex.position;
  45188. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  45189. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  45190. ++count;
  45191. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  45192. ++count;
  45193. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  45194. ++count;
  45195. if (count > 1) {
  45196. ++gCount;
  45197. }
  45198. ;
  45199. });
  45200. if (gCount > 1) {
  45201. console.log(triangle, gCount);
  45202. }
  45203. return gCount > 1;
  45204. };
  45205. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  45206. var _this = this;
  45207. var targetCount = ~~(this.triangles.length * settings.quality);
  45208. var deletedTriangles = 0;
  45209. var triangleCount = this.triangles.length;
  45210. var iterationFunction = function (iteration, callback) {
  45211. setTimeout(function () {
  45212. if (iteration % 5 === 0) {
  45213. _this.updateMesh(iteration === 0);
  45214. }
  45215. for (var i = 0; i < _this.triangles.length; ++i) {
  45216. _this.triangles[i].isDirty = false;
  45217. }
  45218. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  45219. var trianglesIterator = function (i) {
  45220. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  45221. var t = _this.triangles[tIdx];
  45222. if (!t)
  45223. return;
  45224. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  45225. return;
  45226. }
  45227. for (var j = 0; j < 3; ++j) {
  45228. if (t.error[j] < threshold) {
  45229. var deleted0 = [];
  45230. var deleted1 = [];
  45231. var v0 = t.vertices[j];
  45232. var v1 = t.vertices[(j + 1) % 3];
  45233. if (v0.isBorder || v1.isBorder)
  45234. continue;
  45235. var p = BABYLON.Vector3.Zero();
  45236. var n = BABYLON.Vector3.Zero();
  45237. var uv = BABYLON.Vector2.Zero();
  45238. var color = new BABYLON.Color4(0, 0, 0, 1);
  45239. _this.calculateError(v0, v1, p, n, uv, color);
  45240. var delTr = [];
  45241. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  45242. continue;
  45243. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  45244. continue;
  45245. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  45246. continue;
  45247. var uniqueArray = [];
  45248. delTr.forEach(function (deletedT) {
  45249. if (uniqueArray.indexOf(deletedT) === -1) {
  45250. deletedT.deletePending = true;
  45251. uniqueArray.push(deletedT);
  45252. }
  45253. });
  45254. if (uniqueArray.length % 2 !== 0) {
  45255. continue;
  45256. }
  45257. v0.q = v1.q.add(v0.q);
  45258. v0.updatePosition(p);
  45259. var tStart = _this.references.length;
  45260. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  45261. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  45262. var tCount = _this.references.length - tStart;
  45263. if (tCount <= v0.triangleCount) {
  45264. if (tCount) {
  45265. for (var c = 0; c < tCount; c++) {
  45266. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  45267. }
  45268. }
  45269. }
  45270. else {
  45271. v0.triangleStart = tStart;
  45272. }
  45273. v0.triangleCount = tCount;
  45274. break;
  45275. }
  45276. }
  45277. };
  45278. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  45279. }, 0);
  45280. };
  45281. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  45282. if (triangleCount - deletedTriangles <= targetCount)
  45283. loop.breakLoop();
  45284. else {
  45285. iterationFunction(loop.index, function () {
  45286. loop.executeNext();
  45287. });
  45288. }
  45289. }, function () {
  45290. setTimeout(function () {
  45291. //reconstruct this part of the mesh
  45292. _this.reconstructMesh(submeshIndex);
  45293. successCallback();
  45294. }, 0);
  45295. });
  45296. };
  45297. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  45298. var _this = this;
  45299. this.vertices = [];
  45300. this.triangles = [];
  45301. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45302. var indices = this._mesh.getIndices();
  45303. var submesh = this._mesh.subMeshes[submeshIndex];
  45304. var findInVertices = function (positionToSearch) {
  45305. if (optimizeMesh) {
  45306. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  45307. if (_this.vertices[ii].position.equals(positionToSearch)) {
  45308. return _this.vertices[ii];
  45309. }
  45310. }
  45311. }
  45312. return null;
  45313. };
  45314. var vertexReferences = [];
  45315. var vertexInit = function (i) {
  45316. var offset = i + submesh.verticesStart;
  45317. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  45318. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  45319. vertex.originalOffsets.push(offset);
  45320. if (vertex.id === _this.vertices.length) {
  45321. _this.vertices.push(vertex);
  45322. }
  45323. vertexReferences.push(vertex.id);
  45324. };
  45325. //var totalVertices = mesh.getTotalVertices();
  45326. var totalVertices = submesh.verticesCount;
  45327. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  45328. var indicesInit = function (i) {
  45329. var offset = (submesh.indexStart / 3) + i;
  45330. var pos = (offset * 3);
  45331. var i0 = indices[pos + 0];
  45332. var i1 = indices[pos + 1];
  45333. var i2 = indices[pos + 2];
  45334. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  45335. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  45336. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  45337. var triangle = new DecimationTriangle([v0, v1, v2]);
  45338. triangle.originalOffset = pos;
  45339. _this.triangles.push(triangle);
  45340. };
  45341. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  45342. _this.init(callback);
  45343. });
  45344. });
  45345. };
  45346. QuadraticErrorSimplification.prototype.init = function (callback) {
  45347. var _this = this;
  45348. var triangleInit1 = function (i) {
  45349. var t = _this.triangles[i];
  45350. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  45351. for (var j = 0; j < 3; j++) {
  45352. 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))));
  45353. }
  45354. };
  45355. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  45356. var triangleInit2 = function (i) {
  45357. var t = _this.triangles[i];
  45358. for (var j = 0; j < 3; ++j) {
  45359. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  45360. }
  45361. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  45362. };
  45363. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  45364. _this.initialized = true;
  45365. callback();
  45366. });
  45367. });
  45368. };
  45369. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  45370. var newTriangles = [];
  45371. var i;
  45372. for (i = 0; i < this.vertices.length; ++i) {
  45373. this.vertices[i].triangleCount = 0;
  45374. }
  45375. var t;
  45376. var j;
  45377. for (i = 0; i < this.triangles.length; ++i) {
  45378. if (!this.triangles[i].deleted) {
  45379. t = this.triangles[i];
  45380. for (j = 0; j < 3; ++j) {
  45381. t.vertices[j].triangleCount = 1;
  45382. }
  45383. newTriangles.push(t);
  45384. }
  45385. }
  45386. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  45387. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  45388. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  45389. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  45390. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45391. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45392. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45393. var vertexCount = 0;
  45394. for (i = 0; i < this.vertices.length; ++i) {
  45395. var vertex = this.vertices[i];
  45396. vertex.id = vertexCount;
  45397. if (vertex.triangleCount) {
  45398. vertex.originalOffsets.forEach(function (originalOffset) {
  45399. newPositionData.push(vertex.position.x);
  45400. newPositionData.push(vertex.position.y);
  45401. newPositionData.push(vertex.position.z);
  45402. newNormalData.push(normalData[originalOffset * 3]);
  45403. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  45404. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  45405. if (uvs && uvs.length) {
  45406. newUVsData.push(uvs[(originalOffset * 2)]);
  45407. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  45408. }
  45409. else if (colorsData && colorsData.length) {
  45410. newColorsData.push(colorsData[(originalOffset * 4)]);
  45411. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  45412. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  45413. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  45414. }
  45415. ++vertexCount;
  45416. });
  45417. }
  45418. }
  45419. var startingIndex = this._reconstructedMesh.getTotalIndices();
  45420. var startingVertex = this._reconstructedMesh.getTotalVertices();
  45421. var submeshesArray = this._reconstructedMesh.subMeshes;
  45422. this._reconstructedMesh.subMeshes = [];
  45423. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  45424. var originalIndices = this._mesh.getIndices();
  45425. for (i = 0; i < newTriangles.length; ++i) {
  45426. t = newTriangles[i]; //now get the new referencing point for each vertex
  45427. [0, 1, 2].forEach(function (idx) {
  45428. var id = originalIndices[t.originalOffset + idx];
  45429. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  45430. if (offset < 0)
  45431. offset = 0;
  45432. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  45433. });
  45434. }
  45435. //overwriting the old vertex buffers and indices.
  45436. this._reconstructedMesh.setIndices(newIndicesArray);
  45437. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  45438. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  45439. if (newUVsData.length > 0)
  45440. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  45441. if (newColorsData.length > 0)
  45442. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  45443. //create submesh
  45444. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  45445. if (submeshIndex > 0) {
  45446. this._reconstructedMesh.subMeshes = [];
  45447. submeshesArray.forEach(function (submesh) {
  45448. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  45449. });
  45450. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  45451. }
  45452. };
  45453. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  45454. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  45455. this._reconstructedMesh.material = this._mesh.material;
  45456. this._reconstructedMesh.parent = this._mesh.parent;
  45457. this._reconstructedMesh.isVisible = false;
  45458. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  45459. };
  45460. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  45461. for (var i = 0; i < vertex1.triangleCount; ++i) {
  45462. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  45463. if (t.deleted)
  45464. continue;
  45465. var s = this.references[vertex1.triangleStart + i].vertexId;
  45466. var v1 = t.vertices[(s + 1) % 3];
  45467. var v2 = t.vertices[(s + 2) % 3];
  45468. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  45469. deletedArray[i] = true;
  45470. delTr.push(t);
  45471. continue;
  45472. }
  45473. var d1 = v1.position.subtract(point);
  45474. d1 = d1.normalize();
  45475. var d2 = v2.position.subtract(point);
  45476. d2 = d2.normalize();
  45477. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  45478. return true;
  45479. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  45480. deletedArray[i] = false;
  45481. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  45482. return true;
  45483. }
  45484. return false;
  45485. };
  45486. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  45487. var newDeleted = deletedTriangles;
  45488. for (var i = 0; i < vertex.triangleCount; ++i) {
  45489. var ref = this.references[vertex.triangleStart + i];
  45490. var t = this.triangles[ref.triangleId];
  45491. if (t.deleted)
  45492. continue;
  45493. if (deletedArray[i] && t.deletePending) {
  45494. t.deleted = true;
  45495. newDeleted++;
  45496. continue;
  45497. }
  45498. t.vertices[ref.vertexId] = origVertex;
  45499. t.isDirty = true;
  45500. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  45501. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  45502. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  45503. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  45504. this.references.push(ref);
  45505. }
  45506. return newDeleted;
  45507. };
  45508. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  45509. for (var i = 0; i < this.vertices.length; ++i) {
  45510. var vCount = [];
  45511. var vId = [];
  45512. var v = this.vertices[i];
  45513. var j;
  45514. for (j = 0; j < v.triangleCount; ++j) {
  45515. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  45516. for (var ii = 0; ii < 3; ii++) {
  45517. var ofs = 0;
  45518. var vv = triangle.vertices[ii];
  45519. while (ofs < vCount.length) {
  45520. if (vId[ofs] === vv.id)
  45521. break;
  45522. ++ofs;
  45523. }
  45524. if (ofs === vCount.length) {
  45525. vCount.push(1);
  45526. vId.push(vv.id);
  45527. }
  45528. else {
  45529. vCount[ofs]++;
  45530. }
  45531. }
  45532. }
  45533. for (j = 0; j < vCount.length; ++j) {
  45534. if (vCount[j] === 1) {
  45535. this.vertices[vId[j]].isBorder = true;
  45536. }
  45537. else {
  45538. this.vertices[vId[j]].isBorder = false;
  45539. }
  45540. }
  45541. }
  45542. };
  45543. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  45544. if (identifyBorders === void 0) { identifyBorders = false; }
  45545. var i;
  45546. if (!identifyBorders) {
  45547. var newTrianglesVector = [];
  45548. for (i = 0; i < this.triangles.length; ++i) {
  45549. if (!this.triangles[i].deleted) {
  45550. newTrianglesVector.push(this.triangles[i]);
  45551. }
  45552. }
  45553. this.triangles = newTrianglesVector;
  45554. }
  45555. for (i = 0; i < this.vertices.length; ++i) {
  45556. this.vertices[i].triangleCount = 0;
  45557. this.vertices[i].triangleStart = 0;
  45558. }
  45559. var t;
  45560. var j;
  45561. var v;
  45562. for (i = 0; i < this.triangles.length; ++i) {
  45563. t = this.triangles[i];
  45564. for (j = 0; j < 3; ++j) {
  45565. v = t.vertices[j];
  45566. v.triangleCount++;
  45567. }
  45568. }
  45569. var tStart = 0;
  45570. for (i = 0; i < this.vertices.length; ++i) {
  45571. this.vertices[i].triangleStart = tStart;
  45572. tStart += this.vertices[i].triangleCount;
  45573. this.vertices[i].triangleCount = 0;
  45574. }
  45575. var newReferences = new Array(this.triangles.length * 3);
  45576. for (i = 0; i < this.triangles.length; ++i) {
  45577. t = this.triangles[i];
  45578. for (j = 0; j < 3; ++j) {
  45579. v = t.vertices[j];
  45580. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  45581. v.triangleCount++;
  45582. }
  45583. }
  45584. this.references = newReferences;
  45585. if (identifyBorders) {
  45586. this.identifyBorder();
  45587. }
  45588. };
  45589. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  45590. var x = point.x;
  45591. var y = point.y;
  45592. var z = point.z;
  45593. 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
  45594. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  45595. };
  45596. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  45597. var q = vertex1.q.add(vertex2.q);
  45598. var border = vertex1.isBorder && vertex2.isBorder;
  45599. var error = 0;
  45600. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  45601. if (qDet !== 0 && !border) {
  45602. if (!pointResult) {
  45603. pointResult = BABYLON.Vector3.Zero();
  45604. }
  45605. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  45606. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  45607. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  45608. error = this.vertexError(q, pointResult);
  45609. }
  45610. else {
  45611. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  45612. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  45613. var error1 = this.vertexError(q, vertex1.position);
  45614. var error2 = this.vertexError(q, vertex2.position);
  45615. var error3 = this.vertexError(q, p3);
  45616. error = Math.min(error1, error2, error3);
  45617. if (error === error1) {
  45618. if (pointResult) {
  45619. pointResult.copyFrom(vertex1.position);
  45620. }
  45621. }
  45622. else if (error === error2) {
  45623. if (pointResult) {
  45624. pointResult.copyFrom(vertex2.position);
  45625. }
  45626. }
  45627. else {
  45628. if (pointResult) {
  45629. pointResult.copyFrom(p3);
  45630. }
  45631. }
  45632. }
  45633. return error;
  45634. };
  45635. return QuadraticErrorSimplification;
  45636. }());
  45637. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  45638. })(BABYLON || (BABYLON = {}));
  45639. //# sourceMappingURL=babylon.meshSimplification.js.map
  45640. var BABYLON;
  45641. (function (BABYLON) {
  45642. var serializedGeometries = [];
  45643. var serializeGeometry = function (geometry, serializationGeometries) {
  45644. if (serializedGeometries[geometry.id]) {
  45645. return;
  45646. }
  45647. if (geometry.doNotSerialize) {
  45648. return;
  45649. }
  45650. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  45651. serializationGeometries.boxes.push(geometry.serialize());
  45652. }
  45653. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  45654. serializationGeometries.spheres.push(geometry.serialize());
  45655. }
  45656. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  45657. serializationGeometries.cylinders.push(geometry.serialize());
  45658. }
  45659. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  45660. serializationGeometries.toruses.push(geometry.serialize());
  45661. }
  45662. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  45663. serializationGeometries.grounds.push(geometry.serialize());
  45664. }
  45665. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  45666. serializationGeometries.planes.push(geometry.serialize());
  45667. }
  45668. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  45669. serializationGeometries.torusKnots.push(geometry.serialize());
  45670. }
  45671. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  45672. throw new Error("Unknown primitive type");
  45673. }
  45674. else {
  45675. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  45676. }
  45677. serializedGeometries[geometry.id] = true;
  45678. };
  45679. var serializeMesh = function (mesh, serializationScene) {
  45680. var serializationObject = {};
  45681. serializationObject.name = mesh.name;
  45682. serializationObject.id = mesh.id;
  45683. if (BABYLON.Tags.HasTags(mesh)) {
  45684. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  45685. }
  45686. serializationObject.position = mesh.position.asArray();
  45687. if (mesh.rotationQuaternion) {
  45688. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  45689. }
  45690. else if (mesh.rotation) {
  45691. serializationObject.rotation = mesh.rotation.asArray();
  45692. }
  45693. serializationObject.scaling = mesh.scaling.asArray();
  45694. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  45695. serializationObject.isEnabled = mesh.isEnabled();
  45696. serializationObject.isVisible = mesh.isVisible;
  45697. serializationObject.infiniteDistance = mesh.infiniteDistance;
  45698. serializationObject.pickable = mesh.isPickable;
  45699. serializationObject.receiveShadows = mesh.receiveShadows;
  45700. serializationObject.billboardMode = mesh.billboardMode;
  45701. serializationObject.visibility = mesh.visibility;
  45702. serializationObject.checkCollisions = mesh.checkCollisions;
  45703. serializationObject.isBlocker = mesh.isBlocker;
  45704. // Parent
  45705. if (mesh.parent) {
  45706. serializationObject.parentId = mesh.parent.id;
  45707. }
  45708. // Geometry
  45709. var geometry = mesh._geometry;
  45710. if (geometry) {
  45711. var geometryId = geometry.id;
  45712. serializationObject.geometryId = geometryId;
  45713. if (!mesh.getScene().getGeometryByID(geometryId)) {
  45714. // 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
  45715. serializeGeometry(geometry, serializationScene.geometries);
  45716. }
  45717. // SubMeshes
  45718. serializationObject.subMeshes = [];
  45719. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  45720. var subMesh = mesh.subMeshes[subIndex];
  45721. serializationObject.subMeshes.push({
  45722. materialIndex: subMesh.materialIndex,
  45723. verticesStart: subMesh.verticesStart,
  45724. verticesCount: subMesh.verticesCount,
  45725. indexStart: subMesh.indexStart,
  45726. indexCount: subMesh.indexCount
  45727. });
  45728. }
  45729. }
  45730. // Material
  45731. if (mesh.material) {
  45732. serializationObject.materialId = mesh.material.id;
  45733. }
  45734. else {
  45735. mesh.material = null;
  45736. }
  45737. // Skeleton
  45738. if (mesh.skeleton) {
  45739. serializationObject.skeletonId = mesh.skeleton.id;
  45740. }
  45741. // Physics
  45742. //TODO implement correct serialization for physics impostors.
  45743. if (mesh.getPhysicsImpostor()) {
  45744. serializationObject.physicsMass = mesh.getPhysicsMass();
  45745. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  45746. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  45747. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  45748. }
  45749. // Metadata
  45750. if (mesh.metadata) {
  45751. serializationObject.metadata = mesh.metadata;
  45752. }
  45753. // Instances
  45754. serializationObject.instances = [];
  45755. for (var index = 0; index < mesh.instances.length; index++) {
  45756. var instance = mesh.instances[index];
  45757. var serializationInstance = {
  45758. name: instance.name,
  45759. position: instance.position.asArray(),
  45760. scaling: instance.scaling.asArray()
  45761. };
  45762. if (instance.rotationQuaternion) {
  45763. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  45764. }
  45765. else if (instance.rotation) {
  45766. serializationInstance.rotation = instance.rotation.asArray();
  45767. }
  45768. serializationObject.instances.push(serializationInstance);
  45769. // Animations
  45770. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  45771. serializationInstance.ranges = instance.serializeAnimationRanges();
  45772. }
  45773. // Animations
  45774. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  45775. serializationObject.ranges = mesh.serializeAnimationRanges();
  45776. // Layer mask
  45777. serializationObject.layerMask = mesh.layerMask;
  45778. // Alpha
  45779. serializationObject.alphaIndex = mesh.alphaIndex;
  45780. serializationObject.hasVertexAlpha = mesh.hasVertexAlpha;
  45781. // Overlay
  45782. serializationObject.overlayAlpha = mesh.overlayAlpha;
  45783. serializationObject.overlayColor = mesh.overlayColor.asArray();
  45784. serializationObject.renderOverlay = mesh.renderOverlay;
  45785. // Fog
  45786. serializationObject.applyFog = mesh.applyFog;
  45787. // Action Manager
  45788. if (mesh.actionManager) {
  45789. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  45790. }
  45791. return serializationObject;
  45792. };
  45793. var finalizeSingleMesh = function (mesh, serializationObject) {
  45794. //only works if the mesh is already loaded
  45795. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  45796. //serialize material
  45797. if (mesh.material) {
  45798. if (mesh.material instanceof BABYLON.StandardMaterial) {
  45799. serializationObject.materials = serializationObject.materials || [];
  45800. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  45801. serializationObject.materials.push(mesh.material.serialize());
  45802. }
  45803. }
  45804. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  45805. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  45806. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  45807. serializationObject.multiMaterials.push(mesh.material.serialize());
  45808. }
  45809. }
  45810. }
  45811. //serialize geometry
  45812. var geometry = mesh._geometry;
  45813. if (geometry) {
  45814. if (!serializationObject.geometries) {
  45815. serializationObject.geometries = {};
  45816. serializationObject.geometries.boxes = [];
  45817. serializationObject.geometries.spheres = [];
  45818. serializationObject.geometries.cylinders = [];
  45819. serializationObject.geometries.toruses = [];
  45820. serializationObject.geometries.grounds = [];
  45821. serializationObject.geometries.planes = [];
  45822. serializationObject.geometries.torusKnots = [];
  45823. serializationObject.geometries.vertexData = [];
  45824. }
  45825. serializeGeometry(geometry, serializationObject.geometries);
  45826. }
  45827. // Skeletons
  45828. if (mesh.skeleton) {
  45829. serializationObject.skeletons = serializationObject.skeletons || [];
  45830. serializationObject.skeletons.push(mesh.skeleton.serialize());
  45831. }
  45832. //serialize the actual mesh
  45833. serializationObject.meshes = serializationObject.meshes || [];
  45834. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  45835. }
  45836. };
  45837. var SceneSerializer = (function () {
  45838. function SceneSerializer() {
  45839. }
  45840. SceneSerializer.ClearCache = function () {
  45841. serializedGeometries = [];
  45842. };
  45843. SceneSerializer.Serialize = function (scene) {
  45844. var serializationObject = {};
  45845. // Scene
  45846. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  45847. serializationObject.autoClear = scene.autoClear;
  45848. serializationObject.clearColor = scene.clearColor.asArray();
  45849. serializationObject.ambientColor = scene.ambientColor.asArray();
  45850. serializationObject.gravity = scene.gravity.asArray();
  45851. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  45852. serializationObject.workerCollisions = scene.workerCollisions;
  45853. // Fog
  45854. if (scene.fogMode && scene.fogMode !== 0) {
  45855. serializationObject.fogMode = scene.fogMode;
  45856. serializationObject.fogColor = scene.fogColor.asArray();
  45857. serializationObject.fogStart = scene.fogStart;
  45858. serializationObject.fogEnd = scene.fogEnd;
  45859. serializationObject.fogDensity = scene.fogDensity;
  45860. }
  45861. //Physics
  45862. if (scene.isPhysicsEnabled()) {
  45863. serializationObject.physicsEnabled = true;
  45864. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  45865. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  45866. }
  45867. // Metadata
  45868. if (scene.metadata) {
  45869. serializationObject.metadata = scene.metadata;
  45870. }
  45871. // Lights
  45872. serializationObject.lights = [];
  45873. var index;
  45874. var light;
  45875. for (index = 0; index < scene.lights.length; index++) {
  45876. light = scene.lights[index];
  45877. if (!light.doNotSerialize) {
  45878. serializationObject.lights.push(light.serialize());
  45879. }
  45880. }
  45881. // Cameras
  45882. serializationObject.cameras = [];
  45883. for (index = 0; index < scene.cameras.length; index++) {
  45884. var camera = scene.cameras[index];
  45885. if (!camera.doNotSerialize) {
  45886. serializationObject.cameras.push(camera.serialize());
  45887. }
  45888. }
  45889. if (scene.activeCamera) {
  45890. serializationObject.activeCameraID = scene.activeCamera.id;
  45891. }
  45892. // Animations
  45893. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  45894. // Materials
  45895. serializationObject.materials = [];
  45896. serializationObject.multiMaterials = [];
  45897. var material;
  45898. for (index = 0; index < scene.materials.length; index++) {
  45899. material = scene.materials[index];
  45900. if (!material.doNotSerialize) {
  45901. serializationObject.materials.push(material.serialize());
  45902. }
  45903. }
  45904. // MultiMaterials
  45905. serializationObject.multiMaterials = [];
  45906. for (index = 0; index < scene.multiMaterials.length; index++) {
  45907. var multiMaterial = scene.multiMaterials[index];
  45908. serializationObject.multiMaterials.push(multiMaterial.serialize());
  45909. }
  45910. // Skeletons
  45911. serializationObject.skeletons = [];
  45912. for (index = 0; index < scene.skeletons.length; index++) {
  45913. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  45914. }
  45915. // Geometries
  45916. serializationObject.geometries = {};
  45917. serializationObject.geometries.boxes = [];
  45918. serializationObject.geometries.spheres = [];
  45919. serializationObject.geometries.cylinders = [];
  45920. serializationObject.geometries.toruses = [];
  45921. serializationObject.geometries.grounds = [];
  45922. serializationObject.geometries.planes = [];
  45923. serializationObject.geometries.torusKnots = [];
  45924. serializationObject.geometries.vertexData = [];
  45925. serializedGeometries = [];
  45926. var geometries = scene.getGeometries();
  45927. for (index = 0; index < geometries.length; index++) {
  45928. var geometry = geometries[index];
  45929. if (geometry.isReady()) {
  45930. serializeGeometry(geometry, serializationObject.geometries);
  45931. }
  45932. }
  45933. // Meshes
  45934. serializationObject.meshes = [];
  45935. for (index = 0; index < scene.meshes.length; index++) {
  45936. var abstractMesh = scene.meshes[index];
  45937. if (abstractMesh instanceof BABYLON.Mesh) {
  45938. var mesh = abstractMesh;
  45939. if (!mesh.doNotSerialize) {
  45940. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  45941. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  45942. }
  45943. }
  45944. }
  45945. }
  45946. // Particles Systems
  45947. serializationObject.particleSystems = [];
  45948. for (index = 0; index < scene.particleSystems.length; index++) {
  45949. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  45950. }
  45951. // Lens flares
  45952. serializationObject.lensFlareSystems = [];
  45953. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  45954. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  45955. }
  45956. // Shadows
  45957. serializationObject.shadowGenerators = [];
  45958. for (index = 0; index < scene.lights.length; index++) {
  45959. light = scene.lights[index];
  45960. var shadowGenerator = light.getShadowGenerator();
  45961. // Only support serialization for official generator so far.
  45962. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  45963. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  45964. }
  45965. }
  45966. // Action Manager
  45967. if (scene.actionManager) {
  45968. serializationObject.actions = scene.actionManager.serialize("scene");
  45969. }
  45970. // Audio
  45971. serializationObject.sounds = [];
  45972. for (index = 0; index < scene.soundTracks.length; index++) {
  45973. var soundtrack = scene.soundTracks[index];
  45974. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  45975. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  45976. }
  45977. }
  45978. return serializationObject;
  45979. };
  45980. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  45981. if (withParents === void 0) { withParents = false; }
  45982. if (withChildren === void 0) { withChildren = false; }
  45983. var serializationObject = {};
  45984. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  45985. if (withParents || withChildren) {
  45986. //deliberate for loop! not for each, appended should be processed as well.
  45987. for (var i = 0; i < toSerialize.length; ++i) {
  45988. if (withChildren) {
  45989. toSerialize[i].getDescendants().forEach(function (node) {
  45990. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  45991. toSerialize.push(node);
  45992. }
  45993. });
  45994. }
  45995. //make sure the array doesn't contain the object already
  45996. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  45997. toSerialize.push(toSerialize[i].parent);
  45998. }
  45999. }
  46000. }
  46001. toSerialize.forEach(function (mesh) {
  46002. finalizeSingleMesh(mesh, serializationObject);
  46003. });
  46004. return serializationObject;
  46005. };
  46006. return SceneSerializer;
  46007. }());
  46008. BABYLON.SceneSerializer = SceneSerializer;
  46009. })(BABYLON || (BABYLON = {}));
  46010. //# sourceMappingURL=babylon.sceneSerializer.js.map
  46011. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  46012. // Huge respect for a such great lib.
  46013. // Earcut license:
  46014. // Copyright (c) 2016, Mapbox
  46015. //
  46016. // Permission to use, copy, modify, and/or distribute this software for any purpose
  46017. // with or without fee is hereby granted, provided that the above copyright notice
  46018. // and this permission notice appear in all copies.
  46019. //
  46020. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  46021. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  46022. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  46023. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  46024. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  46025. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  46026. // THIS SOFTWARE.
  46027. var Earcut;
  46028. (function (Earcut) {
  46029. /**
  46030. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  46031. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  46032. * @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).
  46033. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  46034. */
  46035. function earcut(data, holeIndices, dim) {
  46036. dim = dim || 2;
  46037. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  46038. if (!outerNode)
  46039. return triangles;
  46040. var minX, minY, maxX, maxY, x, y, size;
  46041. if (hasHoles)
  46042. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  46043. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  46044. if (data.length > 80 * dim) {
  46045. minX = maxX = data[0];
  46046. minY = maxY = data[1];
  46047. for (var i = dim; i < outerLen; i += dim) {
  46048. x = data[i];
  46049. y = data[i + 1];
  46050. if (x < minX)
  46051. minX = x;
  46052. if (y < minY)
  46053. minY = y;
  46054. if (x > maxX)
  46055. maxX = x;
  46056. if (y > maxY)
  46057. maxY = y;
  46058. }
  46059. // minX, minY and size are later used to transform coords into integers for z-order calculation
  46060. size = Math.max(maxX - minX, maxY - minY);
  46061. }
  46062. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  46063. return triangles;
  46064. }
  46065. Earcut.earcut = earcut;
  46066. // create a circular doubly linked list from polygon points in the specified winding order
  46067. function linkedList(data, start, end, dim, clockwise) {
  46068. var i, last;
  46069. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  46070. for (i = start; i < end; i += dim)
  46071. last = insertNode(i, data[i], data[i + 1], last);
  46072. }
  46073. else {
  46074. for (i = end - dim; i >= start; i -= dim)
  46075. last = insertNode(i, data[i], data[i + 1], last);
  46076. }
  46077. if (last && equals(last, last.next)) {
  46078. removeNode(last);
  46079. last = last.next;
  46080. }
  46081. return last;
  46082. }
  46083. // eliminate colinear or duplicate points
  46084. function filterPoints(start, end) {
  46085. if (!start)
  46086. return start;
  46087. if (!end)
  46088. end = start;
  46089. var p = start, again;
  46090. do {
  46091. again = false;
  46092. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  46093. removeNode(p);
  46094. p = end = p.prev;
  46095. if (p === p.next)
  46096. return null;
  46097. again = true;
  46098. }
  46099. else {
  46100. p = p.next;
  46101. }
  46102. } while (again || p !== end);
  46103. return end;
  46104. }
  46105. // main ear slicing loop which triangulates a polygon (given as a linked list)
  46106. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  46107. if (!ear)
  46108. return;
  46109. // interlink polygon nodes in z-order
  46110. if (!pass && size)
  46111. indexCurve(ear, minX, minY, size);
  46112. var stop = ear, prev, next;
  46113. // iterate through ears, slicing them one by one
  46114. while (ear.prev !== ear.next) {
  46115. prev = ear.prev;
  46116. next = ear.next;
  46117. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  46118. // cut off the triangle
  46119. triangles.push(prev.i / dim);
  46120. triangles.push(ear.i / dim);
  46121. triangles.push(next.i / dim);
  46122. removeNode(ear);
  46123. // skipping the next vertice leads to less sliver triangles
  46124. ear = next.next;
  46125. stop = next.next;
  46126. continue;
  46127. }
  46128. ear = next;
  46129. // if we looped through the whole remaining polygon and can't find any more ears
  46130. if (ear === stop) {
  46131. // try filtering points and slicing again
  46132. if (!pass) {
  46133. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  46134. }
  46135. else if (pass === 1) {
  46136. ear = cureLocalIntersections(ear, triangles, dim);
  46137. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  46138. }
  46139. else if (pass === 2) {
  46140. splitEarcut(ear, triangles, dim, minX, minY, size);
  46141. }
  46142. break;
  46143. }
  46144. }
  46145. }
  46146. // check whether a polygon node forms a valid ear with adjacent nodes
  46147. function isEar(ear) {
  46148. var a = ear.prev, b = ear, c = ear.next;
  46149. if (area(a, b, c) >= 0)
  46150. return false; // reflex, can't be an ear
  46151. // now make sure we don't have other points inside the potential ear
  46152. var p = ear.next.next;
  46153. while (p !== ear.prev) {
  46154. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  46155. area(p.prev, p, p.next) >= 0)
  46156. return false;
  46157. p = p.next;
  46158. }
  46159. return true;
  46160. }
  46161. function isEarHashed(ear, minX, minY, size) {
  46162. var a = ear.prev, b = ear, c = ear.next;
  46163. if (area(a, b, c) >= 0)
  46164. return false; // reflex, can't be an ear
  46165. // triangle bbox; min & max are calculated like this for speed
  46166. 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);
  46167. // z-order range for the current triangle bbox;
  46168. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  46169. // first look for points inside the triangle in increasing z-order
  46170. var p = ear.nextZ;
  46171. while (p && p.z <= maxZ) {
  46172. if (p !== ear.prev &&
  46173. p !== ear.next &&
  46174. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  46175. area(p.prev, p, p.next) >= 0)
  46176. return false;
  46177. p = p.nextZ;
  46178. }
  46179. // then look for points in decreasing z-order
  46180. p = ear.prevZ;
  46181. while (p && p.z >= minZ) {
  46182. if (p !== ear.prev &&
  46183. p !== ear.next &&
  46184. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  46185. area(p.prev, p, p.next) >= 0)
  46186. return false;
  46187. p = p.prevZ;
  46188. }
  46189. return true;
  46190. }
  46191. // go through all polygon nodes and cure small local self-intersections
  46192. function cureLocalIntersections(start, triangles, dim) {
  46193. var p = start;
  46194. do {
  46195. var a = p.prev, b = p.next.next;
  46196. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  46197. triangles.push(a.i / dim);
  46198. triangles.push(p.i / dim);
  46199. triangles.push(b.i / dim);
  46200. // remove two nodes involved
  46201. removeNode(p);
  46202. removeNode(p.next);
  46203. p = start = b;
  46204. }
  46205. p = p.next;
  46206. } while (p !== start);
  46207. return p;
  46208. }
  46209. // try splitting polygon into two and triangulate them independently
  46210. function splitEarcut(start, triangles, dim, minX, minY, size) {
  46211. // look for a valid diagonal that divides the polygon into two
  46212. var a = start;
  46213. do {
  46214. var b = a.next.next;
  46215. while (b !== a.prev) {
  46216. if (a.i !== b.i && isValidDiagonal(a, b)) {
  46217. // split the polygon in two by the diagonal
  46218. var c = splitPolygon(a, b);
  46219. // filter colinear points around the cuts
  46220. a = filterPoints(a, a.next);
  46221. c = filterPoints(c, c.next);
  46222. // run earcut on each half
  46223. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  46224. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  46225. return;
  46226. }
  46227. b = b.next;
  46228. }
  46229. a = a.next;
  46230. } while (a !== start);
  46231. }
  46232. // link every hole into the outer loop, producing a single-ring polygon without holes
  46233. function eliminateHoles(data, holeIndices, outerNode, dim) {
  46234. var queue = [], i, len, start, end, list;
  46235. for (i = 0, len = holeIndices.length; i < len; i++) {
  46236. start = holeIndices[i] * dim;
  46237. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  46238. list = linkedList(data, start, end, dim, false);
  46239. if (list === list.next)
  46240. list.steiner = true;
  46241. queue.push(getLeftmost(list));
  46242. }
  46243. queue.sort(compareX);
  46244. // process holes from left to right
  46245. for (i = 0; i < queue.length; i++) {
  46246. eliminateHole(queue[i], outerNode);
  46247. outerNode = filterPoints(outerNode, outerNode.next);
  46248. }
  46249. return outerNode;
  46250. }
  46251. function compareX(a, b) {
  46252. return a.x - b.x;
  46253. }
  46254. // find a bridge between vertices that connects hole with an outer ring and and link it
  46255. function eliminateHole(hole, outerNode) {
  46256. outerNode = findHoleBridge(hole, outerNode);
  46257. if (outerNode) {
  46258. var b = splitPolygon(outerNode, hole);
  46259. filterPoints(b, b.next);
  46260. }
  46261. }
  46262. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  46263. function findHoleBridge(hole, outerNode) {
  46264. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  46265. // find a segment intersected by a ray from the hole's leftmost point to the left;
  46266. // segment's endpoint with lesser x will be potential connection point
  46267. do {
  46268. if (hy <= p.y && hy >= p.next.y) {
  46269. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  46270. if (x <= hx && x > qx) {
  46271. qx = x;
  46272. if (x === hx) {
  46273. if (hy === p.y)
  46274. return p;
  46275. if (hy === p.next.y)
  46276. return p.next;
  46277. }
  46278. m = p.x < p.next.x ? p : p.next;
  46279. }
  46280. }
  46281. p = p.next;
  46282. } while (p !== outerNode);
  46283. if (!m)
  46284. return null;
  46285. if (hx === qx)
  46286. return m.prev; // hole touches outer segment; pick lower endpoint
  46287. // look for points inside the triangle of hole point, segment intersection and endpoint;
  46288. // if there are no points found, we have a valid connection;
  46289. // otherwise choose the point of the minimum angle with the ray as connection point
  46290. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  46291. p = m.next;
  46292. while (p !== stop) {
  46293. if (hx >= p.x &&
  46294. p.x >= mx &&
  46295. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  46296. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  46297. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  46298. m = p;
  46299. tanMin = tan;
  46300. }
  46301. }
  46302. p = p.next;
  46303. }
  46304. return m;
  46305. }
  46306. // interlink polygon nodes in z-order
  46307. function indexCurve(start, minX, minY, size) {
  46308. var p = start;
  46309. do {
  46310. if (p.z === null)
  46311. p.z = zOrder(p.x, p.y, minX, minY, size);
  46312. p.prevZ = p.prev;
  46313. p.nextZ = p.next;
  46314. p = p.next;
  46315. } while (p !== start);
  46316. p.prevZ.nextZ = null;
  46317. p.prevZ = null;
  46318. sortLinked(p);
  46319. }
  46320. // Simon Tatham's linked list merge sort algorithm
  46321. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  46322. function sortLinked(list) {
  46323. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  46324. do {
  46325. p = list;
  46326. list = null;
  46327. tail = null;
  46328. numMerges = 0;
  46329. while (p) {
  46330. numMerges++;
  46331. q = p;
  46332. pSize = 0;
  46333. for (i = 0; i < inSize; i++) {
  46334. pSize++;
  46335. q = q.nextZ;
  46336. if (!q)
  46337. break;
  46338. }
  46339. qSize = inSize;
  46340. while (pSize > 0 || (qSize > 0 && q)) {
  46341. if (pSize === 0) {
  46342. e = q;
  46343. q = q.nextZ;
  46344. qSize--;
  46345. }
  46346. else if (qSize === 0 || !q) {
  46347. e = p;
  46348. p = p.nextZ;
  46349. pSize--;
  46350. }
  46351. else if (p.z <= q.z) {
  46352. e = p;
  46353. p = p.nextZ;
  46354. pSize--;
  46355. }
  46356. else {
  46357. e = q;
  46358. q = q.nextZ;
  46359. qSize--;
  46360. }
  46361. if (tail)
  46362. tail.nextZ = e;
  46363. else
  46364. list = e;
  46365. e.prevZ = tail;
  46366. tail = e;
  46367. }
  46368. p = q;
  46369. }
  46370. tail.nextZ = null;
  46371. inSize *= 2;
  46372. } while (numMerges > 1);
  46373. return list;
  46374. }
  46375. // z-order of a point given coords and size of the data bounding box
  46376. function zOrder(x, y, minX, minY, size) {
  46377. // coords are transformed into non-negative 15-bit integer range
  46378. x = 32767 * (x - minX) / size;
  46379. y = 32767 * (y - minY) / size;
  46380. x = (x | (x << 8)) & 0x00FF00FF;
  46381. x = (x | (x << 4)) & 0x0F0F0F0F;
  46382. x = (x | (x << 2)) & 0x33333333;
  46383. x = (x | (x << 1)) & 0x55555555;
  46384. y = (y | (y << 8)) & 0x00FF00FF;
  46385. y = (y | (y << 4)) & 0x0F0F0F0F;
  46386. y = (y | (y << 2)) & 0x33333333;
  46387. y = (y | (y << 1)) & 0x55555555;
  46388. return x | (y << 1);
  46389. }
  46390. // find the leftmost node of a polygon ring
  46391. function getLeftmost(start) {
  46392. var p = start, leftmost = start;
  46393. do {
  46394. if (p.x < leftmost.x)
  46395. leftmost = p;
  46396. p = p.next;
  46397. } while (p !== start);
  46398. return leftmost;
  46399. }
  46400. // check if a point lies within a convex triangle
  46401. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  46402. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  46403. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  46404. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  46405. }
  46406. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  46407. function isValidDiagonal(a, b) {
  46408. return a.next.i !== b.i &&
  46409. a.prev.i !== b.i &&
  46410. !intersectsPolygon(a, b) &&
  46411. locallyInside(a, b) &&
  46412. locallyInside(b, a) &&
  46413. middleInside(a, b);
  46414. }
  46415. // signed area of a triangle
  46416. function area(p, q, r) {
  46417. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  46418. }
  46419. // check if two points are equal
  46420. function equals(p1, p2) {
  46421. return p1.x === p2.x && p1.y === p2.y;
  46422. }
  46423. // check if two segments intersect
  46424. function intersects(p1, q1, p2, q2) {
  46425. if ((equals(p1, q1) && equals(p2, q2)) ||
  46426. (equals(p1, q2) && equals(p2, q1)))
  46427. return true;
  46428. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  46429. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  46430. }
  46431. // check if a polygon diagonal intersects any polygon segments
  46432. function intersectsPolygon(a, b) {
  46433. var p = a;
  46434. do {
  46435. if (p.i !== a.i &&
  46436. p.next.i !== a.i &&
  46437. p.i !== b.i &&
  46438. p.next.i !== b.i &&
  46439. intersects(p, p.next, a, b))
  46440. return true;
  46441. p = p.next;
  46442. } while (p !== a);
  46443. return false;
  46444. }
  46445. // check if a polygon diagonal is locally inside the polygon
  46446. function locallyInside(a, b) {
  46447. return area(a.prev, a, a.next) < 0
  46448. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  46449. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  46450. }
  46451. // check if the middle point of a polygon diagonal is inside the polygon
  46452. function middleInside(a, b) {
  46453. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  46454. do {
  46455. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  46456. inside = !inside;
  46457. p = p.next;
  46458. } while (p !== a);
  46459. return inside;
  46460. }
  46461. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  46462. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  46463. function splitPolygon(a, b) {
  46464. 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;
  46465. a.next = b;
  46466. b.prev = a;
  46467. a2.next = an;
  46468. an.prev = a2;
  46469. b2.next = a2;
  46470. a2.prev = b2;
  46471. bp.next = b2;
  46472. b2.prev = bp;
  46473. return b2;
  46474. }
  46475. // create a node and optionally link it with previous one (in a circular doubly linked list)
  46476. function insertNode(i, x, y, last) {
  46477. var p = new Node(i, x, y);
  46478. if (!last) {
  46479. p.prev = p;
  46480. p.next = p;
  46481. }
  46482. else {
  46483. p.next = last.next;
  46484. p.prev = last;
  46485. last.next.prev = p;
  46486. last.next = p;
  46487. }
  46488. return p;
  46489. }
  46490. function removeNode(p) {
  46491. p.next.prev = p.prev;
  46492. p.prev.next = p.next;
  46493. if (p.prevZ)
  46494. p.prevZ.nextZ = p.nextZ;
  46495. if (p.nextZ)
  46496. p.nextZ.prevZ = p.prevZ;
  46497. }
  46498. function Node(i, x, y) {
  46499. // vertice index in coordinates array
  46500. this.i = i;
  46501. // vertex coordinates
  46502. this.x = x;
  46503. this.y = y;
  46504. // previous and next vertice nodes in a polygon ring
  46505. this.prev = null;
  46506. this.next = null;
  46507. // z-order curve value
  46508. this.z = null;
  46509. // previous and next nodes in z-order
  46510. this.prevZ = null;
  46511. this.nextZ = null;
  46512. // indicates whether this is a steiner point
  46513. this.steiner = false;
  46514. }
  46515. /**
  46516. * return a percentage difference between the polygon area and its triangulation area;
  46517. * used to verify correctness of triangulation
  46518. */
  46519. function deviation(data, holeIndices, dim, triangles) {
  46520. var hasHoles = holeIndices && holeIndices.length;
  46521. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  46522. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  46523. if (hasHoles) {
  46524. for (var i = 0, len = holeIndices.length; i < len; i++) {
  46525. var start = holeIndices[i] * dim;
  46526. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  46527. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  46528. }
  46529. }
  46530. var trianglesArea = 0;
  46531. for (i = 0; i < triangles.length; i += 3) {
  46532. var a = triangles[i] * dim;
  46533. var b = triangles[i + 1] * dim;
  46534. var c = triangles[i + 2] * dim;
  46535. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  46536. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  46537. }
  46538. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  46539. }
  46540. Earcut.deviation = deviation;
  46541. ;
  46542. function signedArea(data, start, end, dim) {
  46543. var sum = 0;
  46544. for (var i = start, j = end - dim; i < end; i += dim) {
  46545. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  46546. j = i;
  46547. }
  46548. return sum;
  46549. }
  46550. /**
  46551. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  46552. */
  46553. function flatten(data) {
  46554. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  46555. for (var i = 0; i < data.length; i++) {
  46556. for (var j = 0; j < data[i].length; j++) {
  46557. for (var d = 0; d < dim; d++)
  46558. result.vertices.push(data[i][j][d]);
  46559. }
  46560. if (i > 0) {
  46561. holeIndex += data[i - 1].length;
  46562. result.holes.push(holeIndex);
  46563. }
  46564. }
  46565. return result;
  46566. }
  46567. Earcut.flatten = flatten;
  46568. ;
  46569. })(Earcut || (Earcut = {}));
  46570. //# sourceMappingURL=babylon.earcut.js.map
  46571. var BABYLON;
  46572. (function (BABYLON) {
  46573. // Unique ID when we import meshes from Babylon to CSG
  46574. var currentCSGMeshId = 0;
  46575. // # class Vertex
  46576. // Represents a vertex of a polygon. Use your own vertex class instead of this
  46577. // one to provide additional features like texture coordinates and vertex
  46578. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  46579. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  46580. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  46581. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  46582. // is not used anywhere else.
  46583. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  46584. var Vertex = (function () {
  46585. function Vertex(pos, normal, uv) {
  46586. this.pos = pos;
  46587. this.normal = normal;
  46588. this.uv = uv;
  46589. }
  46590. Vertex.prototype.clone = function () {
  46591. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  46592. };
  46593. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  46594. // orientation of a polygon is flipped.
  46595. Vertex.prototype.flip = function () {
  46596. this.normal = this.normal.scale(-1);
  46597. };
  46598. // Create a new vertex between this vertex and `other` by linearly
  46599. // interpolating all properties using a parameter of `t`. Subclasses should
  46600. // override this to interpolate additional properties.
  46601. Vertex.prototype.interpolate = function (other, t) {
  46602. 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));
  46603. };
  46604. return Vertex;
  46605. }());
  46606. // # class Plane
  46607. // Represents a plane in 3D space.
  46608. var Plane = (function () {
  46609. function Plane(normal, w) {
  46610. this.normal = normal;
  46611. this.w = w;
  46612. }
  46613. Plane.FromPoints = function (a, b, c) {
  46614. var v0 = c.subtract(a);
  46615. var v1 = b.subtract(a);
  46616. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  46617. return null;
  46618. }
  46619. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  46620. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  46621. };
  46622. Plane.prototype.clone = function () {
  46623. return new Plane(this.normal.clone(), this.w);
  46624. };
  46625. Plane.prototype.flip = function () {
  46626. this.normal.scaleInPlace(-1);
  46627. this.w = -this.w;
  46628. };
  46629. // Split `polygon` by this plane if needed, then put the polygon or polygon
  46630. // fragments in the appropriate lists. Coplanar polygons go into either
  46631. // `coplanarFront` or `coplanarBack` depending on their orientation with
  46632. // respect to this plane. Polygons in front or in back of this plane go into
  46633. // either `front` or `back`.
  46634. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  46635. var COPLANAR = 0;
  46636. var FRONT = 1;
  46637. var BACK = 2;
  46638. var SPANNING = 3;
  46639. // Classify each point as well as the entire polygon into one of the above
  46640. // four classes.
  46641. var polygonType = 0;
  46642. var types = [];
  46643. var i;
  46644. var t;
  46645. for (i = 0; i < polygon.vertices.length; i++) {
  46646. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  46647. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  46648. polygonType |= type;
  46649. types.push(type);
  46650. }
  46651. // Put the polygon in the correct list, splitting it when necessary.
  46652. switch (polygonType) {
  46653. case COPLANAR:
  46654. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  46655. break;
  46656. case FRONT:
  46657. front.push(polygon);
  46658. break;
  46659. case BACK:
  46660. back.push(polygon);
  46661. break;
  46662. case SPANNING:
  46663. var f = [], b = [];
  46664. for (i = 0; i < polygon.vertices.length; i++) {
  46665. var j = (i + 1) % polygon.vertices.length;
  46666. var ti = types[i], tj = types[j];
  46667. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  46668. if (ti !== BACK)
  46669. f.push(vi);
  46670. if (ti !== FRONT)
  46671. b.push(ti !== BACK ? vi.clone() : vi);
  46672. if ((ti | tj) === SPANNING) {
  46673. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  46674. var v = vi.interpolate(vj, t);
  46675. f.push(v);
  46676. b.push(v.clone());
  46677. }
  46678. }
  46679. var poly;
  46680. if (f.length >= 3) {
  46681. poly = new Polygon(f, polygon.shared);
  46682. if (poly.plane)
  46683. front.push(poly);
  46684. }
  46685. if (b.length >= 3) {
  46686. poly = new Polygon(b, polygon.shared);
  46687. if (poly.plane)
  46688. back.push(poly);
  46689. }
  46690. break;
  46691. }
  46692. };
  46693. return Plane;
  46694. }());
  46695. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  46696. // point is on the plane.
  46697. Plane.EPSILON = 1e-5;
  46698. // # class Polygon
  46699. // Represents a convex polygon. The vertices used to initialize a polygon must
  46700. // be coplanar and form a convex loop.
  46701. //
  46702. // Each convex polygon has a `shared` property, which is shared between all
  46703. // polygons that are clones of each other or were split from the same polygon.
  46704. // This can be used to define per-polygon properties (such as surface color).
  46705. var Polygon = (function () {
  46706. function Polygon(vertices, shared) {
  46707. this.vertices = vertices;
  46708. this.shared = shared;
  46709. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  46710. }
  46711. Polygon.prototype.clone = function () {
  46712. var vertices = this.vertices.map(function (v) { return v.clone(); });
  46713. return new Polygon(vertices, this.shared);
  46714. };
  46715. Polygon.prototype.flip = function () {
  46716. this.vertices.reverse().map(function (v) { v.flip(); });
  46717. this.plane.flip();
  46718. };
  46719. return Polygon;
  46720. }());
  46721. // # class Node
  46722. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  46723. // by picking a polygon to split along. That polygon (and all other coplanar
  46724. // polygons) are added directly to that node and the other polygons are added to
  46725. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  46726. // no distinction between internal and leaf nodes.
  46727. var Node = (function () {
  46728. function Node(polygons) {
  46729. this.plane = null;
  46730. this.front = null;
  46731. this.back = null;
  46732. this.polygons = [];
  46733. if (polygons) {
  46734. this.build(polygons);
  46735. }
  46736. }
  46737. Node.prototype.clone = function () {
  46738. var node = new Node();
  46739. node.plane = this.plane && this.plane.clone();
  46740. node.front = this.front && this.front.clone();
  46741. node.back = this.back && this.back.clone();
  46742. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  46743. return node;
  46744. };
  46745. // Convert solid space to empty space and empty space to solid space.
  46746. Node.prototype.invert = function () {
  46747. for (var i = 0; i < this.polygons.length; i++) {
  46748. this.polygons[i].flip();
  46749. }
  46750. if (this.plane) {
  46751. this.plane.flip();
  46752. }
  46753. if (this.front) {
  46754. this.front.invert();
  46755. }
  46756. if (this.back) {
  46757. this.back.invert();
  46758. }
  46759. var temp = this.front;
  46760. this.front = this.back;
  46761. this.back = temp;
  46762. };
  46763. // Recursively remove all polygons in `polygons` that are inside this BSP
  46764. // tree.
  46765. Node.prototype.clipPolygons = function (polygons) {
  46766. if (!this.plane)
  46767. return polygons.slice();
  46768. var front = [], back = [];
  46769. for (var i = 0; i < polygons.length; i++) {
  46770. this.plane.splitPolygon(polygons[i], front, back, front, back);
  46771. }
  46772. if (this.front) {
  46773. front = this.front.clipPolygons(front);
  46774. }
  46775. if (this.back) {
  46776. back = this.back.clipPolygons(back);
  46777. }
  46778. else {
  46779. back = [];
  46780. }
  46781. return front.concat(back);
  46782. };
  46783. // Remove all polygons in this BSP tree that are inside the other BSP tree
  46784. // `bsp`.
  46785. Node.prototype.clipTo = function (bsp) {
  46786. this.polygons = bsp.clipPolygons(this.polygons);
  46787. if (this.front)
  46788. this.front.clipTo(bsp);
  46789. if (this.back)
  46790. this.back.clipTo(bsp);
  46791. };
  46792. // Return a list of all polygons in this BSP tree.
  46793. Node.prototype.allPolygons = function () {
  46794. var polygons = this.polygons.slice();
  46795. if (this.front)
  46796. polygons = polygons.concat(this.front.allPolygons());
  46797. if (this.back)
  46798. polygons = polygons.concat(this.back.allPolygons());
  46799. return polygons;
  46800. };
  46801. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  46802. // new polygons are filtered down to the bottom of the tree and become new
  46803. // nodes there. Each set of polygons is partitioned using the first polygon
  46804. // (no heuristic is used to pick a good split).
  46805. Node.prototype.build = function (polygons) {
  46806. if (!polygons.length)
  46807. return;
  46808. if (!this.plane)
  46809. this.plane = polygons[0].plane.clone();
  46810. var front = [], back = [];
  46811. for (var i = 0; i < polygons.length; i++) {
  46812. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  46813. }
  46814. if (front.length) {
  46815. if (!this.front)
  46816. this.front = new Node();
  46817. this.front.build(front);
  46818. }
  46819. if (back.length) {
  46820. if (!this.back)
  46821. this.back = new Node();
  46822. this.back.build(back);
  46823. }
  46824. };
  46825. return Node;
  46826. }());
  46827. var CSG = (function () {
  46828. function CSG() {
  46829. this.polygons = new Array();
  46830. }
  46831. // Convert BABYLON.Mesh to BABYLON.CSG
  46832. CSG.FromMesh = function (mesh) {
  46833. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  46834. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  46835. if (mesh instanceof BABYLON.Mesh) {
  46836. mesh.computeWorldMatrix(true);
  46837. matrix = mesh.getWorldMatrix();
  46838. meshPosition = mesh.position.clone();
  46839. meshRotation = mesh.rotation.clone();
  46840. if (mesh.rotationQuaternion) {
  46841. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  46842. }
  46843. meshScaling = mesh.scaling.clone();
  46844. }
  46845. else {
  46846. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  46847. }
  46848. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46849. var subMeshes = mesh.subMeshes;
  46850. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  46851. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  46852. vertices = [];
  46853. for (var j = 0; j < 3; j++) {
  46854. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  46855. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  46856. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  46857. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  46858. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  46859. vertex = new Vertex(position, normal, uv);
  46860. vertices.push(vertex);
  46861. }
  46862. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  46863. // To handle the case of degenerated triangle
  46864. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  46865. if (polygon.plane)
  46866. polygons.push(polygon);
  46867. }
  46868. }
  46869. var csg = CSG.FromPolygons(polygons);
  46870. csg.matrix = matrix;
  46871. csg.position = meshPosition;
  46872. csg.rotation = meshRotation;
  46873. csg.scaling = meshScaling;
  46874. csg.rotationQuaternion = meshRotationQuaternion;
  46875. currentCSGMeshId++;
  46876. return csg;
  46877. };
  46878. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  46879. CSG.FromPolygons = function (polygons) {
  46880. var csg = new CSG();
  46881. csg.polygons = polygons;
  46882. return csg;
  46883. };
  46884. CSG.prototype.clone = function () {
  46885. var csg = new CSG();
  46886. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  46887. csg.copyTransformAttributes(this);
  46888. return csg;
  46889. };
  46890. CSG.prototype.toPolygons = function () {
  46891. return this.polygons;
  46892. };
  46893. CSG.prototype.union = function (csg) {
  46894. var a = new Node(this.clone().polygons);
  46895. var b = new Node(csg.clone().polygons);
  46896. a.clipTo(b);
  46897. b.clipTo(a);
  46898. b.invert();
  46899. b.clipTo(a);
  46900. b.invert();
  46901. a.build(b.allPolygons());
  46902. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  46903. };
  46904. CSG.prototype.unionInPlace = function (csg) {
  46905. var a = new Node(this.polygons);
  46906. var b = new Node(csg.polygons);
  46907. a.clipTo(b);
  46908. b.clipTo(a);
  46909. b.invert();
  46910. b.clipTo(a);
  46911. b.invert();
  46912. a.build(b.allPolygons());
  46913. this.polygons = a.allPolygons();
  46914. };
  46915. CSG.prototype.subtract = function (csg) {
  46916. var a = new Node(this.clone().polygons);
  46917. var b = new Node(csg.clone().polygons);
  46918. a.invert();
  46919. a.clipTo(b);
  46920. b.clipTo(a);
  46921. b.invert();
  46922. b.clipTo(a);
  46923. b.invert();
  46924. a.build(b.allPolygons());
  46925. a.invert();
  46926. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  46927. };
  46928. CSG.prototype.subtractInPlace = function (csg) {
  46929. var a = new Node(this.polygons);
  46930. var b = new Node(csg.polygons);
  46931. a.invert();
  46932. a.clipTo(b);
  46933. b.clipTo(a);
  46934. b.invert();
  46935. b.clipTo(a);
  46936. b.invert();
  46937. a.build(b.allPolygons());
  46938. a.invert();
  46939. this.polygons = a.allPolygons();
  46940. };
  46941. CSG.prototype.intersect = function (csg) {
  46942. var a = new Node(this.clone().polygons);
  46943. var b = new Node(csg.clone().polygons);
  46944. a.invert();
  46945. b.clipTo(a);
  46946. b.invert();
  46947. a.clipTo(b);
  46948. b.clipTo(a);
  46949. a.build(b.allPolygons());
  46950. a.invert();
  46951. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  46952. };
  46953. CSG.prototype.intersectInPlace = function (csg) {
  46954. var a = new Node(this.polygons);
  46955. var b = new Node(csg.polygons);
  46956. a.invert();
  46957. b.clipTo(a);
  46958. b.invert();
  46959. a.clipTo(b);
  46960. b.clipTo(a);
  46961. a.build(b.allPolygons());
  46962. a.invert();
  46963. this.polygons = a.allPolygons();
  46964. };
  46965. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  46966. // not modified.
  46967. CSG.prototype.inverse = function () {
  46968. var csg = this.clone();
  46969. csg.inverseInPlace();
  46970. return csg;
  46971. };
  46972. CSG.prototype.inverseInPlace = function () {
  46973. this.polygons.map(function (p) { p.flip(); });
  46974. };
  46975. // This is used to keep meshes transformations so they can be restored
  46976. // when we build back a Babylon Mesh
  46977. // NB : All CSG operations are performed in world coordinates
  46978. CSG.prototype.copyTransformAttributes = function (csg) {
  46979. this.matrix = csg.matrix;
  46980. this.position = csg.position;
  46981. this.rotation = csg.rotation;
  46982. this.scaling = csg.scaling;
  46983. this.rotationQuaternion = csg.rotationQuaternion;
  46984. return this;
  46985. };
  46986. // Build Raw mesh from CSG
  46987. // Coordinates here are in world space
  46988. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  46989. var matrix = this.matrix.clone();
  46990. matrix.invert();
  46991. 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;
  46992. if (keepSubMeshes) {
  46993. // Sort Polygons, since subMeshes are indices range
  46994. polygons.sort(function (a, b) {
  46995. if (a.shared.meshId === b.shared.meshId) {
  46996. return a.shared.subMeshId - b.shared.subMeshId;
  46997. }
  46998. else {
  46999. return a.shared.meshId - b.shared.meshId;
  47000. }
  47001. });
  47002. }
  47003. for (var i = 0, il = polygons.length; i < il; i++) {
  47004. polygon = polygons[i];
  47005. // Building SubMeshes
  47006. if (!subMesh_dict[polygon.shared.meshId]) {
  47007. subMesh_dict[polygon.shared.meshId] = {};
  47008. }
  47009. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  47010. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  47011. indexStart: +Infinity,
  47012. indexEnd: -Infinity,
  47013. materialIndex: polygon.shared.materialIndex
  47014. };
  47015. }
  47016. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  47017. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  47018. polygonIndices[0] = 0;
  47019. polygonIndices[1] = j - 1;
  47020. polygonIndices[2] = j;
  47021. for (var k = 0; k < 3; k++) {
  47022. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  47023. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  47024. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  47025. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  47026. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  47027. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  47028. // Check if 2 points can be merged
  47029. if (!(typeof vertex_idx !== 'undefined' &&
  47030. normals[vertex_idx * 3] === localNormal.x &&
  47031. normals[vertex_idx * 3 + 1] === localNormal.y &&
  47032. normals[vertex_idx * 3 + 2] === localNormal.z &&
  47033. uvs[vertex_idx * 2] === uv.x &&
  47034. uvs[vertex_idx * 2 + 1] === uv.y)) {
  47035. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  47036. uvs.push(uv.x, uv.y);
  47037. normals.push(normal.x, normal.y, normal.z);
  47038. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  47039. }
  47040. indices.push(vertex_idx);
  47041. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  47042. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  47043. currentIndex++;
  47044. }
  47045. }
  47046. }
  47047. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  47048. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  47049. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  47050. mesh.setIndices(indices);
  47051. if (keepSubMeshes) {
  47052. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  47053. var materialIndexOffset = 0, materialMaxIndex;
  47054. mesh.subMeshes = new Array();
  47055. for (var m in subMesh_dict) {
  47056. materialMaxIndex = -1;
  47057. for (var sm in subMesh_dict[m]) {
  47058. subMesh_obj = subMesh_dict[m][sm];
  47059. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  47060. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  47061. }
  47062. materialIndexOffset += ++materialMaxIndex;
  47063. }
  47064. }
  47065. return mesh;
  47066. };
  47067. // Build Mesh from CSG taking material and transforms into account
  47068. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  47069. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  47070. mesh.material = material;
  47071. mesh.position.copyFrom(this.position);
  47072. mesh.rotation.copyFrom(this.rotation);
  47073. if (this.rotationQuaternion) {
  47074. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  47075. }
  47076. mesh.scaling.copyFrom(this.scaling);
  47077. mesh.computeWorldMatrix(true);
  47078. return mesh;
  47079. };
  47080. return CSG;
  47081. }());
  47082. BABYLON.CSG = CSG;
  47083. })(BABYLON || (BABYLON = {}));
  47084. //# sourceMappingURL=babylon.csg.js.map
  47085. var BABYLON;
  47086. (function (BABYLON) {
  47087. var VRDistortionCorrectionPostProcess = (function (_super) {
  47088. __extends(VRDistortionCorrectionPostProcess, _super);
  47089. //ANY
  47090. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  47091. var _this = _super.call(this, name, "vrDistortionCorrection", [
  47092. 'LensCenter',
  47093. 'Scale',
  47094. 'ScaleIn',
  47095. 'HmdWarpParam'
  47096. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  47097. _this._isRightEye = isRightEye;
  47098. _this._distortionFactors = vrMetrics.distortionK;
  47099. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  47100. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  47101. _this.onSizeChangedObservable.add(function () {
  47102. _this.aspectRatio = _this.width * .5 / _this.height;
  47103. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  47104. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  47105. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  47106. });
  47107. _this.onApplyObservable.add(function (effect) {
  47108. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  47109. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  47110. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  47111. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  47112. });
  47113. return _this;
  47114. }
  47115. return VRDistortionCorrectionPostProcess;
  47116. }(BABYLON.PostProcess));
  47117. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  47118. })(BABYLON || (BABYLON = {}));
  47119. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  47120. // Mainly based on these 2 articles :
  47121. // 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
  47122. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  47123. var BABYLON;
  47124. (function (BABYLON) {
  47125. var JoystickAxis;
  47126. (function (JoystickAxis) {
  47127. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  47128. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  47129. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  47130. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  47131. var VirtualJoystick = (function () {
  47132. function VirtualJoystick(leftJoystick) {
  47133. var _this = this;
  47134. if (leftJoystick) {
  47135. this._leftJoystick = true;
  47136. }
  47137. else {
  47138. this._leftJoystick = false;
  47139. }
  47140. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  47141. VirtualJoystick._globalJoystickIndex++;
  47142. // By default left & right arrow keys are moving the X
  47143. // and up & down keys are moving the Y
  47144. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  47145. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  47146. this.reverseLeftRight = false;
  47147. this.reverseUpDown = false;
  47148. // collections of pointers
  47149. this._touches = new BABYLON.StringDictionary();
  47150. this.deltaPosition = BABYLON.Vector3.Zero();
  47151. this._joystickSensibility = 25;
  47152. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  47153. this._rotationSpeed = 25;
  47154. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  47155. this._rotateOnAxisRelativeToMesh = false;
  47156. this._onResize = function (evt) {
  47157. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  47158. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  47159. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  47160. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  47161. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  47162. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  47163. };
  47164. // injecting a canvas element on top of the canvas 3D game
  47165. if (!VirtualJoystick.vjCanvas) {
  47166. window.addEventListener("resize", this._onResize, false);
  47167. VirtualJoystick.vjCanvas = document.createElement("canvas");
  47168. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  47169. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  47170. VirtualJoystick.vjCanvas.width = window.innerWidth;
  47171. VirtualJoystick.vjCanvas.height = window.innerHeight;
  47172. VirtualJoystick.vjCanvas.style.width = "100%";
  47173. VirtualJoystick.vjCanvas.style.height = "100%";
  47174. VirtualJoystick.vjCanvas.style.position = "absolute";
  47175. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  47176. VirtualJoystick.vjCanvas.style.top = "0px";
  47177. VirtualJoystick.vjCanvas.style.left = "0px";
  47178. VirtualJoystick.vjCanvas.style.zIndex = "5";
  47179. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  47180. // Support for jQuery PEP polyfill
  47181. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  47182. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  47183. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  47184. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  47185. document.body.appendChild(VirtualJoystick.vjCanvas);
  47186. }
  47187. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  47188. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  47189. this.pressed = false;
  47190. // default joystick color
  47191. this._joystickColor = "cyan";
  47192. this._joystickPointerID = -1;
  47193. // current joystick position
  47194. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  47195. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  47196. // origin joystick position
  47197. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  47198. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  47199. this._onPointerDownHandlerRef = function (evt) {
  47200. _this._onPointerDown(evt);
  47201. };
  47202. this._onPointerMoveHandlerRef = function (evt) {
  47203. _this._onPointerMove(evt);
  47204. };
  47205. this._onPointerOutHandlerRef = function (evt) {
  47206. _this._onPointerUp(evt);
  47207. };
  47208. this._onPointerUpHandlerRef = function (evt) {
  47209. _this._onPointerUp(evt);
  47210. };
  47211. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  47212. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  47213. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  47214. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  47215. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  47216. evt.preventDefault(); // Disables system menu
  47217. }, false);
  47218. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  47219. }
  47220. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  47221. this._joystickSensibility = newJoystickSensibility;
  47222. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  47223. };
  47224. VirtualJoystick.prototype._onPointerDown = function (e) {
  47225. var positionOnScreenCondition;
  47226. e.preventDefault();
  47227. if (this._leftJoystick === true) {
  47228. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  47229. }
  47230. else {
  47231. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  47232. }
  47233. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  47234. // First contact will be dedicated to the virtual joystick
  47235. this._joystickPointerID = e.pointerId;
  47236. this._joystickPointerStartPos.x = e.clientX;
  47237. this._joystickPointerStartPos.y = e.clientY;
  47238. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  47239. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  47240. this._deltaJoystickVector.x = 0;
  47241. this._deltaJoystickVector.y = 0;
  47242. this.pressed = true;
  47243. this._touches.add(e.pointerId.toString(), e);
  47244. }
  47245. else {
  47246. // You can only trigger the action buttons with a joystick declared
  47247. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  47248. this._action();
  47249. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  47250. }
  47251. }
  47252. };
  47253. VirtualJoystick.prototype._onPointerMove = function (e) {
  47254. // If the current pointer is the one associated to the joystick (first touch contact)
  47255. if (this._joystickPointerID == e.pointerId) {
  47256. this._joystickPointerPos.x = e.clientX;
  47257. this._joystickPointerPos.y = e.clientY;
  47258. this._deltaJoystickVector = this._joystickPointerPos.clone();
  47259. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  47260. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  47261. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  47262. switch (this._axisTargetedByLeftAndRight) {
  47263. case JoystickAxis.X:
  47264. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  47265. break;
  47266. case JoystickAxis.Y:
  47267. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  47268. break;
  47269. case JoystickAxis.Z:
  47270. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  47271. break;
  47272. }
  47273. var directionUpDown = this.reverseUpDown ? 1 : -1;
  47274. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  47275. switch (this._axisTargetedByUpAndDown) {
  47276. case JoystickAxis.X:
  47277. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  47278. break;
  47279. case JoystickAxis.Y:
  47280. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  47281. break;
  47282. case JoystickAxis.Z:
  47283. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  47284. break;
  47285. }
  47286. }
  47287. else {
  47288. var data = this._touches.get(e.pointerId.toString());
  47289. if (data) {
  47290. data.x = e.clientX;
  47291. data.y = e.clientY;
  47292. }
  47293. }
  47294. };
  47295. VirtualJoystick.prototype._onPointerUp = function (e) {
  47296. if (this._joystickPointerID == e.pointerId) {
  47297. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  47298. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  47299. this._joystickPointerID = -1;
  47300. this.pressed = false;
  47301. }
  47302. else {
  47303. var touch = this._touches.get(e.pointerId.toString());
  47304. if (touch) {
  47305. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  47306. }
  47307. }
  47308. this._deltaJoystickVector.x = 0;
  47309. this._deltaJoystickVector.y = 0;
  47310. this._touches.remove(e.pointerId.toString());
  47311. };
  47312. /**
  47313. * Change the color of the virtual joystick
  47314. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  47315. */
  47316. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  47317. this._joystickColor = newColor;
  47318. };
  47319. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  47320. this._action = action;
  47321. };
  47322. // Define which axis you'd like to control for left & right
  47323. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  47324. switch (axis) {
  47325. case JoystickAxis.X:
  47326. case JoystickAxis.Y:
  47327. case JoystickAxis.Z:
  47328. this._axisTargetedByLeftAndRight = axis;
  47329. break;
  47330. default:
  47331. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  47332. break;
  47333. }
  47334. };
  47335. // Define which axis you'd like to control for up & down
  47336. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  47337. switch (axis) {
  47338. case JoystickAxis.X:
  47339. case JoystickAxis.Y:
  47340. case JoystickAxis.Z:
  47341. this._axisTargetedByUpAndDown = axis;
  47342. break;
  47343. default:
  47344. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  47345. break;
  47346. }
  47347. };
  47348. VirtualJoystick.prototype._clearCanvas = function () {
  47349. if (this._leftJoystick) {
  47350. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  47351. }
  47352. else {
  47353. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  47354. }
  47355. };
  47356. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  47357. var _this = this;
  47358. if (this.pressed) {
  47359. this._touches.forEach(function (key, touch) {
  47360. if (touch.pointerId === _this._joystickPointerID) {
  47361. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  47362. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  47363. VirtualJoystick.vjCanvasContext.beginPath();
  47364. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  47365. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  47366. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  47367. VirtualJoystick.vjCanvasContext.stroke();
  47368. VirtualJoystick.vjCanvasContext.closePath();
  47369. VirtualJoystick.vjCanvasContext.beginPath();
  47370. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  47371. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  47372. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  47373. VirtualJoystick.vjCanvasContext.stroke();
  47374. VirtualJoystick.vjCanvasContext.closePath();
  47375. VirtualJoystick.vjCanvasContext.beginPath();
  47376. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  47377. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  47378. VirtualJoystick.vjCanvasContext.stroke();
  47379. VirtualJoystick.vjCanvasContext.closePath();
  47380. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  47381. }
  47382. else {
  47383. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  47384. VirtualJoystick.vjCanvasContext.beginPath();
  47385. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  47386. VirtualJoystick.vjCanvasContext.beginPath();
  47387. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  47388. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  47389. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  47390. VirtualJoystick.vjCanvasContext.stroke();
  47391. VirtualJoystick.vjCanvasContext.closePath();
  47392. touch.prevX = touch.x;
  47393. touch.prevY = touch.y;
  47394. }
  47395. ;
  47396. });
  47397. }
  47398. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  47399. };
  47400. VirtualJoystick.prototype.releaseCanvas = function () {
  47401. if (VirtualJoystick.vjCanvas) {
  47402. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  47403. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  47404. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  47405. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  47406. window.removeEventListener("resize", this._onResize);
  47407. document.body.removeChild(VirtualJoystick.vjCanvas);
  47408. VirtualJoystick.vjCanvas = null;
  47409. }
  47410. };
  47411. return VirtualJoystick;
  47412. }());
  47413. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  47414. VirtualJoystick._globalJoystickIndex = 0;
  47415. BABYLON.VirtualJoystick = VirtualJoystick;
  47416. })(BABYLON || (BABYLON = {}));
  47417. //# sourceMappingURL=babylon.virtualJoystick.js.map
  47418. var BABYLON;
  47419. (function (BABYLON) {
  47420. // We're mainly based on the logic defined into the FreeCamera code
  47421. var VirtualJoysticksCamera = (function (_super) {
  47422. __extends(VirtualJoysticksCamera, _super);
  47423. function VirtualJoysticksCamera(name, position, scene) {
  47424. var _this = _super.call(this, name, position, scene) || this;
  47425. _this.inputs.addVirtualJoystick();
  47426. return _this;
  47427. }
  47428. VirtualJoysticksCamera.prototype.getClassName = function () {
  47429. return "VirtualJoysticksCamera";
  47430. };
  47431. return VirtualJoysticksCamera;
  47432. }(BABYLON.FreeCamera));
  47433. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  47434. })(BABYLON || (BABYLON = {}));
  47435. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  47436. var BABYLON;
  47437. (function (BABYLON) {
  47438. var FreeCameraVirtualJoystickInput = (function () {
  47439. function FreeCameraVirtualJoystickInput() {
  47440. }
  47441. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  47442. return this._leftjoystick;
  47443. };
  47444. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  47445. return this._rightjoystick;
  47446. };
  47447. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  47448. if (this._leftjoystick) {
  47449. var camera = this.camera;
  47450. var speed = camera._computeLocalCameraSpeed() * 50;
  47451. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  47452. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  47453. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  47454. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  47455. if (!this._leftjoystick.pressed) {
  47456. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  47457. }
  47458. if (!this._rightjoystick.pressed) {
  47459. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  47460. }
  47461. }
  47462. };
  47463. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  47464. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  47465. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  47466. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  47467. this._leftjoystick.setJoystickSensibility(0.15);
  47468. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  47469. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  47470. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  47471. this._rightjoystick.reverseUpDown = true;
  47472. this._rightjoystick.setJoystickSensibility(0.05);
  47473. this._rightjoystick.setJoystickColor("yellow");
  47474. };
  47475. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  47476. this._leftjoystick.releaseCanvas();
  47477. this._rightjoystick.releaseCanvas();
  47478. };
  47479. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  47480. return "FreeCameraVirtualJoystickInput";
  47481. };
  47482. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  47483. return "virtualJoystick";
  47484. };
  47485. return FreeCameraVirtualJoystickInput;
  47486. }());
  47487. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  47488. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  47489. })(BABYLON || (BABYLON = {}));
  47490. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  47491. var BABYLON;
  47492. (function (BABYLON) {
  47493. var AnaglyphPostProcess = (function (_super) {
  47494. __extends(AnaglyphPostProcess, _super);
  47495. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  47496. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  47497. _this._passedProcess = rigCameras[0]._rigPostProcess;
  47498. _this.onApplyObservable.add(function (effect) {
  47499. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  47500. });
  47501. return _this;
  47502. }
  47503. return AnaglyphPostProcess;
  47504. }(BABYLON.PostProcess));
  47505. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  47506. })(BABYLON || (BABYLON = {}));
  47507. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  47508. var BABYLON;
  47509. (function (BABYLON) {
  47510. var OutlineRenderer = (function () {
  47511. function OutlineRenderer(scene) {
  47512. this._scene = scene;
  47513. }
  47514. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  47515. var _this = this;
  47516. if (useOverlay === void 0) { useOverlay = false; }
  47517. var scene = this._scene;
  47518. var engine = this._scene.getEngine();
  47519. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  47520. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  47521. return;
  47522. }
  47523. var mesh = subMesh.getRenderingMesh();
  47524. var material = subMesh.getMaterial();
  47525. engine.enableEffect(this._effect);
  47526. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  47527. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  47528. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  47529. // Bones
  47530. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47531. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47532. }
  47533. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  47534. // Alpha test
  47535. if (material && material.needAlphaTesting()) {
  47536. var alphaTexture = material.getAlphaTestTexture();
  47537. this._effect.setTexture("diffuseSampler", alphaTexture);
  47538. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47539. }
  47540. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  47541. };
  47542. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  47543. var defines = [];
  47544. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  47545. var mesh = subMesh.getMesh();
  47546. var material = subMesh.getMaterial();
  47547. // Alpha test
  47548. if (material && material.needAlphaTesting()) {
  47549. defines.push("#define ALPHATEST");
  47550. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47551. attribs.push(BABYLON.VertexBuffer.UVKind);
  47552. defines.push("#define UV1");
  47553. }
  47554. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47555. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47556. defines.push("#define UV2");
  47557. }
  47558. }
  47559. // Bones
  47560. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47561. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47562. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47563. if (mesh.numBoneInfluencers > 4) {
  47564. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47565. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47566. }
  47567. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47568. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47569. }
  47570. else {
  47571. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47572. }
  47573. // Instances
  47574. if (useInstances) {
  47575. defines.push("#define INSTANCES");
  47576. attribs.push("world0");
  47577. attribs.push("world1");
  47578. attribs.push("world2");
  47579. attribs.push("world3");
  47580. }
  47581. // Get correct effect
  47582. var join = defines.join("\n");
  47583. if (this._cachedDefines !== join) {
  47584. this._cachedDefines = join;
  47585. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  47586. }
  47587. return this._effect.isReady();
  47588. };
  47589. return OutlineRenderer;
  47590. }());
  47591. BABYLON.OutlineRenderer = OutlineRenderer;
  47592. })(BABYLON || (BABYLON = {}));
  47593. //# sourceMappingURL=babylon.outlineRenderer.js.map
  47594. var BABYLON;
  47595. (function (BABYLON) {
  47596. var MeshAssetTask = (function () {
  47597. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  47598. this.name = name;
  47599. this.meshesNames = meshesNames;
  47600. this.rootUrl = rootUrl;
  47601. this.sceneFilename = sceneFilename;
  47602. this.isCompleted = false;
  47603. }
  47604. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47605. var _this = this;
  47606. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  47607. _this.loadedMeshes = meshes;
  47608. _this.loadedParticleSystems = particleSystems;
  47609. _this.loadedSkeletons = skeletons;
  47610. _this.isCompleted = true;
  47611. if (_this.onSuccess) {
  47612. _this.onSuccess(_this);
  47613. }
  47614. onSuccess();
  47615. }, null, function () {
  47616. if (_this.onError) {
  47617. _this.onError(_this);
  47618. }
  47619. onError();
  47620. });
  47621. };
  47622. return MeshAssetTask;
  47623. }());
  47624. BABYLON.MeshAssetTask = MeshAssetTask;
  47625. var TextFileAssetTask = (function () {
  47626. function TextFileAssetTask(name, url) {
  47627. this.name = name;
  47628. this.url = url;
  47629. this.isCompleted = false;
  47630. }
  47631. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47632. var _this = this;
  47633. BABYLON.Tools.LoadFile(this.url, function (data) {
  47634. _this.text = data;
  47635. _this.isCompleted = true;
  47636. if (_this.onSuccess) {
  47637. _this.onSuccess(_this);
  47638. }
  47639. onSuccess();
  47640. }, null, scene.database, false, function () {
  47641. if (_this.onError) {
  47642. _this.onError(_this);
  47643. }
  47644. onError();
  47645. });
  47646. };
  47647. return TextFileAssetTask;
  47648. }());
  47649. BABYLON.TextFileAssetTask = TextFileAssetTask;
  47650. var BinaryFileAssetTask = (function () {
  47651. function BinaryFileAssetTask(name, url) {
  47652. this.name = name;
  47653. this.url = url;
  47654. this.isCompleted = false;
  47655. }
  47656. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47657. var _this = this;
  47658. BABYLON.Tools.LoadFile(this.url, function (data) {
  47659. _this.data = data;
  47660. _this.isCompleted = true;
  47661. if (_this.onSuccess) {
  47662. _this.onSuccess(_this);
  47663. }
  47664. onSuccess();
  47665. }, null, scene.database, true, function () {
  47666. if (_this.onError) {
  47667. _this.onError(_this);
  47668. }
  47669. onError();
  47670. });
  47671. };
  47672. return BinaryFileAssetTask;
  47673. }());
  47674. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  47675. var ImageAssetTask = (function () {
  47676. function ImageAssetTask(name, url) {
  47677. this.name = name;
  47678. this.url = url;
  47679. this.isCompleted = false;
  47680. }
  47681. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47682. var _this = this;
  47683. var img = new Image();
  47684. BABYLON.Tools.SetCorsBehavior(this.url, img);
  47685. img.onload = function () {
  47686. _this.image = img;
  47687. _this.isCompleted = true;
  47688. if (_this.onSuccess) {
  47689. _this.onSuccess(_this);
  47690. }
  47691. onSuccess();
  47692. };
  47693. img.onerror = function () {
  47694. if (_this.onError) {
  47695. _this.onError(_this);
  47696. }
  47697. onError();
  47698. };
  47699. img.src = this.url;
  47700. };
  47701. return ImageAssetTask;
  47702. }());
  47703. BABYLON.ImageAssetTask = ImageAssetTask;
  47704. var TextureAssetTask = (function () {
  47705. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  47706. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47707. this.name = name;
  47708. this.url = url;
  47709. this.noMipmap = noMipmap;
  47710. this.invertY = invertY;
  47711. this.samplingMode = samplingMode;
  47712. this.isCompleted = false;
  47713. }
  47714. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47715. var _this = this;
  47716. var onload = function () {
  47717. _this.isCompleted = true;
  47718. if (_this.onSuccess) {
  47719. _this.onSuccess(_this);
  47720. }
  47721. onSuccess();
  47722. };
  47723. var onerror = function () {
  47724. if (_this.onError) {
  47725. _this.onError(_this);
  47726. }
  47727. onError();
  47728. };
  47729. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  47730. };
  47731. return TextureAssetTask;
  47732. }());
  47733. BABYLON.TextureAssetTask = TextureAssetTask;
  47734. var CubeTextureAssetTask = (function () {
  47735. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  47736. this.name = name;
  47737. this.url = url;
  47738. this.extensions = extensions;
  47739. this.noMipmap = noMipmap;
  47740. this.files = files;
  47741. this.isCompleted = false;
  47742. }
  47743. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47744. var _this = this;
  47745. var onload = function () {
  47746. _this.isCompleted = true;
  47747. if (_this.onSuccess) {
  47748. _this.onSuccess(_this);
  47749. }
  47750. onSuccess();
  47751. };
  47752. var onerror = function () {
  47753. if (_this.onError) {
  47754. _this.onError(_this);
  47755. }
  47756. onError();
  47757. };
  47758. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  47759. };
  47760. return CubeTextureAssetTask;
  47761. }());
  47762. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  47763. var HDRCubeTextureAssetTask = (function () {
  47764. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  47765. if (noMipmap === void 0) { noMipmap = false; }
  47766. if (generateHarmonics === void 0) { generateHarmonics = true; }
  47767. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  47768. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  47769. this.name = name;
  47770. this.url = url;
  47771. this.size = size;
  47772. this.noMipmap = noMipmap;
  47773. this.generateHarmonics = generateHarmonics;
  47774. this.useInGammaSpace = useInGammaSpace;
  47775. this.usePMREMGenerator = usePMREMGenerator;
  47776. this.isCompleted = false;
  47777. }
  47778. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  47779. var _this = this;
  47780. var onload = function () {
  47781. _this.isCompleted = true;
  47782. if (_this.onSuccess) {
  47783. _this.onSuccess(_this);
  47784. }
  47785. onSuccess();
  47786. };
  47787. var onerror = function () {
  47788. if (_this.onError) {
  47789. _this.onError(_this);
  47790. }
  47791. onError();
  47792. };
  47793. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  47794. };
  47795. return HDRCubeTextureAssetTask;
  47796. }());
  47797. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  47798. var AssetsManager = (function () {
  47799. function AssetsManager(scene) {
  47800. this.tasks = new Array();
  47801. this.waitingTasksCount = 0;
  47802. this.useDefaultLoadingScreen = true;
  47803. this._scene = scene;
  47804. }
  47805. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  47806. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  47807. this.tasks.push(task);
  47808. return task;
  47809. };
  47810. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  47811. var task = new TextFileAssetTask(taskName, url);
  47812. this.tasks.push(task);
  47813. return task;
  47814. };
  47815. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  47816. var task = new BinaryFileAssetTask(taskName, url);
  47817. this.tasks.push(task);
  47818. return task;
  47819. };
  47820. AssetsManager.prototype.addImageTask = function (taskName, url) {
  47821. var task = new ImageAssetTask(taskName, url);
  47822. this.tasks.push(task);
  47823. return task;
  47824. };
  47825. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  47826. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47827. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  47828. this.tasks.push(task);
  47829. return task;
  47830. };
  47831. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  47832. this.waitingTasksCount--;
  47833. if (this.waitingTasksCount === 0) {
  47834. if (this.onFinish) {
  47835. this.onFinish(this.tasks);
  47836. }
  47837. this._scene.getEngine().hideLoadingUI();
  47838. }
  47839. };
  47840. AssetsManager.prototype._runTask = function (task) {
  47841. var _this = this;
  47842. task.run(this._scene, function () {
  47843. if (_this.onTaskSuccess) {
  47844. _this.onTaskSuccess(task);
  47845. }
  47846. _this._decreaseWaitingTasksCount();
  47847. }, function () {
  47848. if (_this.onTaskError) {
  47849. _this.onTaskError(task);
  47850. }
  47851. _this._decreaseWaitingTasksCount();
  47852. });
  47853. };
  47854. AssetsManager.prototype.reset = function () {
  47855. this.tasks = new Array();
  47856. return this;
  47857. };
  47858. AssetsManager.prototype.load = function () {
  47859. this.waitingTasksCount = this.tasks.length;
  47860. if (this.waitingTasksCount === 0) {
  47861. if (this.onFinish) {
  47862. this.onFinish(this.tasks);
  47863. }
  47864. return this;
  47865. }
  47866. if (this.useDefaultLoadingScreen) {
  47867. this._scene.getEngine().displayLoadingUI();
  47868. }
  47869. for (var index = 0; index < this.tasks.length; index++) {
  47870. var task = this.tasks[index];
  47871. this._runTask(task);
  47872. }
  47873. return this;
  47874. };
  47875. return AssetsManager;
  47876. }());
  47877. BABYLON.AssetsManager = AssetsManager;
  47878. })(BABYLON || (BABYLON = {}));
  47879. //# sourceMappingURL=babylon.assetsManager.js.map
  47880. var BABYLON;
  47881. (function (BABYLON) {
  47882. var VRCameraMetrics = (function () {
  47883. function VRCameraMetrics() {
  47884. this.compensateDistortion = true;
  47885. }
  47886. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  47887. get: function () {
  47888. return this.hResolution / (2 * this.vResolution);
  47889. },
  47890. enumerable: true,
  47891. configurable: true
  47892. });
  47893. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  47894. get: function () {
  47895. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  47896. },
  47897. enumerable: true,
  47898. configurable: true
  47899. });
  47900. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  47901. get: function () {
  47902. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  47903. var h = (4 * meters) / this.hScreenSize;
  47904. return BABYLON.Matrix.Translation(h, 0, 0);
  47905. },
  47906. enumerable: true,
  47907. configurable: true
  47908. });
  47909. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  47910. get: function () {
  47911. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  47912. var h = (4 * meters) / this.hScreenSize;
  47913. return BABYLON.Matrix.Translation(-h, 0, 0);
  47914. },
  47915. enumerable: true,
  47916. configurable: true
  47917. });
  47918. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  47919. get: function () {
  47920. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  47921. },
  47922. enumerable: true,
  47923. configurable: true
  47924. });
  47925. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  47926. get: function () {
  47927. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  47928. },
  47929. enumerable: true,
  47930. configurable: true
  47931. });
  47932. VRCameraMetrics.GetDefault = function () {
  47933. var result = new VRCameraMetrics();
  47934. result.hResolution = 1280;
  47935. result.vResolution = 800;
  47936. result.hScreenSize = 0.149759993;
  47937. result.vScreenSize = 0.0935999975;
  47938. result.vScreenCenter = 0.0467999987;
  47939. result.eyeToScreenDistance = 0.0410000011;
  47940. result.lensSeparationDistance = 0.0635000020;
  47941. result.interpupillaryDistance = 0.0640000030;
  47942. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  47943. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  47944. result.postProcessScaleFactor = 1.714605507808412;
  47945. result.lensCenterOffset = 0.151976421;
  47946. return result;
  47947. };
  47948. return VRCameraMetrics;
  47949. }());
  47950. BABYLON.VRCameraMetrics = VRCameraMetrics;
  47951. })(BABYLON || (BABYLON = {}));
  47952. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  47953. var BABYLON;
  47954. (function (BABYLON) {
  47955. var WebVRFreeCamera = (function (_super) {
  47956. __extends(WebVRFreeCamera, _super);
  47957. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  47958. if (compensateDistortion === void 0) { compensateDistortion = false; }
  47959. if (webVROptions === void 0) { webVROptions = {}; }
  47960. var _this = _super.call(this, name, position, scene) || this;
  47961. _this.webVROptions = webVROptions;
  47962. _this._vrDevice = null;
  47963. _this._cacheState = null;
  47964. _this._vrEnabled = false;
  47965. _this._attached = false;
  47966. //using the position provided as the current position offset
  47967. _this._positionOffset = position;
  47968. //enable VR
  47969. _this.getEngine().initWebVR();
  47970. if (!_this.getEngine().vrDisplaysPromise) {
  47971. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  47972. }
  47973. else {
  47974. //TODO get the metrics updated using the device's eye parameters!
  47975. //TODO also check that the device has the right capabilities!
  47976. _this._frameData = new VRFrameData();
  47977. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  47978. if (devices.length > 0) {
  47979. _this._vrEnabled = true;
  47980. if (_this.webVROptions.displayName) {
  47981. var found = devices.some(function (device) {
  47982. if (device.displayName === _this.webVROptions.displayName) {
  47983. _this._vrDevice = device;
  47984. return true;
  47985. }
  47986. else {
  47987. return false;
  47988. }
  47989. });
  47990. if (!found) {
  47991. _this._vrDevice = devices[0];
  47992. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  47993. }
  47994. }
  47995. else {
  47996. //choose the first one
  47997. _this._vrDevice = devices[0];
  47998. }
  47999. //reset the rig parameters.
  48000. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  48001. if (_this._attached) {
  48002. _this.getEngine().enableVR(_this._vrDevice);
  48003. }
  48004. }
  48005. else {
  48006. BABYLON.Tools.Error("No WebVR devices found!");
  48007. }
  48008. });
  48009. }
  48010. _this.rotationQuaternion = new BABYLON.Quaternion();
  48011. _this._quaternionCache = new BABYLON.Quaternion();
  48012. return _this;
  48013. }
  48014. WebVRFreeCamera.prototype._checkInputs = function () {
  48015. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  48016. var currentPost = this._frameData.pose;
  48017. //make sure we have data
  48018. if (currentPost && currentPost.orientation) {
  48019. this._cacheState = currentPost;
  48020. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  48021. if (this.webVROptions.trackPosition && this._cacheState.position) {
  48022. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  48023. //scale the position accordingly
  48024. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  48025. //add the position offset
  48026. this.position.addInPlace(this._positionOffset);
  48027. }
  48028. }
  48029. }
  48030. _super.prototype._checkInputs.call(this);
  48031. };
  48032. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48033. _super.prototype.attachControl.call(this, element, noPreventDefault);
  48034. this._attached = true;
  48035. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  48036. if (this._vrEnabled) {
  48037. this.getEngine().enableVR(this._vrDevice);
  48038. }
  48039. };
  48040. WebVRFreeCamera.prototype.detachControl = function (element) {
  48041. _super.prototype.detachControl.call(this, element);
  48042. this._vrEnabled = false;
  48043. this._attached = false;
  48044. this.getEngine().disableVR();
  48045. };
  48046. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  48047. //Backwards comp.
  48048. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  48049. //this.getEngine().switchFullscreen(requestPointerlock);
  48050. };
  48051. WebVRFreeCamera.prototype.getClassName = function () {
  48052. return "WebVRFreeCamera";
  48053. };
  48054. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  48055. //uses the vrDisplay's "resetPose()".
  48056. //pitch and roll won't be affected.
  48057. this._vrDevice.resetPose();
  48058. };
  48059. /**
  48060. *
  48061. * Set the position offset of the VR camera
  48062. * The offset will be added to the WebVR pose, after scaling it (if set).
  48063. *
  48064. * @param {Vector3} [newPosition] an optional new position. if not provided, the current camera position will be used.
  48065. *
  48066. * @memberOf WebVRFreeCamera
  48067. */
  48068. WebVRFreeCamera.prototype.setPositionOffset = function (newPosition) {
  48069. if (newPosition) {
  48070. this._positionOffset = newPosition;
  48071. }
  48072. else {
  48073. this._positionOffset.copyFrom(this.position);
  48074. }
  48075. };
  48076. return WebVRFreeCamera;
  48077. }(BABYLON.FreeCamera));
  48078. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  48079. var WebVRGamepadCamera = (function (_super) {
  48080. __extends(WebVRGamepadCamera, _super);
  48081. function WebVRGamepadCamera(name, position, scene, compensateDistortion, webVROptions) {
  48082. if (compensateDistortion === void 0) { compensateDistortion = false; }
  48083. if (webVROptions === void 0) { webVROptions = {}; }
  48084. var _this = _super.call(this, name, position, scene, compensateDistortion, webVROptions) || this;
  48085. _this.inputs.addGamepad();
  48086. return _this;
  48087. }
  48088. WebVRGamepadCamera.prototype.getClassName = function () {
  48089. return "WebVRGamepadCamera";
  48090. };
  48091. return WebVRGamepadCamera;
  48092. }(WebVRFreeCamera));
  48093. BABYLON.WebVRGamepadCamera = WebVRGamepadCamera;
  48094. })(BABYLON || (BABYLON = {}));
  48095. //# sourceMappingURL=babylon.webVRCamera.js.map
  48096. var BABYLON;
  48097. (function (BABYLON) {
  48098. // Standard optimizations
  48099. var SceneOptimization = (function () {
  48100. function SceneOptimization(priority) {
  48101. if (priority === void 0) { priority = 0; }
  48102. this.priority = priority;
  48103. this.apply = function (scene) {
  48104. return true; // Return true if everything that can be done was applied
  48105. };
  48106. }
  48107. return SceneOptimization;
  48108. }());
  48109. BABYLON.SceneOptimization = SceneOptimization;
  48110. var TextureOptimization = (function (_super) {
  48111. __extends(TextureOptimization, _super);
  48112. function TextureOptimization(priority, maximumSize) {
  48113. if (priority === void 0) { priority = 0; }
  48114. if (maximumSize === void 0) { maximumSize = 1024; }
  48115. var _this = _super.call(this, priority) || this;
  48116. _this.priority = priority;
  48117. _this.maximumSize = maximumSize;
  48118. _this.apply = function (scene) {
  48119. var allDone = true;
  48120. for (var index = 0; index < scene.textures.length; index++) {
  48121. var texture = scene.textures[index];
  48122. if (!texture.canRescale) {
  48123. continue;
  48124. }
  48125. var currentSize = texture.getSize();
  48126. var maxDimension = Math.max(currentSize.width, currentSize.height);
  48127. if (maxDimension > _this.maximumSize) {
  48128. texture.scale(0.5);
  48129. allDone = false;
  48130. }
  48131. }
  48132. return allDone;
  48133. };
  48134. return _this;
  48135. }
  48136. return TextureOptimization;
  48137. }(SceneOptimization));
  48138. BABYLON.TextureOptimization = TextureOptimization;
  48139. var HardwareScalingOptimization = (function (_super) {
  48140. __extends(HardwareScalingOptimization, _super);
  48141. function HardwareScalingOptimization(priority, maximumScale) {
  48142. if (priority === void 0) { priority = 0; }
  48143. if (maximumScale === void 0) { maximumScale = 2; }
  48144. var _this = _super.call(this, priority) || this;
  48145. _this.priority = priority;
  48146. _this.maximumScale = maximumScale;
  48147. _this._currentScale = 1;
  48148. _this.apply = function (scene) {
  48149. _this._currentScale++;
  48150. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  48151. return _this._currentScale >= _this.maximumScale;
  48152. };
  48153. return _this;
  48154. }
  48155. return HardwareScalingOptimization;
  48156. }(SceneOptimization));
  48157. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  48158. var ShadowsOptimization = (function (_super) {
  48159. __extends(ShadowsOptimization, _super);
  48160. function ShadowsOptimization() {
  48161. var _this = _super !== null && _super.apply(this, arguments) || this;
  48162. _this.apply = function (scene) {
  48163. scene.shadowsEnabled = false;
  48164. return true;
  48165. };
  48166. return _this;
  48167. }
  48168. return ShadowsOptimization;
  48169. }(SceneOptimization));
  48170. BABYLON.ShadowsOptimization = ShadowsOptimization;
  48171. var PostProcessesOptimization = (function (_super) {
  48172. __extends(PostProcessesOptimization, _super);
  48173. function PostProcessesOptimization() {
  48174. var _this = _super !== null && _super.apply(this, arguments) || this;
  48175. _this.apply = function (scene) {
  48176. scene.postProcessesEnabled = false;
  48177. return true;
  48178. };
  48179. return _this;
  48180. }
  48181. return PostProcessesOptimization;
  48182. }(SceneOptimization));
  48183. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  48184. var LensFlaresOptimization = (function (_super) {
  48185. __extends(LensFlaresOptimization, _super);
  48186. function LensFlaresOptimization() {
  48187. var _this = _super !== null && _super.apply(this, arguments) || this;
  48188. _this.apply = function (scene) {
  48189. scene.lensFlaresEnabled = false;
  48190. return true;
  48191. };
  48192. return _this;
  48193. }
  48194. return LensFlaresOptimization;
  48195. }(SceneOptimization));
  48196. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  48197. var ParticlesOptimization = (function (_super) {
  48198. __extends(ParticlesOptimization, _super);
  48199. function ParticlesOptimization() {
  48200. var _this = _super !== null && _super.apply(this, arguments) || this;
  48201. _this.apply = function (scene) {
  48202. scene.particlesEnabled = false;
  48203. return true;
  48204. };
  48205. return _this;
  48206. }
  48207. return ParticlesOptimization;
  48208. }(SceneOptimization));
  48209. BABYLON.ParticlesOptimization = ParticlesOptimization;
  48210. var RenderTargetsOptimization = (function (_super) {
  48211. __extends(RenderTargetsOptimization, _super);
  48212. function RenderTargetsOptimization() {
  48213. var _this = _super !== null && _super.apply(this, arguments) || this;
  48214. _this.apply = function (scene) {
  48215. scene.renderTargetsEnabled = false;
  48216. return true;
  48217. };
  48218. return _this;
  48219. }
  48220. return RenderTargetsOptimization;
  48221. }(SceneOptimization));
  48222. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  48223. var MergeMeshesOptimization = (function (_super) {
  48224. __extends(MergeMeshesOptimization, _super);
  48225. function MergeMeshesOptimization() {
  48226. var _this = _super !== null && _super.apply(this, arguments) || this;
  48227. _this._canBeMerged = function (abstractMesh) {
  48228. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  48229. return false;
  48230. }
  48231. var mesh = abstractMesh;
  48232. if (!mesh.isVisible || !mesh.isEnabled()) {
  48233. return false;
  48234. }
  48235. if (mesh.instances.length > 0) {
  48236. return false;
  48237. }
  48238. if (mesh.skeleton || mesh.hasLODLevels) {
  48239. return false;
  48240. }
  48241. if (mesh.parent) {
  48242. return false;
  48243. }
  48244. return true;
  48245. };
  48246. _this.apply = function (scene, updateSelectionTree) {
  48247. var globalPool = scene.meshes.slice(0);
  48248. var globalLength = globalPool.length;
  48249. for (var index = 0; index < globalLength; index++) {
  48250. var currentPool = new Array();
  48251. var current = globalPool[index];
  48252. // Checks
  48253. if (!_this._canBeMerged(current)) {
  48254. continue;
  48255. }
  48256. currentPool.push(current);
  48257. // Find compatible meshes
  48258. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  48259. var otherMesh = globalPool[subIndex];
  48260. if (!_this._canBeMerged(otherMesh)) {
  48261. continue;
  48262. }
  48263. if (otherMesh.material !== current.material) {
  48264. continue;
  48265. }
  48266. if (otherMesh.checkCollisions !== current.checkCollisions) {
  48267. continue;
  48268. }
  48269. currentPool.push(otherMesh);
  48270. globalLength--;
  48271. globalPool.splice(subIndex, 1);
  48272. subIndex--;
  48273. }
  48274. if (currentPool.length < 2) {
  48275. continue;
  48276. }
  48277. // Merge meshes
  48278. BABYLON.Mesh.MergeMeshes(currentPool);
  48279. }
  48280. if (updateSelectionTree != undefined) {
  48281. if (updateSelectionTree) {
  48282. scene.createOrUpdateSelectionOctree();
  48283. }
  48284. }
  48285. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  48286. scene.createOrUpdateSelectionOctree();
  48287. }
  48288. return true;
  48289. };
  48290. return _this;
  48291. }
  48292. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  48293. get: function () {
  48294. return MergeMeshesOptimization._UpdateSelectionTree;
  48295. },
  48296. set: function (value) {
  48297. MergeMeshesOptimization._UpdateSelectionTree = value;
  48298. },
  48299. enumerable: true,
  48300. configurable: true
  48301. });
  48302. return MergeMeshesOptimization;
  48303. }(SceneOptimization));
  48304. MergeMeshesOptimization._UpdateSelectionTree = false;
  48305. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  48306. // Options
  48307. var SceneOptimizerOptions = (function () {
  48308. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  48309. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  48310. if (trackerDuration === void 0) { trackerDuration = 2000; }
  48311. this.targetFrameRate = targetFrameRate;
  48312. this.trackerDuration = trackerDuration;
  48313. this.optimizations = new Array();
  48314. }
  48315. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  48316. var result = new SceneOptimizerOptions(targetFrameRate);
  48317. var priority = 0;
  48318. result.optimizations.push(new MergeMeshesOptimization(priority));
  48319. result.optimizations.push(new ShadowsOptimization(priority));
  48320. result.optimizations.push(new LensFlaresOptimization(priority));
  48321. // Next priority
  48322. priority++;
  48323. result.optimizations.push(new PostProcessesOptimization(priority));
  48324. result.optimizations.push(new ParticlesOptimization(priority));
  48325. // Next priority
  48326. priority++;
  48327. result.optimizations.push(new TextureOptimization(priority, 1024));
  48328. return result;
  48329. };
  48330. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  48331. var result = new SceneOptimizerOptions(targetFrameRate);
  48332. var priority = 0;
  48333. result.optimizations.push(new MergeMeshesOptimization(priority));
  48334. result.optimizations.push(new ShadowsOptimization(priority));
  48335. result.optimizations.push(new LensFlaresOptimization(priority));
  48336. // Next priority
  48337. priority++;
  48338. result.optimizations.push(new PostProcessesOptimization(priority));
  48339. result.optimizations.push(new ParticlesOptimization(priority));
  48340. // Next priority
  48341. priority++;
  48342. result.optimizations.push(new TextureOptimization(priority, 512));
  48343. // Next priority
  48344. priority++;
  48345. result.optimizations.push(new RenderTargetsOptimization(priority));
  48346. // Next priority
  48347. priority++;
  48348. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  48349. return result;
  48350. };
  48351. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  48352. var result = new SceneOptimizerOptions(targetFrameRate);
  48353. var priority = 0;
  48354. result.optimizations.push(new MergeMeshesOptimization(priority));
  48355. result.optimizations.push(new ShadowsOptimization(priority));
  48356. result.optimizations.push(new LensFlaresOptimization(priority));
  48357. // Next priority
  48358. priority++;
  48359. result.optimizations.push(new PostProcessesOptimization(priority));
  48360. result.optimizations.push(new ParticlesOptimization(priority));
  48361. // Next priority
  48362. priority++;
  48363. result.optimizations.push(new TextureOptimization(priority, 256));
  48364. // Next priority
  48365. priority++;
  48366. result.optimizations.push(new RenderTargetsOptimization(priority));
  48367. // Next priority
  48368. priority++;
  48369. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  48370. return result;
  48371. };
  48372. return SceneOptimizerOptions;
  48373. }());
  48374. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  48375. // Scene optimizer tool
  48376. var SceneOptimizer = (function () {
  48377. function SceneOptimizer() {
  48378. }
  48379. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  48380. // TODO: add an epsilon
  48381. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  48382. if (onSuccess) {
  48383. onSuccess();
  48384. }
  48385. return;
  48386. }
  48387. // Apply current level of optimizations
  48388. var allDone = true;
  48389. var noOptimizationApplied = true;
  48390. for (var index = 0; index < options.optimizations.length; index++) {
  48391. var optimization = options.optimizations[index];
  48392. if (optimization.priority === currentPriorityLevel) {
  48393. noOptimizationApplied = false;
  48394. allDone = allDone && optimization.apply(scene);
  48395. }
  48396. }
  48397. // If no optimization was applied, this is a failure :(
  48398. if (noOptimizationApplied) {
  48399. if (onFailure) {
  48400. onFailure();
  48401. }
  48402. return;
  48403. }
  48404. // If all optimizations were done, move to next level
  48405. if (allDone) {
  48406. currentPriorityLevel++;
  48407. }
  48408. // Let's the system running for a specific amount of time before checking FPS
  48409. scene.executeWhenReady(function () {
  48410. setTimeout(function () {
  48411. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  48412. }, options.trackerDuration);
  48413. });
  48414. };
  48415. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  48416. if (!options) {
  48417. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  48418. }
  48419. // Let's the system running for a specific amount of time before checking FPS
  48420. scene.executeWhenReady(function () {
  48421. setTimeout(function () {
  48422. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  48423. }, options.trackerDuration);
  48424. });
  48425. };
  48426. return SceneOptimizer;
  48427. }());
  48428. BABYLON.SceneOptimizer = SceneOptimizer;
  48429. })(BABYLON || (BABYLON = {}));
  48430. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  48431. var BABYLON;
  48432. (function (BABYLON) {
  48433. var Internals;
  48434. (function (Internals) {
  48435. var MeshLODLevel = (function () {
  48436. function MeshLODLevel(distance, mesh) {
  48437. this.distance = distance;
  48438. this.mesh = mesh;
  48439. }
  48440. return MeshLODLevel;
  48441. }());
  48442. Internals.MeshLODLevel = MeshLODLevel;
  48443. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48444. })(BABYLON || (BABYLON = {}));
  48445. //# sourceMappingURL=babylon.meshLODLevel.js.map
  48446. var BABYLON;
  48447. (function (BABYLON) {
  48448. var RawTexture = (function (_super) {
  48449. __extends(RawTexture, _super);
  48450. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  48451. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48452. if (invertY === void 0) { invertY = false; }
  48453. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48454. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  48455. _this.format = format;
  48456. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  48457. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48458. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48459. return _this;
  48460. }
  48461. RawTexture.prototype.update = function (data) {
  48462. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  48463. };
  48464. // Statics
  48465. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48466. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48467. if (invertY === void 0) { invertY = false; }
  48468. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48469. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  48470. };
  48471. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48472. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48473. if (invertY === void 0) { invertY = false; }
  48474. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48475. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  48476. };
  48477. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48478. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48479. if (invertY === void 0) { invertY = false; }
  48480. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48481. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  48482. };
  48483. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48484. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48485. if (invertY === void 0) { invertY = false; }
  48486. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48487. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  48488. };
  48489. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48490. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48491. if (invertY === void 0) { invertY = false; }
  48492. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48493. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  48494. };
  48495. return RawTexture;
  48496. }(BABYLON.Texture));
  48497. BABYLON.RawTexture = RawTexture;
  48498. })(BABYLON || (BABYLON = {}));
  48499. //# sourceMappingURL=babylon.rawTexture.js.map
  48500. /// <reference path="..\Math\babylon.math.ts" />
  48501. var BABYLON;
  48502. (function (BABYLON) {
  48503. var IndexedVector2 = (function (_super) {
  48504. __extends(IndexedVector2, _super);
  48505. function IndexedVector2(original, index) {
  48506. var _this = _super.call(this, original.x, original.y) || this;
  48507. _this.index = index;
  48508. return _this;
  48509. }
  48510. return IndexedVector2;
  48511. }(BABYLON.Vector2));
  48512. var PolygonPoints = (function () {
  48513. function PolygonPoints() {
  48514. this.elements = new Array();
  48515. }
  48516. PolygonPoints.prototype.add = function (originalPoints) {
  48517. var _this = this;
  48518. var result = new Array();
  48519. originalPoints.forEach(function (point) {
  48520. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  48521. var newPoint = new IndexedVector2(point, _this.elements.length);
  48522. result.push(newPoint);
  48523. _this.elements.push(newPoint);
  48524. }
  48525. });
  48526. return result;
  48527. };
  48528. PolygonPoints.prototype.computeBounds = function () {
  48529. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  48530. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  48531. this.elements.forEach(function (point) {
  48532. // x
  48533. if (point.x < lmin.x) {
  48534. lmin.x = point.x;
  48535. }
  48536. else if (point.x > lmax.x) {
  48537. lmax.x = point.x;
  48538. }
  48539. // y
  48540. if (point.y < lmin.y) {
  48541. lmin.y = point.y;
  48542. }
  48543. else if (point.y > lmax.y) {
  48544. lmax.y = point.y;
  48545. }
  48546. });
  48547. return {
  48548. min: lmin,
  48549. max: lmax,
  48550. width: lmax.x - lmin.x,
  48551. height: lmax.y - lmin.y
  48552. };
  48553. };
  48554. return PolygonPoints;
  48555. }());
  48556. var Polygon = (function () {
  48557. function Polygon() {
  48558. }
  48559. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  48560. return [
  48561. new BABYLON.Vector2(xmin, ymin),
  48562. new BABYLON.Vector2(xmax, ymin),
  48563. new BABYLON.Vector2(xmax, ymax),
  48564. new BABYLON.Vector2(xmin, ymax)
  48565. ];
  48566. };
  48567. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  48568. if (cx === void 0) { cx = 0; }
  48569. if (cy === void 0) { cy = 0; }
  48570. if (numberOfSides === void 0) { numberOfSides = 32; }
  48571. var result = new Array();
  48572. var angle = 0;
  48573. var increment = (Math.PI * 2) / numberOfSides;
  48574. for (var i = 0; i < numberOfSides; i++) {
  48575. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  48576. angle -= increment;
  48577. }
  48578. return result;
  48579. };
  48580. Polygon.Parse = function (input) {
  48581. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  48582. var i, result = [];
  48583. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  48584. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  48585. }
  48586. return result;
  48587. };
  48588. Polygon.StartingAt = function (x, y) {
  48589. return BABYLON.Path2.StartingAt(x, y);
  48590. };
  48591. return Polygon;
  48592. }());
  48593. BABYLON.Polygon = Polygon;
  48594. var PolygonMeshBuilder = (function () {
  48595. function PolygonMeshBuilder(name, contours, scene) {
  48596. this._points = new PolygonPoints();
  48597. this._outlinepoints = new PolygonPoints();
  48598. this._holes = [];
  48599. this._epoints = new Array();
  48600. this._eholes = new Array();
  48601. this._name = name;
  48602. this._scene = scene;
  48603. var points;
  48604. if (contours instanceof BABYLON.Path2) {
  48605. points = contours.getPoints();
  48606. }
  48607. else {
  48608. points = contours;
  48609. }
  48610. this._addToepoint(points);
  48611. this._points.add(points);
  48612. this._outlinepoints.add(points);
  48613. }
  48614. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  48615. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  48616. var p = points_1[_i];
  48617. this._epoints.push(p.x, p.y);
  48618. }
  48619. };
  48620. PolygonMeshBuilder.prototype.addHole = function (hole) {
  48621. this._points.add(hole);
  48622. var holepoints = new PolygonPoints();
  48623. holepoints.add(hole);
  48624. this._holes.push(holepoints);
  48625. this._eholes.push(this._epoints.length / 2);
  48626. this._addToepoint(hole);
  48627. return this;
  48628. };
  48629. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  48630. var _this = this;
  48631. if (updatable === void 0) { updatable = false; }
  48632. var result = new BABYLON.Mesh(this._name, this._scene);
  48633. var normals = [];
  48634. var positions = [];
  48635. var uvs = [];
  48636. var bounds = this._points.computeBounds();
  48637. this._points.elements.forEach(function (p) {
  48638. normals.push(0, 1.0, 0);
  48639. positions.push(p.x, 0, p.y);
  48640. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  48641. });
  48642. var indices = [];
  48643. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  48644. for (var i = 0; i < res.length; i++) {
  48645. indices.push(res[i]);
  48646. }
  48647. if (depth > 0) {
  48648. var positionscount = (positions.length / 3); //get the current pointcount
  48649. this._points.elements.forEach(function (p) {
  48650. normals.push(0, -1.0, 0);
  48651. positions.push(p.x, -depth, p.y);
  48652. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  48653. });
  48654. var totalCount = indices.length;
  48655. for (var i = 0; i < totalCount; i += 3) {
  48656. var i0 = indices[i + 0];
  48657. var i1 = indices[i + 1];
  48658. var i2 = indices[i + 2];
  48659. indices.push(i2 + positionscount);
  48660. indices.push(i1 + positionscount);
  48661. indices.push(i0 + positionscount);
  48662. }
  48663. //Add the sides
  48664. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  48665. this._holes.forEach(function (hole) {
  48666. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  48667. });
  48668. }
  48669. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  48670. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  48671. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  48672. result.setIndices(indices);
  48673. return result;
  48674. };
  48675. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  48676. var StartIndex = positions.length / 3;
  48677. var ulength = 0;
  48678. for (var i = 0; i < points.elements.length; i++) {
  48679. var p = points.elements[i];
  48680. var p1;
  48681. if ((i + 1) > points.elements.length - 1) {
  48682. p1 = points.elements[0];
  48683. }
  48684. else {
  48685. p1 = points.elements[i + 1];
  48686. }
  48687. positions.push(p.x, 0, p.y);
  48688. positions.push(p.x, -depth, p.y);
  48689. positions.push(p1.x, 0, p1.y);
  48690. positions.push(p1.x, -depth, p1.y);
  48691. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  48692. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  48693. var v3 = v2.subtract(v1);
  48694. var v4 = new BABYLON.Vector3(0, 1, 0);
  48695. var vn = BABYLON.Vector3.Cross(v3, v4);
  48696. vn = vn.normalize();
  48697. uvs.push(ulength / bounds.width, 0);
  48698. uvs.push(ulength / bounds.width, 1);
  48699. ulength += v3.length();
  48700. uvs.push((ulength / bounds.width), 0);
  48701. uvs.push((ulength / bounds.width), 1);
  48702. if (!flip) {
  48703. normals.push(-vn.x, -vn.y, -vn.z);
  48704. normals.push(-vn.x, -vn.y, -vn.z);
  48705. normals.push(-vn.x, -vn.y, -vn.z);
  48706. normals.push(-vn.x, -vn.y, -vn.z);
  48707. indices.push(StartIndex);
  48708. indices.push(StartIndex + 1);
  48709. indices.push(StartIndex + 2);
  48710. indices.push(StartIndex + 1);
  48711. indices.push(StartIndex + 3);
  48712. indices.push(StartIndex + 2);
  48713. }
  48714. else {
  48715. normals.push(vn.x, vn.y, vn.z);
  48716. normals.push(vn.x, vn.y, vn.z);
  48717. normals.push(vn.x, vn.y, vn.z);
  48718. normals.push(vn.x, vn.y, vn.z);
  48719. indices.push(StartIndex);
  48720. indices.push(StartIndex + 2);
  48721. indices.push(StartIndex + 1);
  48722. indices.push(StartIndex + 1);
  48723. indices.push(StartIndex + 2);
  48724. indices.push(StartIndex + 3);
  48725. }
  48726. StartIndex += 4;
  48727. }
  48728. ;
  48729. };
  48730. return PolygonMeshBuilder;
  48731. }());
  48732. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  48733. })(BABYLON || (BABYLON = {}));
  48734. //# sourceMappingURL=babylon.polygonMesh.js.map
  48735. var BABYLON;
  48736. (function (BABYLON) {
  48737. var Octree = (function () {
  48738. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  48739. if (maxDepth === void 0) { maxDepth = 2; }
  48740. this.maxDepth = maxDepth;
  48741. this.dynamicContent = new Array();
  48742. this._maxBlockCapacity = maxBlockCapacity || 64;
  48743. this._selectionContent = new BABYLON.SmartArray(1024);
  48744. this._creationFunc = creationFunc;
  48745. }
  48746. // Methods
  48747. Octree.prototype.update = function (worldMin, worldMax, entries) {
  48748. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  48749. };
  48750. Octree.prototype.addMesh = function (entry) {
  48751. for (var index = 0; index < this.blocks.length; index++) {
  48752. var block = this.blocks[index];
  48753. block.addEntry(entry);
  48754. }
  48755. };
  48756. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  48757. this._selectionContent.reset();
  48758. for (var index = 0; index < this.blocks.length; index++) {
  48759. var block = this.blocks[index];
  48760. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  48761. }
  48762. if (allowDuplicate) {
  48763. this._selectionContent.concat(this.dynamicContent);
  48764. }
  48765. else {
  48766. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  48767. }
  48768. return this._selectionContent;
  48769. };
  48770. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  48771. this._selectionContent.reset();
  48772. for (var index = 0; index < this.blocks.length; index++) {
  48773. var block = this.blocks[index];
  48774. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  48775. }
  48776. if (allowDuplicate) {
  48777. this._selectionContent.concat(this.dynamicContent);
  48778. }
  48779. else {
  48780. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  48781. }
  48782. return this._selectionContent;
  48783. };
  48784. Octree.prototype.intersectsRay = function (ray) {
  48785. this._selectionContent.reset();
  48786. for (var index = 0; index < this.blocks.length; index++) {
  48787. var block = this.blocks[index];
  48788. block.intersectsRay(ray, this._selectionContent);
  48789. }
  48790. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  48791. return this._selectionContent;
  48792. };
  48793. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  48794. target.blocks = new Array();
  48795. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  48796. // Segmenting space
  48797. for (var x = 0; x < 2; x++) {
  48798. for (var y = 0; y < 2; y++) {
  48799. for (var z = 0; z < 2; z++) {
  48800. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  48801. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  48802. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  48803. block.addEntries(entries);
  48804. target.blocks.push(block);
  48805. }
  48806. }
  48807. }
  48808. };
  48809. return Octree;
  48810. }());
  48811. Octree.CreationFuncForMeshes = function (entry, block) {
  48812. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  48813. block.entries.push(entry);
  48814. }
  48815. };
  48816. Octree.CreationFuncForSubMeshes = function (entry, block) {
  48817. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  48818. block.entries.push(entry);
  48819. }
  48820. };
  48821. BABYLON.Octree = Octree;
  48822. })(BABYLON || (BABYLON = {}));
  48823. //# sourceMappingURL=babylon.octree.js.map
  48824. var BABYLON;
  48825. (function (BABYLON) {
  48826. var OctreeBlock = (function () {
  48827. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  48828. this.entries = new Array();
  48829. this._boundingVectors = new Array();
  48830. this._capacity = capacity;
  48831. this._depth = depth;
  48832. this._maxDepth = maxDepth;
  48833. this._creationFunc = creationFunc;
  48834. this._minPoint = minPoint;
  48835. this._maxPoint = maxPoint;
  48836. this._boundingVectors.push(minPoint.clone());
  48837. this._boundingVectors.push(maxPoint.clone());
  48838. this._boundingVectors.push(minPoint.clone());
  48839. this._boundingVectors[2].x = maxPoint.x;
  48840. this._boundingVectors.push(minPoint.clone());
  48841. this._boundingVectors[3].y = maxPoint.y;
  48842. this._boundingVectors.push(minPoint.clone());
  48843. this._boundingVectors[4].z = maxPoint.z;
  48844. this._boundingVectors.push(maxPoint.clone());
  48845. this._boundingVectors[5].z = minPoint.z;
  48846. this._boundingVectors.push(maxPoint.clone());
  48847. this._boundingVectors[6].x = minPoint.x;
  48848. this._boundingVectors.push(maxPoint.clone());
  48849. this._boundingVectors[7].y = minPoint.y;
  48850. }
  48851. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  48852. // Property
  48853. get: function () {
  48854. return this._capacity;
  48855. },
  48856. enumerable: true,
  48857. configurable: true
  48858. });
  48859. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  48860. get: function () {
  48861. return this._minPoint;
  48862. },
  48863. enumerable: true,
  48864. configurable: true
  48865. });
  48866. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  48867. get: function () {
  48868. return this._maxPoint;
  48869. },
  48870. enumerable: true,
  48871. configurable: true
  48872. });
  48873. // Methods
  48874. OctreeBlock.prototype.addEntry = function (entry) {
  48875. if (this.blocks) {
  48876. for (var index = 0; index < this.blocks.length; index++) {
  48877. var block = this.blocks[index];
  48878. block.addEntry(entry);
  48879. }
  48880. return;
  48881. }
  48882. this._creationFunc(entry, this);
  48883. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  48884. this.createInnerBlocks();
  48885. }
  48886. };
  48887. OctreeBlock.prototype.addEntries = function (entries) {
  48888. for (var index = 0; index < entries.length; index++) {
  48889. var mesh = entries[index];
  48890. this.addEntry(mesh);
  48891. }
  48892. };
  48893. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  48894. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  48895. if (this.blocks) {
  48896. for (var index = 0; index < this.blocks.length; index++) {
  48897. var block = this.blocks[index];
  48898. block.select(frustumPlanes, selection, allowDuplicate);
  48899. }
  48900. return;
  48901. }
  48902. if (allowDuplicate) {
  48903. selection.concat(this.entries);
  48904. }
  48905. else {
  48906. selection.concatWithNoDuplicate(this.entries);
  48907. }
  48908. }
  48909. };
  48910. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  48911. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  48912. if (this.blocks) {
  48913. for (var index = 0; index < this.blocks.length; index++) {
  48914. var block = this.blocks[index];
  48915. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  48916. }
  48917. return;
  48918. }
  48919. if (allowDuplicate) {
  48920. selection.concat(this.entries);
  48921. }
  48922. else {
  48923. selection.concatWithNoDuplicate(this.entries);
  48924. }
  48925. }
  48926. };
  48927. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  48928. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  48929. if (this.blocks) {
  48930. for (var index = 0; index < this.blocks.length; index++) {
  48931. var block = this.blocks[index];
  48932. block.intersectsRay(ray, selection);
  48933. }
  48934. return;
  48935. }
  48936. selection.concatWithNoDuplicate(this.entries);
  48937. }
  48938. };
  48939. OctreeBlock.prototype.createInnerBlocks = function () {
  48940. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  48941. };
  48942. return OctreeBlock;
  48943. }());
  48944. BABYLON.OctreeBlock = OctreeBlock;
  48945. })(BABYLON || (BABYLON = {}));
  48946. //# sourceMappingURL=babylon.octreeBlock.js.map
  48947. var BABYLON;
  48948. (function (BABYLON) {
  48949. var BlurPostProcess = (function (_super) {
  48950. __extends(BlurPostProcess, _super);
  48951. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  48952. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48953. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  48954. _this.direction = direction;
  48955. _this.blurWidth = blurWidth;
  48956. _this.onApplyObservable.add(function (effect) {
  48957. effect.setFloat2("screenSize", _this.width, _this.height);
  48958. effect.setVector2("direction", _this.direction);
  48959. effect.setFloat("blurWidth", _this.blurWidth);
  48960. });
  48961. return _this;
  48962. }
  48963. return BlurPostProcess;
  48964. }(BABYLON.PostProcess));
  48965. BABYLON.BlurPostProcess = BlurPostProcess;
  48966. })(BABYLON || (BABYLON = {}));
  48967. //# sourceMappingURL=babylon.blurPostProcess.js.map
  48968. var BABYLON;
  48969. (function (BABYLON) {
  48970. var RefractionPostProcess = (function (_super) {
  48971. __extends(RefractionPostProcess, _super);
  48972. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  48973. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  48974. _this.color = color;
  48975. _this.depth = depth;
  48976. _this.colorLevel = colorLevel;
  48977. _this.onActivateObservable.add(function (cam) {
  48978. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  48979. });
  48980. _this.onApplyObservable.add(function (effect) {
  48981. effect.setColor3("baseColor", _this.color);
  48982. effect.setFloat("depth", _this.depth);
  48983. effect.setFloat("colorLevel", _this.colorLevel);
  48984. effect.setTexture("refractionSampler", _this._refRexture);
  48985. });
  48986. return _this;
  48987. }
  48988. // Methods
  48989. RefractionPostProcess.prototype.dispose = function (camera) {
  48990. if (this._refRexture) {
  48991. this._refRexture.dispose();
  48992. }
  48993. _super.prototype.dispose.call(this, camera);
  48994. };
  48995. return RefractionPostProcess;
  48996. }(BABYLON.PostProcess));
  48997. BABYLON.RefractionPostProcess = RefractionPostProcess;
  48998. })(BABYLON || (BABYLON = {}));
  48999. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  49000. var BABYLON;
  49001. (function (BABYLON) {
  49002. var BlackAndWhitePostProcess = (function (_super) {
  49003. __extends(BlackAndWhitePostProcess, _super);
  49004. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  49005. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  49006. }
  49007. return BlackAndWhitePostProcess;
  49008. }(BABYLON.PostProcess));
  49009. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  49010. })(BABYLON || (BABYLON = {}));
  49011. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  49012. var BABYLON;
  49013. (function (BABYLON) {
  49014. var ConvolutionPostProcess = (function (_super) {
  49015. __extends(ConvolutionPostProcess, _super);
  49016. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  49017. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  49018. _this.kernel = kernel;
  49019. _this.onApply = function (effect) {
  49020. effect.setFloat2("screenSize", _this.width, _this.height);
  49021. effect.setArray("kernel", _this.kernel);
  49022. };
  49023. return _this;
  49024. }
  49025. return ConvolutionPostProcess;
  49026. }(BABYLON.PostProcess));
  49027. // Statics
  49028. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  49029. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  49030. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  49031. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  49032. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  49033. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  49034. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  49035. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  49036. })(BABYLON || (BABYLON = {}));
  49037. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  49038. var BABYLON;
  49039. (function (BABYLON) {
  49040. var FilterPostProcess = (function (_super) {
  49041. __extends(FilterPostProcess, _super);
  49042. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  49043. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  49044. _this.kernelMatrix = kernelMatrix;
  49045. _this.onApply = function (effect) {
  49046. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  49047. };
  49048. return _this;
  49049. }
  49050. return FilterPostProcess;
  49051. }(BABYLON.PostProcess));
  49052. BABYLON.FilterPostProcess = FilterPostProcess;
  49053. })(BABYLON || (BABYLON = {}));
  49054. //# sourceMappingURL=babylon.filterPostProcess.js.map
  49055. var BABYLON;
  49056. (function (BABYLON) {
  49057. var FxaaPostProcess = (function (_super) {
  49058. __extends(FxaaPostProcess, _super);
  49059. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  49060. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable) || this;
  49061. _this.onSizeChangedObservable.add(function () {
  49062. _this.texelWidth = 1.0 / _this.width;
  49063. _this.texelHeight = 1.0 / _this.height;
  49064. });
  49065. _this.onApplyObservable.add(function (effect) {
  49066. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  49067. });
  49068. return _this;
  49069. }
  49070. return FxaaPostProcess;
  49071. }(BABYLON.PostProcess));
  49072. BABYLON.FxaaPostProcess = FxaaPostProcess;
  49073. })(BABYLON || (BABYLON = {}));
  49074. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  49075. var BABYLON;
  49076. (function (BABYLON) {
  49077. var StereoscopicInterlacePostProcess = (function (_super) {
  49078. __extends(StereoscopicInterlacePostProcess, _super);
  49079. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  49080. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  49081. _this._passedProcess = rigCameras[0]._rigPostProcess;
  49082. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  49083. _this.onSizeChangedObservable.add(function () {
  49084. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  49085. });
  49086. _this.onApplyObservable.add(function (effect) {
  49087. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  49088. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  49089. });
  49090. return _this;
  49091. }
  49092. return StereoscopicInterlacePostProcess;
  49093. }(BABYLON.PostProcess));
  49094. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  49095. })(BABYLON || (BABYLON = {}));
  49096. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  49097. var BABYLON;
  49098. (function (BABYLON) {
  49099. var LensFlare = (function () {
  49100. function LensFlare(size, position, color, imgUrl, system) {
  49101. this.size = size;
  49102. this.position = position;
  49103. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  49104. this.dispose = function () {
  49105. if (this.texture) {
  49106. this.texture.dispose();
  49107. }
  49108. // Remove from scene
  49109. var index = this._system.lensFlares.indexOf(this);
  49110. this._system.lensFlares.splice(index, 1);
  49111. };
  49112. this.color = color || new BABYLON.Color3(1, 1, 1);
  49113. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  49114. this._system = system;
  49115. system.lensFlares.push(this);
  49116. }
  49117. return LensFlare;
  49118. }());
  49119. BABYLON.LensFlare = LensFlare;
  49120. })(BABYLON || (BABYLON = {}));
  49121. //# sourceMappingURL=babylon.lensFlare.js.map
  49122. var BABYLON;
  49123. (function (BABYLON) {
  49124. var LensFlareSystem = (function () {
  49125. function LensFlareSystem(name, emitter, scene) {
  49126. this.name = name;
  49127. this.lensFlares = new Array();
  49128. this.borderLimit = 300;
  49129. this.viewportBorder = 0;
  49130. this.layerMask = 0x0FFFFFFF;
  49131. this._vertexBuffers = {};
  49132. this._isEnabled = true;
  49133. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49134. this._emitter = emitter;
  49135. this.id = name;
  49136. scene.lensFlareSystems.push(this);
  49137. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  49138. var engine = scene.getEngine();
  49139. // VBO
  49140. var vertices = [];
  49141. vertices.push(1, 1);
  49142. vertices.push(-1, 1);
  49143. vertices.push(-1, -1);
  49144. vertices.push(1, -1);
  49145. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  49146. // Indices
  49147. var indices = [];
  49148. indices.push(0);
  49149. indices.push(1);
  49150. indices.push(2);
  49151. indices.push(0);
  49152. indices.push(2);
  49153. indices.push(3);
  49154. this._indexBuffer = engine.createIndexBuffer(indices);
  49155. // Effects
  49156. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  49157. }
  49158. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  49159. get: function () {
  49160. return this._isEnabled;
  49161. },
  49162. set: function (value) {
  49163. this._isEnabled = value;
  49164. },
  49165. enumerable: true,
  49166. configurable: true
  49167. });
  49168. LensFlareSystem.prototype.getScene = function () {
  49169. return this._scene;
  49170. };
  49171. LensFlareSystem.prototype.getEmitter = function () {
  49172. return this._emitter;
  49173. };
  49174. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  49175. this._emitter = newEmitter;
  49176. };
  49177. LensFlareSystem.prototype.getEmitterPosition = function () {
  49178. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  49179. };
  49180. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  49181. var position = this.getEmitterPosition();
  49182. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  49183. this._positionX = position.x;
  49184. this._positionY = position.y;
  49185. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  49186. if (this.viewportBorder > 0) {
  49187. globalViewport.x -= this.viewportBorder;
  49188. globalViewport.y -= this.viewportBorder;
  49189. globalViewport.width += this.viewportBorder * 2;
  49190. globalViewport.height += this.viewportBorder * 2;
  49191. position.x += this.viewportBorder;
  49192. position.y += this.viewportBorder;
  49193. this._positionX += this.viewportBorder;
  49194. this._positionY += this.viewportBorder;
  49195. }
  49196. if (position.z > 0) {
  49197. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  49198. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  49199. return true;
  49200. }
  49201. return true;
  49202. }
  49203. return false;
  49204. };
  49205. LensFlareSystem.prototype._isVisible = function () {
  49206. if (!this._isEnabled) {
  49207. return false;
  49208. }
  49209. var emitterPosition = this.getEmitterPosition();
  49210. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  49211. var distance = direction.length();
  49212. direction.normalize();
  49213. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  49214. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  49215. return !pickInfo.hit || pickInfo.distance > distance;
  49216. };
  49217. LensFlareSystem.prototype.render = function () {
  49218. if (!this._effect.isReady())
  49219. return false;
  49220. var engine = this._scene.getEngine();
  49221. var viewport = this._scene.activeCamera.viewport;
  49222. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  49223. // Position
  49224. if (!this.computeEffectivePosition(globalViewport)) {
  49225. return false;
  49226. }
  49227. // Visibility
  49228. if (!this._isVisible()) {
  49229. return false;
  49230. }
  49231. // Intensity
  49232. var awayX;
  49233. var awayY;
  49234. if (this._positionX < this.borderLimit + globalViewport.x) {
  49235. awayX = this.borderLimit + globalViewport.x - this._positionX;
  49236. }
  49237. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  49238. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  49239. }
  49240. else {
  49241. awayX = 0;
  49242. }
  49243. if (this._positionY < this.borderLimit + globalViewport.y) {
  49244. awayY = this.borderLimit + globalViewport.y - this._positionY;
  49245. }
  49246. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  49247. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  49248. }
  49249. else {
  49250. awayY = 0;
  49251. }
  49252. var away = (awayX > awayY) ? awayX : awayY;
  49253. away -= this.viewportBorder;
  49254. if (away > this.borderLimit) {
  49255. away = this.borderLimit;
  49256. }
  49257. var intensity = 1.0 - (away / this.borderLimit);
  49258. if (intensity < 0) {
  49259. return false;
  49260. }
  49261. if (intensity > 1.0) {
  49262. intensity = 1.0;
  49263. }
  49264. if (this.viewportBorder > 0) {
  49265. globalViewport.x += this.viewportBorder;
  49266. globalViewport.y += this.viewportBorder;
  49267. globalViewport.width -= this.viewportBorder * 2;
  49268. globalViewport.height -= this.viewportBorder * 2;
  49269. this._positionX -= this.viewportBorder;
  49270. this._positionY -= this.viewportBorder;
  49271. }
  49272. // Position
  49273. var centerX = globalViewport.x + globalViewport.width / 2;
  49274. var centerY = globalViewport.y + globalViewport.height / 2;
  49275. var distX = centerX - this._positionX;
  49276. var distY = centerY - this._positionY;
  49277. // Effects
  49278. engine.enableEffect(this._effect);
  49279. engine.setState(false);
  49280. engine.setDepthBuffer(false);
  49281. // VBOs
  49282. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  49283. // Flares
  49284. for (var index = 0; index < this.lensFlares.length; index++) {
  49285. var flare = this.lensFlares[index];
  49286. engine.setAlphaMode(flare.alphaMode);
  49287. var x = centerX - (distX * flare.position);
  49288. var y = centerY - (distY * flare.position);
  49289. var cw = flare.size;
  49290. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  49291. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  49292. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  49293. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  49294. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  49295. // Texture
  49296. this._effect.setTexture("textureSampler", flare.texture);
  49297. // Color
  49298. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  49299. // Draw order
  49300. engine.draw(true, 0, 6);
  49301. }
  49302. engine.setDepthBuffer(true);
  49303. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49304. return true;
  49305. };
  49306. LensFlareSystem.prototype.dispose = function () {
  49307. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  49308. if (vertexBuffer) {
  49309. vertexBuffer.dispose();
  49310. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  49311. }
  49312. if (this._indexBuffer) {
  49313. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49314. this._indexBuffer = null;
  49315. }
  49316. while (this.lensFlares.length) {
  49317. this.lensFlares[0].dispose();
  49318. }
  49319. // Remove from scene
  49320. var index = this._scene.lensFlareSystems.indexOf(this);
  49321. this._scene.lensFlareSystems.splice(index, 1);
  49322. };
  49323. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  49324. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  49325. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  49326. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  49327. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  49328. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  49329. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  49330. var parsedFlare = parsedLensFlareSystem.flares[index];
  49331. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  49332. }
  49333. return lensFlareSystem;
  49334. };
  49335. LensFlareSystem.prototype.serialize = function () {
  49336. var serializationObject = {};
  49337. serializationObject.id = this.id;
  49338. serializationObject.name = this.name;
  49339. serializationObject.emitterId = this.getEmitter().id;
  49340. serializationObject.borderLimit = this.borderLimit;
  49341. serializationObject.flares = [];
  49342. for (var index = 0; index < this.lensFlares.length; index++) {
  49343. var flare = this.lensFlares[index];
  49344. serializationObject.flares.push({
  49345. size: flare.size,
  49346. position: flare.position,
  49347. color: flare.color.asArray(),
  49348. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  49349. });
  49350. }
  49351. return serializationObject;
  49352. };
  49353. return LensFlareSystem;
  49354. }());
  49355. BABYLON.LensFlareSystem = LensFlareSystem;
  49356. })(BABYLON || (BABYLON = {}));
  49357. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  49358. /// <reference path="babylon.freeCamera.ts" />
  49359. var BABYLON;
  49360. (function (BABYLON) {
  49361. // We're mainly based on the logic defined into the FreeCamera code
  49362. var DeviceOrientationCamera = (function (_super) {
  49363. __extends(DeviceOrientationCamera, _super);
  49364. function DeviceOrientationCamera(name, position, scene) {
  49365. var _this = _super.call(this, name, position, scene) || this;
  49366. _this._quaternionCache = new BABYLON.Quaternion();
  49367. _this.inputs.addDeviceOrientation();
  49368. return _this;
  49369. }
  49370. DeviceOrientationCamera.prototype.getClassName = function () {
  49371. return "DeviceOrientationCamera";
  49372. };
  49373. DeviceOrientationCamera.prototype._checkInputs = function () {
  49374. _super.prototype._checkInputs.call(this);
  49375. this._quaternionCache.copyFrom(this.rotationQuaternion);
  49376. if (this._initialQuaternion) {
  49377. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  49378. }
  49379. };
  49380. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  49381. var _this = this;
  49382. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  49383. //can only work if this camera has a rotation quaternion already.
  49384. if (!this.rotationQuaternion)
  49385. return;
  49386. if (!this._initialQuaternion) {
  49387. this._initialQuaternion = new BABYLON.Quaternion();
  49388. }
  49389. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  49390. ['x', 'y', 'z'].forEach(function (axisName) {
  49391. if (!axis[axisName]) {
  49392. _this._initialQuaternion[axisName] = 0;
  49393. }
  49394. else {
  49395. _this._initialQuaternion[axisName] *= -1;
  49396. }
  49397. });
  49398. this._initialQuaternion.normalize();
  49399. //force rotation update
  49400. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  49401. };
  49402. return DeviceOrientationCamera;
  49403. }(BABYLON.FreeCamera));
  49404. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  49405. })(BABYLON || (BABYLON = {}));
  49406. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  49407. var BABYLON;
  49408. (function (BABYLON) {
  49409. var VRDeviceOrientationFreeCamera = (function (_super) {
  49410. __extends(VRDeviceOrientationFreeCamera, _super);
  49411. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  49412. if (compensateDistortion === void 0) { compensateDistortion = true; }
  49413. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  49414. var _this = _super.call(this, name, position, scene) || this;
  49415. vrCameraMetrics.compensateDistortion = compensateDistortion;
  49416. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  49417. return _this;
  49418. }
  49419. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  49420. return "VRDeviceOrientationFreeCamera";
  49421. };
  49422. return VRDeviceOrientationFreeCamera;
  49423. }(BABYLON.DeviceOrientationCamera));
  49424. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  49425. var VRDeviceOrientationGamepadCamera = (function (_super) {
  49426. __extends(VRDeviceOrientationGamepadCamera, _super);
  49427. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  49428. if (compensateDistortion === void 0) { compensateDistortion = true; }
  49429. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  49430. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  49431. _this.inputs.addGamepad();
  49432. return _this;
  49433. }
  49434. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  49435. return "VRDeviceOrientationGamepadCamera";
  49436. };
  49437. return VRDeviceOrientationGamepadCamera;
  49438. }(VRDeviceOrientationFreeCamera));
  49439. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  49440. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  49441. __extends(VRDeviceOrientationArcRotateCamera, _super);
  49442. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  49443. if (compensateDistortion === void 0) { compensateDistortion = true; }
  49444. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  49445. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  49446. vrCameraMetrics.compensateDistortion = compensateDistortion;
  49447. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  49448. _this.inputs.addVRDeviceOrientation();
  49449. return _this;
  49450. }
  49451. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  49452. return "VRDeviceOrientationArcRotateCamera";
  49453. };
  49454. return VRDeviceOrientationArcRotateCamera;
  49455. }(BABYLON.ArcRotateCamera));
  49456. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  49457. })(BABYLON || (BABYLON = {}));
  49458. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  49459. /// <reference path="babylon.touchCamera.ts" />
  49460. var BABYLON;
  49461. (function (BABYLON) {
  49462. // We're mainly based on the logic defined into the FreeCamera code
  49463. var UniversalCamera = (function (_super) {
  49464. __extends(UniversalCamera, _super);
  49465. //-- end properties for backward compatibility for inputs
  49466. function UniversalCamera(name, position, scene) {
  49467. var _this = _super.call(this, name, position, scene) || this;
  49468. _this.inputs.addGamepad();
  49469. return _this;
  49470. }
  49471. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  49472. //-- Begin properties for backward compatibility for inputs
  49473. get: function () {
  49474. var gamepad = this.inputs.attached["gamepad"];
  49475. if (gamepad)
  49476. return gamepad.gamepadAngularSensibility;
  49477. },
  49478. set: function (value) {
  49479. var gamepad = this.inputs.attached["gamepad"];
  49480. if (gamepad)
  49481. gamepad.gamepadAngularSensibility = value;
  49482. },
  49483. enumerable: true,
  49484. configurable: true
  49485. });
  49486. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  49487. get: function () {
  49488. var gamepad = this.inputs.attached["gamepad"];
  49489. if (gamepad)
  49490. return gamepad.gamepadMoveSensibility;
  49491. },
  49492. set: function (value) {
  49493. var gamepad = this.inputs.attached["gamepad"];
  49494. if (gamepad)
  49495. gamepad.gamepadMoveSensibility = value;
  49496. },
  49497. enumerable: true,
  49498. configurable: true
  49499. });
  49500. UniversalCamera.prototype.getClassName = function () {
  49501. return "UniversalCamera";
  49502. };
  49503. return UniversalCamera;
  49504. }(BABYLON.TouchCamera));
  49505. BABYLON.UniversalCamera = UniversalCamera;
  49506. })(BABYLON || (BABYLON = {}));
  49507. //# sourceMappingURL=babylon.universalCamera.js.map
  49508. var BABYLON;
  49509. (function (BABYLON) {
  49510. var Gamepads = (function () {
  49511. function Gamepads(ongamedpadconnected) {
  49512. var _this = this;
  49513. this.babylonGamepads = [];
  49514. this.oneGamepadConnected = false;
  49515. this.isMonitoring = false;
  49516. this.gamepadEventSupported = 'GamepadEvent' in window;
  49517. this.gamepadSupportAvailable = (navigator.getGamepads ||
  49518. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  49519. this._callbackGamepadConnected = ongamedpadconnected;
  49520. if (this.gamepadSupportAvailable) {
  49521. // Checking if the gamepad connected event is supported (like in Firefox)
  49522. if (this.gamepadEventSupported) {
  49523. this._onGamepadConnectedEvent = function (evt) {
  49524. _this._onGamepadConnected(evt);
  49525. };
  49526. this._onGamepadDisonnectedEvent = function (evt) {
  49527. _this._onGamepadDisconnected(evt);
  49528. };
  49529. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  49530. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  49531. }
  49532. else {
  49533. this._startMonitoringGamepads();
  49534. }
  49535. }
  49536. }
  49537. Gamepads.prototype.dispose = function () {
  49538. if (Gamepads.gamepadDOMInfo) {
  49539. document.body.removeChild(Gamepads.gamepadDOMInfo);
  49540. }
  49541. if (this._onGamepadConnectedEvent) {
  49542. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  49543. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  49544. this._onGamepadConnectedEvent = null;
  49545. this._onGamepadDisonnectedEvent = null;
  49546. }
  49547. };
  49548. Gamepads.prototype._onGamepadConnected = function (evt) {
  49549. var newGamepad = this._addNewGamepad(evt.gamepad);
  49550. if (this._callbackGamepadConnected)
  49551. this._callbackGamepadConnected(newGamepad);
  49552. this._startMonitoringGamepads();
  49553. };
  49554. Gamepads.prototype._addNewGamepad = function (gamepad) {
  49555. if (!this.oneGamepadConnected) {
  49556. this.oneGamepadConnected = true;
  49557. if (Gamepads.gamepadDOMInfo) {
  49558. document.body.removeChild(Gamepads.gamepadDOMInfo);
  49559. Gamepads.gamepadDOMInfo = null;
  49560. }
  49561. }
  49562. var newGamepad;
  49563. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  49564. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  49565. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  49566. }
  49567. else {
  49568. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  49569. }
  49570. this.babylonGamepads.push(newGamepad);
  49571. return newGamepad;
  49572. };
  49573. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  49574. // Remove the gamepad from the list of gamepads to monitor.
  49575. for (var i in this.babylonGamepads) {
  49576. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  49577. this.babylonGamepads.splice(+i, 1);
  49578. break;
  49579. }
  49580. }
  49581. // If no gamepads are left, stop the polling loop.
  49582. if (this.babylonGamepads.length == 0) {
  49583. this._stopMonitoringGamepads();
  49584. }
  49585. };
  49586. Gamepads.prototype._startMonitoringGamepads = function () {
  49587. if (!this.isMonitoring) {
  49588. this.isMonitoring = true;
  49589. this._checkGamepadsStatus();
  49590. }
  49591. };
  49592. Gamepads.prototype._stopMonitoringGamepads = function () {
  49593. this.isMonitoring = false;
  49594. };
  49595. Gamepads.prototype._checkGamepadsStatus = function () {
  49596. var _this = this;
  49597. // updating gamepad objects
  49598. this._updateGamepadObjects();
  49599. for (var i in this.babylonGamepads) {
  49600. this.babylonGamepads[i].update();
  49601. }
  49602. if (this.isMonitoring) {
  49603. if (window.requestAnimationFrame) {
  49604. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  49605. }
  49606. else if (window.mozRequestAnimationFrame) {
  49607. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  49608. }
  49609. else if (window.webkitRequestAnimationFrame) {
  49610. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  49611. }
  49612. }
  49613. };
  49614. // This function is called only on Chrome, which does not yet support
  49615. // connection/disconnection events, but requires you to monitor
  49616. // an array for changes.
  49617. Gamepads.prototype._updateGamepadObjects = function () {
  49618. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  49619. for (var i = 0; i < gamepads.length; i++) {
  49620. if (gamepads[i]) {
  49621. if (!(gamepads[i].index in this.babylonGamepads)) {
  49622. var newGamepad = this._addNewGamepad(gamepads[i]);
  49623. if (this._callbackGamepadConnected) {
  49624. this._callbackGamepadConnected(newGamepad);
  49625. }
  49626. }
  49627. else {
  49628. this.babylonGamepads[i].browserGamepad = gamepads[i];
  49629. }
  49630. }
  49631. }
  49632. };
  49633. return Gamepads;
  49634. }());
  49635. BABYLON.Gamepads = Gamepads;
  49636. var StickValues = (function () {
  49637. function StickValues(x, y) {
  49638. this.x = x;
  49639. this.y = y;
  49640. }
  49641. return StickValues;
  49642. }());
  49643. BABYLON.StickValues = StickValues;
  49644. var Gamepad = (function () {
  49645. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  49646. if (leftStickX === void 0) { leftStickX = 0; }
  49647. if (leftStickY === void 0) { leftStickY = 1; }
  49648. if (rightStickX === void 0) { rightStickX = 2; }
  49649. if (rightStickY === void 0) { rightStickY = 3; }
  49650. this.id = id;
  49651. this.index = index;
  49652. this.browserGamepad = browserGamepad;
  49653. this._leftStickAxisX = leftStickX;
  49654. this._leftStickAxisY = leftStickY;
  49655. this._rightStickAxisX = rightStickX;
  49656. this._rightStickAxisY = rightStickY;
  49657. if (this.browserGamepad.axes.length >= 2) {
  49658. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  49659. }
  49660. if (this.browserGamepad.axes.length >= 4) {
  49661. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  49662. }
  49663. }
  49664. Gamepad.prototype.onleftstickchanged = function (callback) {
  49665. this._onleftstickchanged = callback;
  49666. };
  49667. Gamepad.prototype.onrightstickchanged = function (callback) {
  49668. this._onrightstickchanged = callback;
  49669. };
  49670. Object.defineProperty(Gamepad.prototype, "leftStick", {
  49671. get: function () {
  49672. return this._leftStick;
  49673. },
  49674. set: function (newValues) {
  49675. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  49676. this._onleftstickchanged(newValues);
  49677. }
  49678. this._leftStick = newValues;
  49679. },
  49680. enumerable: true,
  49681. configurable: true
  49682. });
  49683. Object.defineProperty(Gamepad.prototype, "rightStick", {
  49684. get: function () {
  49685. return this._rightStick;
  49686. },
  49687. set: function (newValues) {
  49688. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  49689. this._onrightstickchanged(newValues);
  49690. }
  49691. this._rightStick = newValues;
  49692. },
  49693. enumerable: true,
  49694. configurable: true
  49695. });
  49696. Gamepad.prototype.update = function () {
  49697. if (this._leftStick) {
  49698. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  49699. }
  49700. if (this._rightStick) {
  49701. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  49702. }
  49703. };
  49704. return Gamepad;
  49705. }());
  49706. BABYLON.Gamepad = Gamepad;
  49707. var GenericPad = (function (_super) {
  49708. __extends(GenericPad, _super);
  49709. function GenericPad(id, index, gamepad) {
  49710. var _this = _super.call(this, id, index, gamepad) || this;
  49711. _this.id = id;
  49712. _this.index = index;
  49713. _this.gamepad = gamepad;
  49714. _this._buttons = new Array(gamepad.buttons.length);
  49715. return _this;
  49716. }
  49717. GenericPad.prototype.onbuttondown = function (callback) {
  49718. this._onbuttondown = callback;
  49719. };
  49720. GenericPad.prototype.onbuttonup = function (callback) {
  49721. this._onbuttonup = callback;
  49722. };
  49723. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  49724. if (newValue !== currentValue) {
  49725. if (this._onbuttondown && newValue === 1) {
  49726. this._onbuttondown(buttonIndex);
  49727. }
  49728. if (this._onbuttonup && newValue === 0) {
  49729. this._onbuttonup(buttonIndex);
  49730. }
  49731. }
  49732. return newValue;
  49733. };
  49734. GenericPad.prototype.update = function () {
  49735. _super.prototype.update.call(this);
  49736. for (var index = 0; index < this._buttons.length; index++) {
  49737. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  49738. }
  49739. };
  49740. return GenericPad;
  49741. }(Gamepad));
  49742. BABYLON.GenericPad = GenericPad;
  49743. var Xbox360Button;
  49744. (function (Xbox360Button) {
  49745. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  49746. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  49747. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  49748. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  49749. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  49750. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  49751. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  49752. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  49753. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  49754. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  49755. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  49756. var Xbox360Dpad;
  49757. (function (Xbox360Dpad) {
  49758. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  49759. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  49760. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  49761. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  49762. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  49763. var Xbox360Pad = (function (_super) {
  49764. __extends(Xbox360Pad, _super);
  49765. function Xbox360Pad(id, index, gamepad, xboxOne) {
  49766. if (xboxOne === void 0) { xboxOne = false; }
  49767. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  49768. _this._leftTrigger = 0;
  49769. _this._rightTrigger = 0;
  49770. _this._buttonA = 0;
  49771. _this._buttonB = 0;
  49772. _this._buttonX = 0;
  49773. _this._buttonY = 0;
  49774. _this._buttonBack = 0;
  49775. _this._buttonStart = 0;
  49776. _this._buttonLB = 0;
  49777. _this._buttonRB = 0;
  49778. _this._buttonLeftStick = 0;
  49779. _this._buttonRightStick = 0;
  49780. _this._dPadUp = 0;
  49781. _this._dPadDown = 0;
  49782. _this._dPadLeft = 0;
  49783. _this._dPadRight = 0;
  49784. _this._isXboxOnePad = false;
  49785. _this._isXboxOnePad = xboxOne;
  49786. return _this;
  49787. }
  49788. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  49789. this._onlefttriggerchanged = callback;
  49790. };
  49791. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  49792. this._onrighttriggerchanged = callback;
  49793. };
  49794. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  49795. get: function () {
  49796. return this._leftTrigger;
  49797. },
  49798. set: function (newValue) {
  49799. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  49800. this._onlefttriggerchanged(newValue);
  49801. }
  49802. this._leftTrigger = newValue;
  49803. },
  49804. enumerable: true,
  49805. configurable: true
  49806. });
  49807. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  49808. get: function () {
  49809. return this._rightTrigger;
  49810. },
  49811. set: function (newValue) {
  49812. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  49813. this._onrighttriggerchanged(newValue);
  49814. }
  49815. this._rightTrigger = newValue;
  49816. },
  49817. enumerable: true,
  49818. configurable: true
  49819. });
  49820. Xbox360Pad.prototype.onbuttondown = function (callback) {
  49821. this._onbuttondown = callback;
  49822. };
  49823. Xbox360Pad.prototype.onbuttonup = function (callback) {
  49824. this._onbuttonup = callback;
  49825. };
  49826. Xbox360Pad.prototype.ondpaddown = function (callback) {
  49827. this._ondpaddown = callback;
  49828. };
  49829. Xbox360Pad.prototype.ondpadup = function (callback) {
  49830. this._ondpadup = callback;
  49831. };
  49832. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  49833. if (newValue !== currentValue) {
  49834. if (this._onbuttondown && newValue === 1) {
  49835. this._onbuttondown(buttonType);
  49836. }
  49837. if (this._onbuttonup && newValue === 0) {
  49838. this._onbuttonup(buttonType);
  49839. }
  49840. }
  49841. return newValue;
  49842. };
  49843. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  49844. if (newValue !== currentValue) {
  49845. if (this._ondpaddown && newValue === 1) {
  49846. this._ondpaddown(buttonType);
  49847. }
  49848. if (this._ondpadup && newValue === 0) {
  49849. this._ondpadup(buttonType);
  49850. }
  49851. }
  49852. return newValue;
  49853. };
  49854. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  49855. get: function () {
  49856. return this._buttonA;
  49857. },
  49858. set: function (value) {
  49859. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  49860. },
  49861. enumerable: true,
  49862. configurable: true
  49863. });
  49864. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  49865. get: function () {
  49866. return this._buttonB;
  49867. },
  49868. set: function (value) {
  49869. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  49870. },
  49871. enumerable: true,
  49872. configurable: true
  49873. });
  49874. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  49875. get: function () {
  49876. return this._buttonX;
  49877. },
  49878. set: function (value) {
  49879. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  49880. },
  49881. enumerable: true,
  49882. configurable: true
  49883. });
  49884. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  49885. get: function () {
  49886. return this._buttonY;
  49887. },
  49888. set: function (value) {
  49889. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  49890. },
  49891. enumerable: true,
  49892. configurable: true
  49893. });
  49894. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  49895. get: function () {
  49896. return this._buttonStart;
  49897. },
  49898. set: function (value) {
  49899. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  49900. },
  49901. enumerable: true,
  49902. configurable: true
  49903. });
  49904. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  49905. get: function () {
  49906. return this._buttonBack;
  49907. },
  49908. set: function (value) {
  49909. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  49910. },
  49911. enumerable: true,
  49912. configurable: true
  49913. });
  49914. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  49915. get: function () {
  49916. return this._buttonLB;
  49917. },
  49918. set: function (value) {
  49919. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  49920. },
  49921. enumerable: true,
  49922. configurable: true
  49923. });
  49924. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  49925. get: function () {
  49926. return this._buttonRB;
  49927. },
  49928. set: function (value) {
  49929. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  49930. },
  49931. enumerable: true,
  49932. configurable: true
  49933. });
  49934. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  49935. get: function () {
  49936. return this._buttonLeftStick;
  49937. },
  49938. set: function (value) {
  49939. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  49940. },
  49941. enumerable: true,
  49942. configurable: true
  49943. });
  49944. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  49945. get: function () {
  49946. return this._buttonRightStick;
  49947. },
  49948. set: function (value) {
  49949. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  49950. },
  49951. enumerable: true,
  49952. configurable: true
  49953. });
  49954. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  49955. get: function () {
  49956. return this._dPadUp;
  49957. },
  49958. set: function (value) {
  49959. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  49960. },
  49961. enumerable: true,
  49962. configurable: true
  49963. });
  49964. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  49965. get: function () {
  49966. return this._dPadDown;
  49967. },
  49968. set: function (value) {
  49969. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  49970. },
  49971. enumerable: true,
  49972. configurable: true
  49973. });
  49974. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  49975. get: function () {
  49976. return this._dPadLeft;
  49977. },
  49978. set: function (value) {
  49979. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  49980. },
  49981. enumerable: true,
  49982. configurable: true
  49983. });
  49984. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  49985. get: function () {
  49986. return this._dPadRight;
  49987. },
  49988. set: function (value) {
  49989. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  49990. },
  49991. enumerable: true,
  49992. configurable: true
  49993. });
  49994. Xbox360Pad.prototype.update = function () {
  49995. _super.prototype.update.call(this);
  49996. if (this._isXboxOnePad) {
  49997. this.buttonA = this.browserGamepad.buttons[0].value;
  49998. this.buttonB = this.browserGamepad.buttons[1].value;
  49999. this.buttonX = this.browserGamepad.buttons[2].value;
  50000. this.buttonY = this.browserGamepad.buttons[3].value;
  50001. this.buttonLB = this.browserGamepad.buttons[4].value;
  50002. this.buttonRB = this.browserGamepad.buttons[5].value;
  50003. this.leftTrigger = this.browserGamepad.axes[2];
  50004. this.rightTrigger = this.browserGamepad.axes[5];
  50005. this.buttonBack = this.browserGamepad.buttons[9].value;
  50006. this.buttonStart = this.browserGamepad.buttons[8].value;
  50007. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  50008. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  50009. this.dPadUp = this.browserGamepad.buttons[11].value;
  50010. this.dPadDown = this.browserGamepad.buttons[12].value;
  50011. this.dPadLeft = this.browserGamepad.buttons[13].value;
  50012. this.dPadRight = this.browserGamepad.buttons[14].value;
  50013. }
  50014. else {
  50015. this.buttonA = this.browserGamepad.buttons[0].value;
  50016. this.buttonB = this.browserGamepad.buttons[1].value;
  50017. this.buttonX = this.browserGamepad.buttons[2].value;
  50018. this.buttonY = this.browserGamepad.buttons[3].value;
  50019. this.buttonLB = this.browserGamepad.buttons[4].value;
  50020. this.buttonRB = this.browserGamepad.buttons[5].value;
  50021. this.leftTrigger = this.browserGamepad.buttons[6].value;
  50022. this.rightTrigger = this.browserGamepad.buttons[7].value;
  50023. this.buttonBack = this.browserGamepad.buttons[8].value;
  50024. this.buttonStart = this.browserGamepad.buttons[9].value;
  50025. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  50026. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  50027. this.dPadUp = this.browserGamepad.buttons[12].value;
  50028. this.dPadDown = this.browserGamepad.buttons[13].value;
  50029. this.dPadLeft = this.browserGamepad.buttons[14].value;
  50030. this.dPadRight = this.browserGamepad.buttons[15].value;
  50031. }
  50032. };
  50033. return Xbox360Pad;
  50034. }(Gamepad));
  50035. BABYLON.Xbox360Pad = Xbox360Pad;
  50036. })(BABYLON || (BABYLON = {}));
  50037. //# sourceMappingURL=babylon.gamepads.js.map
  50038. /// <reference path="babylon.universalCamera.ts" />
  50039. var BABYLON;
  50040. (function (BABYLON) {
  50041. // We're mainly based on the logic defined into the FreeCamera code
  50042. var GamepadCamera = (function (_super) {
  50043. __extends(GamepadCamera, _super);
  50044. //-- end properties for backward compatibility for inputs
  50045. function GamepadCamera(name, position, scene) {
  50046. var _this = this;
  50047. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  50048. _this = _super.call(this, name, position, scene) || this;
  50049. return _this;
  50050. }
  50051. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  50052. //-- Begin properties for backward compatibility for inputs
  50053. get: function () {
  50054. var gamepad = this.inputs.attached["gamepad"];
  50055. if (gamepad)
  50056. return gamepad.gamepadAngularSensibility;
  50057. },
  50058. set: function (value) {
  50059. var gamepad = this.inputs.attached["gamepad"];
  50060. if (gamepad)
  50061. gamepad.gamepadAngularSensibility = value;
  50062. },
  50063. enumerable: true,
  50064. configurable: true
  50065. });
  50066. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  50067. get: function () {
  50068. var gamepad = this.inputs.attached["gamepad"];
  50069. if (gamepad)
  50070. return gamepad.gamepadMoveSensibility;
  50071. },
  50072. set: function (value) {
  50073. var gamepad = this.inputs.attached["gamepad"];
  50074. if (gamepad)
  50075. gamepad.gamepadMoveSensibility = value;
  50076. },
  50077. enumerable: true,
  50078. configurable: true
  50079. });
  50080. GamepadCamera.prototype.getClassName = function () {
  50081. return "GamepadCamera";
  50082. };
  50083. return GamepadCamera;
  50084. }(BABYLON.UniversalCamera));
  50085. BABYLON.GamepadCamera = GamepadCamera;
  50086. })(BABYLON || (BABYLON = {}));
  50087. //# sourceMappingURL=babylon.gamepadCamera.js.map
  50088. var BABYLON;
  50089. (function (BABYLON) {
  50090. var Analyser = (function () {
  50091. function Analyser(scene) {
  50092. this.SMOOTHING = 0.75;
  50093. this.FFT_SIZE = 512;
  50094. this.BARGRAPHAMPLITUDE = 256;
  50095. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  50096. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  50097. this._scene = scene;
  50098. this._audioEngine = BABYLON.Engine.audioEngine;
  50099. if (this._audioEngine.canUseWebAudio) {
  50100. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  50101. this._webAudioAnalyser.minDecibels = -140;
  50102. this._webAudioAnalyser.maxDecibels = 0;
  50103. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  50104. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  50105. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  50106. }
  50107. }
  50108. Analyser.prototype.getFrequencyBinCount = function () {
  50109. if (this._audioEngine.canUseWebAudio) {
  50110. return this._webAudioAnalyser.frequencyBinCount;
  50111. }
  50112. else {
  50113. return 0;
  50114. }
  50115. };
  50116. Analyser.prototype.getByteFrequencyData = function () {
  50117. if (this._audioEngine.canUseWebAudio) {
  50118. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50119. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50120. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  50121. }
  50122. return this._byteFreqs;
  50123. };
  50124. Analyser.prototype.getByteTimeDomainData = function () {
  50125. if (this._audioEngine.canUseWebAudio) {
  50126. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50127. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50128. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  50129. }
  50130. return this._byteTime;
  50131. };
  50132. Analyser.prototype.getFloatFrequencyData = function () {
  50133. if (this._audioEngine.canUseWebAudio) {
  50134. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50135. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50136. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  50137. }
  50138. return this._floatFreqs;
  50139. };
  50140. Analyser.prototype.drawDebugCanvas = function () {
  50141. var _this = this;
  50142. if (this._audioEngine.canUseWebAudio) {
  50143. if (!this._debugCanvas) {
  50144. this._debugCanvas = document.createElement("canvas");
  50145. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  50146. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  50147. this._debugCanvas.style.position = "absolute";
  50148. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  50149. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  50150. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  50151. document.body.appendChild(this._debugCanvas);
  50152. this._registerFunc = function () {
  50153. _this.drawDebugCanvas();
  50154. };
  50155. this._scene.registerBeforeRender(this._registerFunc);
  50156. }
  50157. if (this._registerFunc) {
  50158. var workingArray = this.getByteFrequencyData();
  50159. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  50160. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  50161. // Draw the frequency domain chart.
  50162. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  50163. var value = workingArray[i];
  50164. var percent = value / this.BARGRAPHAMPLITUDE;
  50165. var height = this.DEBUGCANVASSIZE.height * percent;
  50166. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  50167. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  50168. var hue = i / this.getFrequencyBinCount() * 360;
  50169. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  50170. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  50171. }
  50172. }
  50173. }
  50174. };
  50175. Analyser.prototype.stopDebugCanvas = function () {
  50176. if (this._debugCanvas) {
  50177. this._scene.unregisterBeforeRender(this._registerFunc);
  50178. this._registerFunc = null;
  50179. document.body.removeChild(this._debugCanvas);
  50180. this._debugCanvas = null;
  50181. this._debugCanvasContext = null;
  50182. }
  50183. };
  50184. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  50185. if (this._audioEngine.canUseWebAudio) {
  50186. inputAudioNode.connect(this._webAudioAnalyser);
  50187. this._webAudioAnalyser.connect(outputAudioNode);
  50188. }
  50189. };
  50190. Analyser.prototype.dispose = function () {
  50191. if (this._audioEngine.canUseWebAudio) {
  50192. this._webAudioAnalyser.disconnect();
  50193. }
  50194. };
  50195. return Analyser;
  50196. }());
  50197. BABYLON.Analyser = Analyser;
  50198. })(BABYLON || (BABYLON = {}));
  50199. //# sourceMappingURL=babylon.analyser.js.map
  50200. var BABYLON;
  50201. (function (BABYLON) {
  50202. var DepthRenderer = (function () {
  50203. function DepthRenderer(scene, type) {
  50204. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  50205. var _this = this;
  50206. this._viewMatrix = BABYLON.Matrix.Zero();
  50207. this._projectionMatrix = BABYLON.Matrix.Zero();
  50208. this._transformMatrix = BABYLON.Matrix.Zero();
  50209. this._worldViewProjection = BABYLON.Matrix.Zero();
  50210. this._scene = scene;
  50211. var engine = scene.getEngine();
  50212. // Render target
  50213. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  50214. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50215. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50216. this._depthMap.refreshRate = 1;
  50217. this._depthMap.renderParticles = false;
  50218. this._depthMap.renderList = null;
  50219. // set default depth value to 1.0 (far away)
  50220. this._depthMap.onClearObservable.add(function (engine) {
  50221. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  50222. });
  50223. // Custom render function
  50224. var renderSubMesh = function (subMesh) {
  50225. var mesh = subMesh.getRenderingMesh();
  50226. var scene = _this._scene;
  50227. var engine = scene.getEngine();
  50228. // Culling
  50229. engine.setState(subMesh.getMaterial().backFaceCulling);
  50230. // Managing instances
  50231. var batch = mesh._getInstancesRenderList(subMesh._id);
  50232. if (batch.mustReturn) {
  50233. return;
  50234. }
  50235. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  50236. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  50237. engine.enableEffect(_this._effect);
  50238. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  50239. var material = subMesh.getMaterial();
  50240. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  50241. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  50242. // Alpha test
  50243. if (material && material.needAlphaTesting()) {
  50244. var alphaTexture = material.getAlphaTestTexture();
  50245. _this._effect.setTexture("diffuseSampler", alphaTexture);
  50246. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50247. }
  50248. // Bones
  50249. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50250. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50251. }
  50252. // Draw
  50253. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  50254. }
  50255. };
  50256. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  50257. var index;
  50258. for (index = 0; index < opaqueSubMeshes.length; index++) {
  50259. renderSubMesh(opaqueSubMeshes.data[index]);
  50260. }
  50261. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  50262. renderSubMesh(alphaTestSubMeshes.data[index]);
  50263. }
  50264. };
  50265. }
  50266. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  50267. var material = subMesh.getMaterial();
  50268. if (material.disableDepthWrite) {
  50269. return false;
  50270. }
  50271. var defines = [];
  50272. var attribs = [BABYLON.VertexBuffer.PositionKind];
  50273. var mesh = subMesh.getMesh();
  50274. var scene = mesh.getScene();
  50275. // Alpha test
  50276. if (material && material.needAlphaTesting()) {
  50277. defines.push("#define ALPHATEST");
  50278. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50279. attribs.push(BABYLON.VertexBuffer.UVKind);
  50280. defines.push("#define UV1");
  50281. }
  50282. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50283. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50284. defines.push("#define UV2");
  50285. }
  50286. }
  50287. // Bones
  50288. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50289. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50290. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50291. if (mesh.numBoneInfluencers > 4) {
  50292. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50293. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50294. }
  50295. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50296. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50297. }
  50298. else {
  50299. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50300. }
  50301. // Instances
  50302. if (useInstances) {
  50303. defines.push("#define INSTANCES");
  50304. attribs.push("world0");
  50305. attribs.push("world1");
  50306. attribs.push("world2");
  50307. attribs.push("world3");
  50308. }
  50309. // Get correct effect
  50310. var join = defines.join("\n");
  50311. if (this._cachedDefines !== join) {
  50312. this._cachedDefines = join;
  50313. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  50314. }
  50315. return this._effect.isReady();
  50316. };
  50317. DepthRenderer.prototype.getDepthMap = function () {
  50318. return this._depthMap;
  50319. };
  50320. // Methods
  50321. DepthRenderer.prototype.dispose = function () {
  50322. this._depthMap.dispose();
  50323. };
  50324. return DepthRenderer;
  50325. }());
  50326. BABYLON.DepthRenderer = DepthRenderer;
  50327. })(BABYLON || (BABYLON = {}));
  50328. //# sourceMappingURL=babylon.depthRenderer.js.map
  50329. var BABYLON;
  50330. (function (BABYLON) {
  50331. var SSAORenderingPipeline = (function (_super) {
  50332. __extends(SSAORenderingPipeline, _super);
  50333. /**
  50334. * @constructor
  50335. * @param {string} name - The rendering pipeline name
  50336. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50337. * @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 }
  50338. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50339. */
  50340. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  50341. var _this = _super.call(this, scene.getEngine(), name) || this;
  50342. // Members
  50343. /**
  50344. * The PassPostProcess id in the pipeline that contains the original scene color
  50345. * @type {string}
  50346. */
  50347. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  50348. /**
  50349. * The SSAO PostProcess id in the pipeline
  50350. * @type {string}
  50351. */
  50352. _this.SSAORenderEffect = "SSAORenderEffect";
  50353. /**
  50354. * The horizontal blur PostProcess id in the pipeline
  50355. * @type {string}
  50356. */
  50357. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  50358. /**
  50359. * The vertical blur PostProcess id in the pipeline
  50360. * @type {string}
  50361. */
  50362. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  50363. /**
  50364. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  50365. * @type {string}
  50366. */
  50367. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  50368. /**
  50369. * The output strength of the SSAO post-process. Default value is 1.0.
  50370. * @type {number}
  50371. */
  50372. _this.totalStrength = 1.0;
  50373. /**
  50374. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  50375. * @type {number}
  50376. */
  50377. _this.radius = 0.0001;
  50378. /**
  50379. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  50380. * Must not be equal to fallOff and superior to fallOff.
  50381. * Default value is 0.975
  50382. * @type {number}
  50383. */
  50384. _this.area = 0.0075;
  50385. /**
  50386. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  50387. * Must not be equal to area and inferior to area.
  50388. * Default value is 0.0
  50389. * @type {number}
  50390. */
  50391. _this.fallOff = 0.000001;
  50392. /**
  50393. * The base color of the SSAO post-process
  50394. * The final result is "base + ssao" between [0, 1]
  50395. * @type {number}
  50396. */
  50397. _this.base = 0.5;
  50398. _this._firstUpdate = true;
  50399. _this._scene = scene;
  50400. // Set up assets
  50401. _this._createRandomTexture();
  50402. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  50403. var ssaoRatio = ratio.ssaoRatio || ratio;
  50404. var combineRatio = ratio.combineRatio || ratio;
  50405. _this._ratio = {
  50406. ssaoRatio: ssaoRatio,
  50407. combineRatio: combineRatio
  50408. };
  50409. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  50410. _this._createSSAOPostProcess(ssaoRatio);
  50411. _this._createBlurPostProcess(ssaoRatio);
  50412. _this._createSSAOCombinePostProcess(combineRatio);
  50413. // Set up pipeline
  50414. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  50415. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  50416. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  50417. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  50418. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  50419. // Finish
  50420. scene.postProcessRenderPipelineManager.addPipeline(_this);
  50421. if (cameras)
  50422. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  50423. return _this;
  50424. }
  50425. // Public Methods
  50426. /**
  50427. * Returns the horizontal blur PostProcess
  50428. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  50429. */
  50430. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  50431. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  50432. return null;
  50433. };
  50434. /**
  50435. * Returns the vertical blur PostProcess
  50436. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  50437. */
  50438. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  50439. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  50440. return null;
  50441. };
  50442. /**
  50443. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  50444. */
  50445. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  50446. if (disableDepthRender === void 0) { disableDepthRender = false; }
  50447. for (var i = 0; i < this._scene.cameras.length; i++) {
  50448. var camera = this._scene.cameras[i];
  50449. this._originalColorPostProcess.dispose(camera);
  50450. this._ssaoPostProcess.dispose(camera);
  50451. this._blurHPostProcess.dispose(camera);
  50452. this._blurVPostProcess.dispose(camera);
  50453. this._ssaoCombinePostProcess.dispose(camera);
  50454. }
  50455. this._randomTexture.dispose();
  50456. if (disableDepthRender)
  50457. this._scene.disableDepthRenderer();
  50458. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  50459. _super.prototype.dispose.call(this);
  50460. };
  50461. // Private Methods
  50462. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  50463. var _this = this;
  50464. /*
  50465. var samplerOffsets = [
  50466. -8.0, -6.0, -4.0, -2.0,
  50467. 0.0,
  50468. 2.0, 4.0, 6.0, 8.0
  50469. ];
  50470. */
  50471. var samples = 16;
  50472. var samplerOffsets = [];
  50473. for (var i = -8; i < 8; i++) {
  50474. samplerOffsets.push(i * 2);
  50475. }
  50476. 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");
  50477. this._blurHPostProcess.onApply = function (effect) {
  50478. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  50479. effect.setTexture("depthSampler", _this._depthTexture);
  50480. if (_this._firstUpdate) {
  50481. effect.setArray("samplerOffsets", samplerOffsets);
  50482. }
  50483. };
  50484. 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");
  50485. this._blurVPostProcess.onApply = function (effect) {
  50486. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  50487. effect.setTexture("depthSampler", _this._depthTexture);
  50488. if (_this._firstUpdate) {
  50489. effect.setArray("samplerOffsets", samplerOffsets);
  50490. _this._firstUpdate = false;
  50491. }
  50492. };
  50493. };
  50494. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  50495. var _this = this;
  50496. var numSamples = 16;
  50497. var sampleSphere = [
  50498. 0.5381, 0.1856, -0.4319,
  50499. 0.1379, 0.2486, 0.4430,
  50500. 0.3371, 0.5679, -0.0057,
  50501. -0.6999, -0.0451, -0.0019,
  50502. 0.0689, -0.1598, -0.8547,
  50503. 0.0560, 0.0069, -0.1843,
  50504. -0.0146, 0.1402, 0.0762,
  50505. 0.0100, -0.1924, -0.0344,
  50506. -0.3577, -0.5301, -0.4358,
  50507. -0.3169, 0.1063, 0.0158,
  50508. 0.0103, -0.5869, 0.0046,
  50509. -0.0897, -0.4940, 0.3287,
  50510. 0.7119, -0.0154, -0.0918,
  50511. -0.0533, 0.0596, -0.5411,
  50512. 0.0352, -0.0631, 0.5460,
  50513. -0.4776, 0.2847, -0.0271
  50514. ];
  50515. var samplesFactor = 1.0 / numSamples;
  50516. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  50517. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  50518. "area", "fallOff", "base", "range", "viewport"
  50519. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  50520. var viewport = new BABYLON.Vector2(0, 0);
  50521. this._ssaoPostProcess.onApply = function (effect) {
  50522. if (_this._firstUpdate) {
  50523. effect.setArray3("sampleSphere", sampleSphere);
  50524. effect.setFloat("samplesFactor", samplesFactor);
  50525. effect.setFloat("randTextureTiles", 4.0);
  50526. }
  50527. effect.setFloat("totalStrength", _this.totalStrength);
  50528. effect.setFloat("radius", _this.radius);
  50529. effect.setFloat("area", _this.area);
  50530. effect.setFloat("fallOff", _this.fallOff);
  50531. effect.setFloat("base", _this.base);
  50532. effect.setTexture("textureSampler", _this._depthTexture);
  50533. effect.setTexture("randomSampler", _this._randomTexture);
  50534. };
  50535. };
  50536. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  50537. var _this = this;
  50538. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  50539. this._ssaoCombinePostProcess.onApply = function (effect) {
  50540. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  50541. };
  50542. };
  50543. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  50544. var size = 512;
  50545. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  50546. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50547. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50548. var context = this._randomTexture.getContext();
  50549. var rand = function (min, max) {
  50550. return Math.random() * (max - min) + min;
  50551. };
  50552. var randVector = BABYLON.Vector3.Zero();
  50553. for (var x = 0; x < size; x++) {
  50554. for (var y = 0; y < size; y++) {
  50555. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  50556. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  50557. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  50558. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  50559. context.fillRect(x, y, 1, 1);
  50560. }
  50561. }
  50562. this._randomTexture.update(false);
  50563. };
  50564. return SSAORenderingPipeline;
  50565. }(BABYLON.PostProcessRenderPipeline));
  50566. __decorate([
  50567. BABYLON.serialize()
  50568. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  50569. __decorate([
  50570. BABYLON.serialize()
  50571. ], SSAORenderingPipeline.prototype, "radius", void 0);
  50572. __decorate([
  50573. BABYLON.serialize()
  50574. ], SSAORenderingPipeline.prototype, "area", void 0);
  50575. __decorate([
  50576. BABYLON.serialize()
  50577. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  50578. __decorate([
  50579. BABYLON.serialize()
  50580. ], SSAORenderingPipeline.prototype, "base", void 0);
  50581. __decorate([
  50582. BABYLON.serialize()
  50583. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  50584. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  50585. })(BABYLON || (BABYLON = {}));
  50586. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  50587. var BABYLON;
  50588. (function (BABYLON) {
  50589. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  50590. var VolumetricLightScatteringPostProcess = (function (_super) {
  50591. __extends(VolumetricLightScatteringPostProcess, _super);
  50592. /**
  50593. * @constructor
  50594. * @param {string} name - The post-process name
  50595. * @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)
  50596. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  50597. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  50598. * @param {number} samples - The post-process quality, default 100
  50599. * @param {number} samplingMode - The post-process filtering mode
  50600. * @param {BABYLON.Engine} engine - The babylon engine
  50601. * @param {boolean} reusable - If the post-process is reusable
  50602. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  50603. */
  50604. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  50605. if (samples === void 0) { samples = 100; }
  50606. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50607. 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;
  50608. _this._screenCoordinates = BABYLON.Vector2.Zero();
  50609. /**
  50610. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  50611. * @type {Vector3}
  50612. */
  50613. _this.customMeshPosition = BABYLON.Vector3.Zero();
  50614. /**
  50615. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  50616. * @type {boolean}
  50617. */
  50618. _this.useCustomMeshPosition = false;
  50619. /**
  50620. * If the post-process should inverse the light scattering direction
  50621. * @type {boolean}
  50622. */
  50623. _this.invert = true;
  50624. /**
  50625. * Array containing the excluded meshes not rendered in the internal pass
  50626. */
  50627. _this.excludedMeshes = new Array();
  50628. /**
  50629. * Controls the overall intensity of the post-process
  50630. * @type {number}
  50631. */
  50632. _this.exposure = 0.3;
  50633. /**
  50634. * Dissipates each sample's contribution in range [0, 1]
  50635. * @type {number}
  50636. */
  50637. _this.decay = 0.96815;
  50638. /**
  50639. * Controls the overall intensity of each sample
  50640. * @type {number}
  50641. */
  50642. _this.weight = 0.58767;
  50643. /**
  50644. * Controls the density of each sample
  50645. * @type {number}
  50646. */
  50647. _this.density = 0.926;
  50648. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  50649. var engine = scene.getEngine();
  50650. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  50651. // Configure mesh
  50652. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  50653. // Configure
  50654. _this._createPass(scene, ratio.passRatio || ratio);
  50655. _this.onActivate = function (camera) {
  50656. if (!_this.isSupported) {
  50657. _this.dispose(camera);
  50658. }
  50659. _this.onActivate = null;
  50660. };
  50661. _this.onApplyObservable.add(function (effect) {
  50662. _this._updateMeshScreenCoordinates(scene);
  50663. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  50664. effect.setFloat("exposure", _this.exposure);
  50665. effect.setFloat("decay", _this.decay);
  50666. effect.setFloat("weight", _this.weight);
  50667. effect.setFloat("density", _this.density);
  50668. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  50669. });
  50670. return _this;
  50671. }
  50672. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  50673. get: function () {
  50674. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  50675. return false;
  50676. },
  50677. set: function (useDiffuseColor) {
  50678. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  50679. },
  50680. enumerable: true,
  50681. configurable: true
  50682. });
  50683. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  50684. var mesh = subMesh.getMesh();
  50685. // Render this.mesh as default
  50686. if (mesh === this.mesh) {
  50687. return mesh.material.isReady(mesh);
  50688. }
  50689. var defines = [];
  50690. var attribs = [BABYLON.VertexBuffer.PositionKind];
  50691. var material = subMesh.getMaterial();
  50692. var needUV = false;
  50693. // Alpha test
  50694. if (material) {
  50695. if (material.needAlphaTesting()) {
  50696. defines.push("#define ALPHATEST");
  50697. }
  50698. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50699. attribs.push(BABYLON.VertexBuffer.UVKind);
  50700. defines.push("#define UV1");
  50701. }
  50702. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50703. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50704. defines.push("#define UV2");
  50705. }
  50706. }
  50707. // Bones
  50708. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50709. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50710. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50711. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50712. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50713. }
  50714. else {
  50715. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50716. }
  50717. // Instances
  50718. if (useInstances) {
  50719. defines.push("#define INSTANCES");
  50720. attribs.push("world0");
  50721. attribs.push("world1");
  50722. attribs.push("world2");
  50723. attribs.push("world3");
  50724. }
  50725. // Get correct effect
  50726. var join = defines.join("\n");
  50727. if (this._cachedDefines !== join) {
  50728. this._cachedDefines = join;
  50729. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  50730. }
  50731. return this._volumetricLightScatteringPass.isReady();
  50732. };
  50733. /**
  50734. * Sets the new light position for light scattering effect
  50735. * @param {BABYLON.Vector3} The new custom light position
  50736. */
  50737. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  50738. this.customMeshPosition = position;
  50739. };
  50740. /**
  50741. * Returns the light position for light scattering effect
  50742. * @return {BABYLON.Vector3} The custom light position
  50743. */
  50744. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  50745. return this.customMeshPosition;
  50746. };
  50747. /**
  50748. * Disposes the internal assets and detaches the post-process from the camera
  50749. */
  50750. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  50751. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  50752. if (rttIndex !== -1) {
  50753. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  50754. }
  50755. this._volumetricLightScatteringRTT.dispose();
  50756. _super.prototype.dispose.call(this, camera);
  50757. };
  50758. /**
  50759. * Returns the render target texture used by the post-process
  50760. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  50761. */
  50762. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  50763. return this._volumetricLightScatteringRTT;
  50764. };
  50765. // Private methods
  50766. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  50767. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  50768. return true;
  50769. }
  50770. return false;
  50771. };
  50772. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  50773. var _this = this;
  50774. var engine = scene.getEngine();
  50775. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  50776. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50777. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50778. this._volumetricLightScatteringRTT.renderList = null;
  50779. this._volumetricLightScatteringRTT.renderParticles = false;
  50780. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  50781. // Custom render function for submeshes
  50782. var renderSubMesh = function (subMesh) {
  50783. var mesh = subMesh.getRenderingMesh();
  50784. if (_this._meshExcluded(mesh)) {
  50785. return;
  50786. }
  50787. var scene = mesh.getScene();
  50788. var engine = scene.getEngine();
  50789. // Culling
  50790. engine.setState(subMesh.getMaterial().backFaceCulling);
  50791. // Managing instances
  50792. var batch = mesh._getInstancesRenderList(subMesh._id);
  50793. if (batch.mustReturn) {
  50794. return;
  50795. }
  50796. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  50797. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  50798. var effect = _this._volumetricLightScatteringPass;
  50799. if (mesh === _this.mesh) {
  50800. effect = subMesh.getMaterial().getEffect();
  50801. }
  50802. engine.enableEffect(effect);
  50803. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  50804. if (mesh === _this.mesh) {
  50805. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  50806. }
  50807. else {
  50808. var material = subMesh.getMaterial();
  50809. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  50810. // Alpha test
  50811. if (material && material.needAlphaTesting()) {
  50812. var alphaTexture = material.getAlphaTestTexture();
  50813. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  50814. if (alphaTexture) {
  50815. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50816. }
  50817. }
  50818. // Bones
  50819. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50820. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50821. }
  50822. }
  50823. // Draw
  50824. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  50825. }
  50826. };
  50827. // Render target texture callbacks
  50828. var savedSceneClearColor;
  50829. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  50830. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  50831. savedSceneClearColor = scene.clearColor;
  50832. scene.clearColor = sceneClearColor;
  50833. });
  50834. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  50835. scene.clearColor = savedSceneClearColor;
  50836. });
  50837. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  50838. var engine = scene.getEngine();
  50839. var index;
  50840. for (index = 0; index < opaqueSubMeshes.length; index++) {
  50841. renderSubMesh(opaqueSubMeshes.data[index]);
  50842. }
  50843. engine.setAlphaTesting(true);
  50844. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  50845. renderSubMesh(alphaTestSubMeshes.data[index]);
  50846. }
  50847. engine.setAlphaTesting(false);
  50848. if (transparentSubMeshes.length) {
  50849. // Sort sub meshes
  50850. for (index = 0; index < transparentSubMeshes.length; index++) {
  50851. var submesh = transparentSubMeshes.data[index];
  50852. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  50853. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  50854. }
  50855. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  50856. sortedArray.sort(function (a, b) {
  50857. // Alpha index first
  50858. if (a._alphaIndex > b._alphaIndex) {
  50859. return 1;
  50860. }
  50861. if (a._alphaIndex < b._alphaIndex) {
  50862. return -1;
  50863. }
  50864. // Then distance to camera
  50865. if (a._distanceToCamera < b._distanceToCamera) {
  50866. return 1;
  50867. }
  50868. if (a._distanceToCamera > b._distanceToCamera) {
  50869. return -1;
  50870. }
  50871. return 0;
  50872. });
  50873. // Render sub meshes
  50874. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50875. for (index = 0; index < sortedArray.length; index++) {
  50876. renderSubMesh(sortedArray[index]);
  50877. }
  50878. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50879. }
  50880. };
  50881. };
  50882. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  50883. var transform = scene.getTransformMatrix();
  50884. var meshPosition;
  50885. if (this.useCustomMeshPosition) {
  50886. meshPosition = this.customMeshPosition;
  50887. }
  50888. else if (this.attachedNode) {
  50889. meshPosition = this.attachedNode.position;
  50890. }
  50891. else {
  50892. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  50893. }
  50894. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  50895. this._screenCoordinates.x = pos.x / this._viewPort.width;
  50896. this._screenCoordinates.y = pos.y / this._viewPort.height;
  50897. if (this.invert)
  50898. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  50899. };
  50900. // Static methods
  50901. /**
  50902. * Creates a default mesh for the Volumeric Light Scattering post-process
  50903. * @param {string} The mesh name
  50904. * @param {BABYLON.Scene} The scene where to create the mesh
  50905. * @return {BABYLON.Mesh} the default mesh
  50906. */
  50907. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  50908. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  50909. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  50910. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  50911. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  50912. mesh.material = material;
  50913. return mesh;
  50914. };
  50915. return VolumetricLightScatteringPostProcess;
  50916. }(BABYLON.PostProcess));
  50917. __decorate([
  50918. BABYLON.serializeAsVector3()
  50919. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  50920. __decorate([
  50921. BABYLON.serialize()
  50922. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  50923. __decorate([
  50924. BABYLON.serialize()
  50925. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  50926. __decorate([
  50927. BABYLON.serializeAsMeshReference()
  50928. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  50929. __decorate([
  50930. BABYLON.serialize()
  50931. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  50932. __decorate([
  50933. BABYLON.serialize()
  50934. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  50935. __decorate([
  50936. BABYLON.serialize()
  50937. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  50938. __decorate([
  50939. BABYLON.serialize()
  50940. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  50941. __decorate([
  50942. BABYLON.serialize()
  50943. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  50944. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  50945. })(BABYLON || (BABYLON = {}));
  50946. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  50947. // BABYLON.JS Chromatic Aberration GLSL Shader
  50948. // Author: Olivier Guyot
  50949. // Separates very slightly R, G and B colors on the edges of the screen
  50950. // Inspired by Francois Tarlier & Martins Upitis
  50951. var BABYLON;
  50952. (function (BABYLON) {
  50953. var LensRenderingPipeline = (function (_super) {
  50954. __extends(LensRenderingPipeline, _super);
  50955. /**
  50956. * @constructor
  50957. *
  50958. * Effect parameters are as follow:
  50959. * {
  50960. * chromatic_aberration: number; // from 0 to x (1 for realism)
  50961. * edge_blur: number; // from 0 to x (1 for realism)
  50962. * distortion: number; // from 0 to x (1 for realism)
  50963. * grain_amount: number; // from 0 to 1
  50964. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  50965. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  50966. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  50967. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  50968. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  50969. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  50970. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  50971. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  50972. * }
  50973. * Note: if an effect parameter is unset, effect is disabled
  50974. *
  50975. * @param {string} name - The rendering pipeline name
  50976. * @param {object} parameters - An object containing all parameters (see above)
  50977. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50978. * @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)
  50979. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50980. */
  50981. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  50982. if (ratio === void 0) { ratio = 1.0; }
  50983. var _this = _super.call(this, scene.getEngine(), name) || this;
  50984. // Lens effects can be of the following:
  50985. // - chromatic aberration (slight shift of RGB colors)
  50986. // - blur on the edge of the lens
  50987. // - lens distortion
  50988. // - depth-of-field blur & highlights enhancing
  50989. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  50990. // - grain effect (noise or custom texture)
  50991. // Two additional texture samplers are needed:
  50992. // - depth map (for depth-of-field)
  50993. // - grain texture
  50994. /**
  50995. * The chromatic aberration PostProcess id in the pipeline
  50996. * @type {string}
  50997. */
  50998. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  50999. /**
  51000. * The highlights enhancing PostProcess id in the pipeline
  51001. * @type {string}
  51002. */
  51003. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  51004. /**
  51005. * The depth-of-field PostProcess id in the pipeline
  51006. * @type {string}
  51007. */
  51008. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  51009. _this._scene = scene;
  51010. // Fetch texture samplers
  51011. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  51012. if (parameters.grain_texture) {
  51013. _this._grainTexture = parameters.grain_texture;
  51014. }
  51015. else {
  51016. _this._createGrainTexture();
  51017. }
  51018. // save parameters
  51019. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  51020. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  51021. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  51022. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  51023. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  51024. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  51025. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  51026. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  51027. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  51028. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  51029. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  51030. // Create effects
  51031. _this._createChromaticAberrationPostProcess(ratio);
  51032. _this._createHighlightsPostProcess(ratio);
  51033. _this._createDepthOfFieldPostProcess(ratio / 4);
  51034. // Set up pipeline
  51035. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  51036. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  51037. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  51038. if (_this._highlightsGain === -1) {
  51039. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  51040. }
  51041. // Finish
  51042. scene.postProcessRenderPipelineManager.addPipeline(_this);
  51043. if (cameras) {
  51044. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  51045. }
  51046. return _this;
  51047. }
  51048. // public methods (self explanatory)
  51049. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  51050. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  51051. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  51052. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  51053. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  51054. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  51055. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  51056. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  51057. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  51058. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  51059. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  51060. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  51061. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  51062. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  51063. };
  51064. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  51065. this._highlightsPostProcess.updateEffect();
  51066. };
  51067. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  51068. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  51069. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  51070. this._highlightsGain = amount;
  51071. };
  51072. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  51073. if (this._highlightsGain === -1) {
  51074. this._highlightsGain = 1.0;
  51075. }
  51076. this._highlightsThreshold = amount;
  51077. };
  51078. LensRenderingPipeline.prototype.disableHighlights = function () {
  51079. this._highlightsGain = -1;
  51080. };
  51081. /**
  51082. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  51083. */
  51084. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  51085. if (disableDepthRender === void 0) { disableDepthRender = false; }
  51086. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  51087. this._chromaticAberrationPostProcess = undefined;
  51088. this._highlightsPostProcess = undefined;
  51089. this._depthOfFieldPostProcess = undefined;
  51090. this._grainTexture.dispose();
  51091. if (disableDepthRender)
  51092. this._scene.disableDepthRenderer();
  51093. };
  51094. // colors shifting and distortion
  51095. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  51096. var _this = this;
  51097. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  51098. [], // samplers
  51099. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  51100. this._chromaticAberrationPostProcess.onApply = function (effect) {
  51101. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  51102. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  51103. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  51104. };
  51105. };
  51106. // highlights enhancing
  51107. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  51108. var _this = this;
  51109. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  51110. [], // samplers
  51111. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  51112. this._highlightsPostProcess.onApply = function (effect) {
  51113. effect.setFloat('gain', _this._highlightsGain);
  51114. effect.setFloat('threshold', _this._highlightsThreshold);
  51115. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  51116. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  51117. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  51118. };
  51119. };
  51120. // colors shifting and distortion
  51121. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  51122. var _this = this;
  51123. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  51124. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  51125. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  51126. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  51127. this._depthOfFieldPostProcess.onApply = function (effect) {
  51128. effect.setTexture("depthSampler", _this._depthTexture);
  51129. effect.setTexture("grainSampler", _this._grainTexture);
  51130. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  51131. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  51132. effect.setFloat('grain_amount', _this._grainAmount);
  51133. effect.setBool('blur_noise', _this._blurNoise);
  51134. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  51135. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  51136. effect.setFloat('distortion', _this._distortion);
  51137. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  51138. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  51139. effect.setFloat('aperture', _this._dofAperture);
  51140. effect.setFloat('darken', _this._dofDarken);
  51141. effect.setFloat('edge_blur', _this._edgeBlur);
  51142. effect.setBool('highlights', (_this._highlightsGain !== -1));
  51143. effect.setFloat('near', _this._scene.activeCamera.minZ);
  51144. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  51145. };
  51146. };
  51147. // creates a black and white random noise texture, 512x512
  51148. LensRenderingPipeline.prototype._createGrainTexture = function () {
  51149. var size = 512;
  51150. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51151. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51152. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51153. var context = this._grainTexture.getContext();
  51154. var rand = function (min, max) {
  51155. return Math.random() * (max - min) + min;
  51156. };
  51157. var value;
  51158. for (var x = 0; x < size; x++) {
  51159. for (var y = 0; y < size; y++) {
  51160. value = Math.floor(rand(0.42, 0.58) * 255);
  51161. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  51162. context.fillRect(x, y, 1, 1);
  51163. }
  51164. }
  51165. this._grainTexture.update(false);
  51166. };
  51167. return LensRenderingPipeline;
  51168. }(BABYLON.PostProcessRenderPipeline));
  51169. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  51170. })(BABYLON || (BABYLON = {}));
  51171. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  51172. //
  51173. // This post-process allows the modification of rendered colors by using
  51174. // a 'look-up table' (LUT). This effect is also called Color Grading.
  51175. //
  51176. // The object needs to be provided an url to a texture containing the color
  51177. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  51178. // Use an image editing software to tweak the LUT to match your needs.
  51179. //
  51180. // For an example of a color LUT, see here:
  51181. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  51182. // For explanations on color grading, see here:
  51183. // http://udn.epicgames.com/Three/ColorGrading.html
  51184. //
  51185. var BABYLON;
  51186. (function (BABYLON) {
  51187. var ColorCorrectionPostProcess = (function (_super) {
  51188. __extends(ColorCorrectionPostProcess, _super);
  51189. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  51190. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  51191. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  51192. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  51193. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51194. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51195. _this.onApply = function (effect) {
  51196. effect.setTexture("colorTable", _this._colorTableTexture);
  51197. };
  51198. return _this;
  51199. }
  51200. return ColorCorrectionPostProcess;
  51201. }(BABYLON.PostProcess));
  51202. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  51203. })(BABYLON || (BABYLON = {}));
  51204. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  51205. /// <reference path="babylon.freeCamera.ts" />
  51206. /// <reference path="babylon.arcRotateCamera.ts" />
  51207. /// <reference path="babylon.gamepadCamera.ts" />
  51208. /// <reference path="babylon.universalCamera.ts" />
  51209. var BABYLON;
  51210. (function (BABYLON) {
  51211. var AnaglyphFreeCamera = (function (_super) {
  51212. __extends(AnaglyphFreeCamera, _super);
  51213. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  51214. var _this = _super.call(this, name, position, scene) || this;
  51215. _this.interaxialDistance = interaxialDistance;
  51216. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  51217. return _this;
  51218. }
  51219. AnaglyphFreeCamera.prototype.getClassName = function () {
  51220. return "AnaglyphFreeCamera";
  51221. };
  51222. return AnaglyphFreeCamera;
  51223. }(BABYLON.FreeCamera));
  51224. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  51225. var AnaglyphArcRotateCamera = (function (_super) {
  51226. __extends(AnaglyphArcRotateCamera, _super);
  51227. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  51228. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  51229. _this.interaxialDistance = interaxialDistance;
  51230. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  51231. return _this;
  51232. }
  51233. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  51234. return "AnaglyphArcRotateCamera";
  51235. };
  51236. return AnaglyphArcRotateCamera;
  51237. }(BABYLON.ArcRotateCamera));
  51238. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  51239. var AnaglyphGamepadCamera = (function (_super) {
  51240. __extends(AnaglyphGamepadCamera, _super);
  51241. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  51242. var _this = _super.call(this, name, position, scene) || this;
  51243. _this.interaxialDistance = interaxialDistance;
  51244. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  51245. return _this;
  51246. }
  51247. AnaglyphGamepadCamera.prototype.getClassName = function () {
  51248. return "AnaglyphGamepadCamera";
  51249. };
  51250. return AnaglyphGamepadCamera;
  51251. }(BABYLON.GamepadCamera));
  51252. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  51253. var AnaglyphUniversalCamera = (function (_super) {
  51254. __extends(AnaglyphUniversalCamera, _super);
  51255. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  51256. var _this = _super.call(this, name, position, scene) || this;
  51257. _this.interaxialDistance = interaxialDistance;
  51258. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  51259. return _this;
  51260. }
  51261. AnaglyphUniversalCamera.prototype.getClassName = function () {
  51262. return "AnaglyphUniversalCamera";
  51263. };
  51264. return AnaglyphUniversalCamera;
  51265. }(BABYLON.UniversalCamera));
  51266. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  51267. var StereoscopicFreeCamera = (function (_super) {
  51268. __extends(StereoscopicFreeCamera, _super);
  51269. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  51270. var _this = _super.call(this, name, position, scene) || this;
  51271. _this.interaxialDistance = interaxialDistance;
  51272. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  51273. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  51274. return _this;
  51275. }
  51276. StereoscopicFreeCamera.prototype.getClassName = function () {
  51277. return "StereoscopicFreeCamera";
  51278. };
  51279. return StereoscopicFreeCamera;
  51280. }(BABYLON.FreeCamera));
  51281. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  51282. var StereoscopicArcRotateCamera = (function (_super) {
  51283. __extends(StereoscopicArcRotateCamera, _super);
  51284. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  51285. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  51286. _this.interaxialDistance = interaxialDistance;
  51287. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  51288. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  51289. return _this;
  51290. }
  51291. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  51292. return "StereoscopicArcRotateCamera";
  51293. };
  51294. return StereoscopicArcRotateCamera;
  51295. }(BABYLON.ArcRotateCamera));
  51296. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  51297. var StereoscopicGamepadCamera = (function (_super) {
  51298. __extends(StereoscopicGamepadCamera, _super);
  51299. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  51300. var _this = _super.call(this, name, position, scene) || this;
  51301. _this.interaxialDistance = interaxialDistance;
  51302. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  51303. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  51304. return _this;
  51305. }
  51306. StereoscopicGamepadCamera.prototype.getClassName = function () {
  51307. return "StereoscopicGamepadCamera";
  51308. };
  51309. return StereoscopicGamepadCamera;
  51310. }(BABYLON.GamepadCamera));
  51311. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  51312. var StereoscopicUniversalCamera = (function (_super) {
  51313. __extends(StereoscopicUniversalCamera, _super);
  51314. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  51315. var _this = _super.call(this, name, position, scene) || this;
  51316. _this.interaxialDistance = interaxialDistance;
  51317. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  51318. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  51319. return _this;
  51320. }
  51321. StereoscopicUniversalCamera.prototype.getClassName = function () {
  51322. return "StereoscopicUniversalCamera";
  51323. };
  51324. return StereoscopicUniversalCamera;
  51325. }(BABYLON.UniversalCamera));
  51326. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  51327. })(BABYLON || (BABYLON = {}));
  51328. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  51329. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  51330. var BABYLON;
  51331. (function (BABYLON) {
  51332. var HDRRenderingPipeline = (function (_super) {
  51333. __extends(HDRRenderingPipeline, _super);
  51334. /**
  51335. * @constructor
  51336. * @param {string} name - The rendering pipeline name
  51337. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51338. * @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)
  51339. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  51340. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51341. */
  51342. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  51343. if (originalPostProcess === void 0) { originalPostProcess = null; }
  51344. var _this = _super.call(this, scene.getEngine(), name) || this;
  51345. /**
  51346. * Public members
  51347. */
  51348. // Gaussian Blur
  51349. /**
  51350. * Gaussian blur coefficient
  51351. * @type {number}
  51352. */
  51353. _this.gaussCoeff = 0.3;
  51354. /**
  51355. * Gaussian blur mean
  51356. * @type {number}
  51357. */
  51358. _this.gaussMean = 1.0;
  51359. /**
  51360. * Gaussian blur standard deviation
  51361. * @type {number}
  51362. */
  51363. _this.gaussStandDev = 0.8;
  51364. /**
  51365. * Gaussian blur multiplier. Multiplies the blur effect
  51366. * @type {number}
  51367. */
  51368. _this.gaussMultiplier = 4.0;
  51369. // HDR
  51370. /**
  51371. * Exposure, controls the overall intensity of the pipeline
  51372. * @type {number}
  51373. */
  51374. _this.exposure = 1.0;
  51375. /**
  51376. * Minimum luminance that the post-process can output. Luminance is >= 0
  51377. * @type {number}
  51378. */
  51379. _this.minimumLuminance = 1.0;
  51380. /**
  51381. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  51382. * @type {number}
  51383. */
  51384. _this.maximumLuminance = 1e20;
  51385. /**
  51386. * Increase rate for luminance: eye adaptation speed to dark
  51387. * @type {number}
  51388. */
  51389. _this.luminanceIncreaserate = 0.5;
  51390. /**
  51391. * Decrease rate for luminance: eye adaptation speed to bright
  51392. * @type {number}
  51393. */
  51394. _this.luminanceDecreaseRate = 0.5;
  51395. // Bright pass
  51396. /**
  51397. * Minimum luminance needed to compute HDR
  51398. * @type {number}
  51399. */
  51400. _this.brightThreshold = 0.8;
  51401. _this._needUpdate = true;
  51402. _this._scene = scene;
  51403. // Bright pass
  51404. _this._createBrightPassPostProcess(scene, ratio);
  51405. // Down sample X4
  51406. _this._createDownSampleX4PostProcess(scene, ratio);
  51407. // Create gaussian blur post-processes
  51408. _this._createGaussianBlurPostProcess(scene, ratio);
  51409. // Texture adder
  51410. _this._createTextureAdderPostProcess(scene, ratio);
  51411. // Luminance generator
  51412. _this._createLuminanceGeneratorPostProcess(scene);
  51413. // HDR
  51414. _this._createHDRPostProcess(scene, ratio);
  51415. // Pass postprocess
  51416. if (originalPostProcess === null) {
  51417. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  51418. }
  51419. else {
  51420. _this._originalPostProcess = originalPostProcess;
  51421. }
  51422. // Configure pipeline
  51423. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  51424. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  51425. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  51426. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  51427. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  51428. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  51429. var addDownSamplerPostProcess = function (id) {
  51430. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  51431. };
  51432. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  51433. addDownSamplerPostProcess(i);
  51434. }
  51435. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  51436. // Finish
  51437. scene.postProcessRenderPipelineManager.addPipeline(_this);
  51438. if (cameras !== null) {
  51439. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  51440. }
  51441. _this.update();
  51442. return _this;
  51443. }
  51444. /**
  51445. * Tells the pipeline to update its post-processes
  51446. */
  51447. HDRRenderingPipeline.prototype.update = function () {
  51448. this._needUpdate = true;
  51449. };
  51450. /**
  51451. * Returns the current calculated luminance
  51452. */
  51453. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  51454. return this._hdrCurrentLuminance;
  51455. };
  51456. /**
  51457. * Returns the currently drawn luminance
  51458. */
  51459. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  51460. return this._hdrOutputLuminance;
  51461. };
  51462. /**
  51463. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  51464. */
  51465. HDRRenderingPipeline.prototype.dispose = function () {
  51466. for (var i = 0; i < this._scene.cameras.length; i++) {
  51467. var camera = this._scene.cameras[i];
  51468. this._originalPostProcess.dispose(camera);
  51469. this._brightPassPostProcess.dispose(camera);
  51470. this._downSampleX4PostProcess.dispose(camera);
  51471. this._guassianBlurHPostProcess.dispose(camera);
  51472. this._guassianBlurVPostProcess.dispose(camera);
  51473. this._textureAdderPostProcess.dispose(camera);
  51474. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  51475. this._downSamplePostProcesses[j].dispose(camera);
  51476. }
  51477. this._hdrPostProcess.dispose(camera);
  51478. }
  51479. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  51480. _super.prototype.dispose.call(this);
  51481. };
  51482. /**
  51483. * Creates the HDR post-process and computes the luminance adaptation
  51484. */
  51485. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  51486. var _this = this;
  51487. var hdrLastLuminance = 0.0;
  51488. this._hdrOutputLuminance = -1.0;
  51489. this._hdrCurrentLuminance = 1.0;
  51490. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  51491. this._hdrPostProcess.onApply = function (effect) {
  51492. if (_this._hdrOutputLuminance < 0.0) {
  51493. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  51494. }
  51495. else {
  51496. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  51497. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  51498. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  51499. }
  51500. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  51501. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  51502. }
  51503. else {
  51504. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  51505. }
  51506. }
  51507. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  51508. hdrLastLuminance += scene.getEngine().getDeltaTime();
  51509. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  51510. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  51511. effect.setFloat("exposure", _this.exposure);
  51512. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  51513. _this._needUpdate = false;
  51514. };
  51515. };
  51516. /**
  51517. * Texture Adder post-process
  51518. */
  51519. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  51520. var _this = this;
  51521. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  51522. this._textureAdderPostProcess.onApply = function (effect) {
  51523. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  51524. };
  51525. };
  51526. /**
  51527. * Down sample X4 post-process
  51528. */
  51529. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  51530. var _this = this;
  51531. var downSampleX4Offsets = new Array(32);
  51532. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  51533. this._downSampleX4PostProcess.onApply = function (effect) {
  51534. if (_this._needUpdate) {
  51535. var id = 0;
  51536. for (var i = -2; i < 2; i++) {
  51537. for (var j = -2; j < 2; j++) {
  51538. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  51539. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  51540. id += 2;
  51541. }
  51542. }
  51543. }
  51544. effect.setArray2("dsOffsets", downSampleX4Offsets);
  51545. };
  51546. };
  51547. /**
  51548. * Bright pass post-process
  51549. */
  51550. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  51551. var _this = this;
  51552. var brightOffsets = new Array(8);
  51553. var brightPassCallback = function (effect) {
  51554. if (_this._needUpdate) {
  51555. var sU = (1.0 / _this._brightPassPostProcess.width);
  51556. var sV = (1.0 / _this._brightPassPostProcess.height);
  51557. brightOffsets[0] = -0.5 * sU;
  51558. brightOffsets[1] = 0.5 * sV;
  51559. brightOffsets[2] = 0.5 * sU;
  51560. brightOffsets[3] = 0.5 * sV;
  51561. brightOffsets[4] = -0.5 * sU;
  51562. brightOffsets[5] = -0.5 * sV;
  51563. brightOffsets[6] = 0.5 * sU;
  51564. brightOffsets[7] = -0.5 * sV;
  51565. }
  51566. effect.setArray2("dsOffsets", brightOffsets);
  51567. effect.setFloat("brightThreshold", _this.brightThreshold);
  51568. };
  51569. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  51570. this._brightPassPostProcess.onApply = brightPassCallback;
  51571. };
  51572. /**
  51573. * Luminance generator. Creates the luminance post-process and down sample post-processes
  51574. */
  51575. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  51576. var _this = this;
  51577. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  51578. var luminanceOffsets = new Array(8);
  51579. var downSampleOffsets = new Array(18);
  51580. var halfDestPixelSize;
  51581. this._downSamplePostProcesses = new Array(lumSteps);
  51582. // Utils for luminance
  51583. var luminanceUpdateSourceOffsets = function (width, height) {
  51584. var sU = (1.0 / width);
  51585. var sV = (1.0 / height);
  51586. luminanceOffsets[0] = -0.5 * sU;
  51587. luminanceOffsets[1] = 0.5 * sV;
  51588. luminanceOffsets[2] = 0.5 * sU;
  51589. luminanceOffsets[3] = 0.5 * sV;
  51590. luminanceOffsets[4] = -0.5 * sU;
  51591. luminanceOffsets[5] = -0.5 * sV;
  51592. luminanceOffsets[6] = 0.5 * sU;
  51593. luminanceOffsets[7] = -0.5 * sV;
  51594. };
  51595. var luminanceUpdateDestOffsets = function (width, height) {
  51596. var id = 0;
  51597. for (var x = -1; x < 2; x++) {
  51598. for (var y = -1; y < 2; y++) {
  51599. downSampleOffsets[id] = (x) / width;
  51600. downSampleOffsets[id + 1] = (y) / height;
  51601. id += 2;
  51602. }
  51603. }
  51604. };
  51605. // Luminance callback
  51606. var luminanceCallback = function (effect) {
  51607. if (_this._needUpdate) {
  51608. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  51609. }
  51610. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  51611. effect.setArray2("lumOffsets", luminanceOffsets);
  51612. };
  51613. // Down sample callbacks
  51614. var downSampleCallback = function (indice) {
  51615. var i = indice;
  51616. return function (effect) {
  51617. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  51618. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  51619. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  51620. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  51621. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  51622. effect.setArray2("dsOffsets", downSampleOffsets);
  51623. };
  51624. };
  51625. var downSampleAfterRenderCallback = function (effect) {
  51626. // Unpack result
  51627. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  51628. 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);
  51629. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  51630. };
  51631. // Create luminance post-process
  51632. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  51633. 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);
  51634. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  51635. // Create down sample post-processes
  51636. for (var i = lumSteps - 2; i >= 0; i--) {
  51637. var length = Math.pow(3, i);
  51638. ratio = { width: length, height: length };
  51639. var defines = "#define DOWN_SAMPLE\n";
  51640. if (i === 0) {
  51641. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  51642. }
  51643. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  51644. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  51645. if (i === 0) {
  51646. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  51647. }
  51648. }
  51649. };
  51650. /**
  51651. * Gaussian blur post-processes. Horizontal and Vertical
  51652. */
  51653. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  51654. var _this = this;
  51655. var blurOffsetsW = new Array(9);
  51656. var blurOffsetsH = new Array(9);
  51657. var blurWeights = new Array(9);
  51658. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  51659. // Utils for gaussian blur
  51660. var calculateBlurOffsets = function (height) {
  51661. var lastOutputDimensions = {
  51662. width: scene.getEngine().getRenderWidth(),
  51663. height: scene.getEngine().getRenderHeight()
  51664. };
  51665. for (var i = 0; i < 9; i++) {
  51666. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  51667. if (height) {
  51668. blurOffsetsH[i] = value;
  51669. }
  51670. else {
  51671. blurOffsetsW[i] = value;
  51672. }
  51673. }
  51674. };
  51675. var calculateWeights = function () {
  51676. var x = 0.0;
  51677. for (var i = 0; i < 9; i++) {
  51678. x = (i - 4.0) / 4.0;
  51679. 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));
  51680. }
  51681. };
  51682. // Callback
  51683. var gaussianBlurCallback = function (height) {
  51684. return function (effect) {
  51685. if (_this._needUpdate) {
  51686. calculateWeights();
  51687. calculateBlurOffsets(height);
  51688. }
  51689. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  51690. effect.setArray("blurWeights", blurWeights);
  51691. effect.setFloat("multiplier", _this.gaussMultiplier);
  51692. };
  51693. };
  51694. // Create horizontal gaussian blur post-processes
  51695. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  51696. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  51697. // Create vertical gaussian blur post-process
  51698. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  51699. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  51700. };
  51701. return HDRRenderingPipeline;
  51702. }(BABYLON.PostProcessRenderPipeline));
  51703. // Luminance generator
  51704. HDRRenderingPipeline.LUM_STEPS = 6;
  51705. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  51706. })(BABYLON || (BABYLON = {}));
  51707. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  51708. var BABYLON;
  51709. (function (BABYLON) {
  51710. var FaceAdjacencies = (function () {
  51711. function FaceAdjacencies() {
  51712. this.edges = new Array();
  51713. this.edgesConnectedCount = 0;
  51714. }
  51715. return FaceAdjacencies;
  51716. }());
  51717. var EdgesRenderer = (function () {
  51718. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  51719. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  51720. if (epsilon === void 0) { epsilon = 0.95; }
  51721. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  51722. this.edgesWidthScalerForOrthographic = 1000.0;
  51723. this.edgesWidthScalerForPerspective = 50.0;
  51724. this._linesPositions = new Array();
  51725. this._linesNormals = new Array();
  51726. this._linesIndices = new Array();
  51727. this._buffers = {};
  51728. this._checkVerticesInsteadOfIndices = false;
  51729. this._source = source;
  51730. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  51731. this._epsilon = epsilon;
  51732. this._prepareRessources();
  51733. this._generateEdgesLines();
  51734. }
  51735. EdgesRenderer.prototype._prepareRessources = function () {
  51736. if (this._lineShader) {
  51737. return;
  51738. }
  51739. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  51740. attributes: ["position", "normal"],
  51741. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  51742. });
  51743. this._lineShader.disableDepthWrite = true;
  51744. this._lineShader.backFaceCulling = false;
  51745. };
  51746. EdgesRenderer.prototype.dispose = function () {
  51747. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  51748. if (buffer) {
  51749. buffer.dispose();
  51750. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  51751. }
  51752. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  51753. if (buffer) {
  51754. buffer.dispose();
  51755. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  51756. }
  51757. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  51758. this._lineShader.dispose();
  51759. };
  51760. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  51761. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  51762. return 0;
  51763. }
  51764. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  51765. return 1;
  51766. }
  51767. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  51768. return 2;
  51769. }
  51770. return -1;
  51771. };
  51772. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  51773. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  51774. return 0;
  51775. }
  51776. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  51777. return 1;
  51778. }
  51779. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  51780. return 2;
  51781. }
  51782. return -1;
  51783. };
  51784. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  51785. var needToCreateLine;
  51786. if (edge === undefined) {
  51787. needToCreateLine = true;
  51788. }
  51789. else {
  51790. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  51791. needToCreateLine = dotProduct < this._epsilon;
  51792. }
  51793. if (needToCreateLine) {
  51794. var offset = this._linesPositions.length / 3;
  51795. var normal = p0.subtract(p1);
  51796. normal.normalize();
  51797. // Positions
  51798. this._linesPositions.push(p0.x);
  51799. this._linesPositions.push(p0.y);
  51800. this._linesPositions.push(p0.z);
  51801. this._linesPositions.push(p0.x);
  51802. this._linesPositions.push(p0.y);
  51803. this._linesPositions.push(p0.z);
  51804. this._linesPositions.push(p1.x);
  51805. this._linesPositions.push(p1.y);
  51806. this._linesPositions.push(p1.z);
  51807. this._linesPositions.push(p1.x);
  51808. this._linesPositions.push(p1.y);
  51809. this._linesPositions.push(p1.z);
  51810. // Normals
  51811. this._linesNormals.push(p1.x);
  51812. this._linesNormals.push(p1.y);
  51813. this._linesNormals.push(p1.z);
  51814. this._linesNormals.push(-1);
  51815. this._linesNormals.push(p1.x);
  51816. this._linesNormals.push(p1.y);
  51817. this._linesNormals.push(p1.z);
  51818. this._linesNormals.push(1);
  51819. this._linesNormals.push(p0.x);
  51820. this._linesNormals.push(p0.y);
  51821. this._linesNormals.push(p0.z);
  51822. this._linesNormals.push(-1);
  51823. this._linesNormals.push(p0.x);
  51824. this._linesNormals.push(p0.y);
  51825. this._linesNormals.push(p0.z);
  51826. this._linesNormals.push(1);
  51827. // Indices
  51828. this._linesIndices.push(offset);
  51829. this._linesIndices.push(offset + 1);
  51830. this._linesIndices.push(offset + 2);
  51831. this._linesIndices.push(offset);
  51832. this._linesIndices.push(offset + 2);
  51833. this._linesIndices.push(offset + 3);
  51834. }
  51835. };
  51836. EdgesRenderer.prototype._generateEdgesLines = function () {
  51837. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51838. var indices = this._source.getIndices();
  51839. // First let's find adjacencies
  51840. var adjacencies = new Array();
  51841. var faceNormals = new Array();
  51842. var index;
  51843. var faceAdjacencies;
  51844. // Prepare faces
  51845. for (index = 0; index < indices.length; index += 3) {
  51846. faceAdjacencies = new FaceAdjacencies();
  51847. var p0Index = indices[index];
  51848. var p1Index = indices[index + 1];
  51849. var p2Index = indices[index + 2];
  51850. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  51851. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  51852. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  51853. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  51854. faceNormal.normalize();
  51855. faceNormals.push(faceNormal);
  51856. adjacencies.push(faceAdjacencies);
  51857. }
  51858. // Scan
  51859. for (index = 0; index < adjacencies.length; index++) {
  51860. faceAdjacencies = adjacencies[index];
  51861. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  51862. var otherFaceAdjacencies = adjacencies[otherIndex];
  51863. if (faceAdjacencies.edgesConnectedCount === 3) {
  51864. break;
  51865. }
  51866. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  51867. continue;
  51868. }
  51869. var otherP0 = indices[otherIndex * 3];
  51870. var otherP1 = indices[otherIndex * 3 + 1];
  51871. var otherP2 = indices[otherIndex * 3 + 2];
  51872. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  51873. var otherEdgeIndex;
  51874. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  51875. continue;
  51876. }
  51877. switch (edgeIndex) {
  51878. case 0:
  51879. if (this._checkVerticesInsteadOfIndices) {
  51880. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  51881. }
  51882. else {
  51883. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  51884. }
  51885. break;
  51886. case 1:
  51887. if (this._checkVerticesInsteadOfIndices) {
  51888. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  51889. }
  51890. else {
  51891. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  51892. }
  51893. break;
  51894. case 2:
  51895. if (this._checkVerticesInsteadOfIndices) {
  51896. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  51897. }
  51898. else {
  51899. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  51900. }
  51901. break;
  51902. }
  51903. if (otherEdgeIndex === -1) {
  51904. continue;
  51905. }
  51906. faceAdjacencies.edges[edgeIndex] = otherIndex;
  51907. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  51908. faceAdjacencies.edgesConnectedCount++;
  51909. otherFaceAdjacencies.edgesConnectedCount++;
  51910. if (faceAdjacencies.edgesConnectedCount === 3) {
  51911. break;
  51912. }
  51913. }
  51914. }
  51915. }
  51916. // Create lines
  51917. for (index = 0; index < adjacencies.length; index++) {
  51918. // 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
  51919. var current = adjacencies[index];
  51920. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  51921. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  51922. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  51923. }
  51924. // Merge into a single mesh
  51925. var engine = this._source.getScene().getEngine();
  51926. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  51927. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  51928. this._ib = engine.createIndexBuffer(this._linesIndices);
  51929. this._indicesCount = this._linesIndices.length;
  51930. };
  51931. EdgesRenderer.prototype.render = function () {
  51932. if (!this._lineShader.isReady()) {
  51933. return;
  51934. }
  51935. var scene = this._source.getScene();
  51936. var engine = scene.getEngine();
  51937. this._lineShader._preBind();
  51938. // VBOs
  51939. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  51940. scene.resetCachedMaterial();
  51941. this._lineShader.setColor4("color", this._source.edgesColor);
  51942. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  51943. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  51944. }
  51945. else {
  51946. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  51947. }
  51948. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  51949. this._lineShader.bind(this._source.getWorldMatrix());
  51950. // Draw order
  51951. engine.draw(true, 0, this._indicesCount);
  51952. this._lineShader.unbind();
  51953. engine.setDepthWrite(true);
  51954. };
  51955. return EdgesRenderer;
  51956. }());
  51957. BABYLON.EdgesRenderer = EdgesRenderer;
  51958. })(BABYLON || (BABYLON = {}));
  51959. //# sourceMappingURL=babylon.edgesRenderer.js.map
  51960. var BABYLON;
  51961. (function (BABYLON) {
  51962. var TonemappingOperator;
  51963. (function (TonemappingOperator) {
  51964. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  51965. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  51966. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  51967. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  51968. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  51969. ;
  51970. var TonemapPostProcess = (function (_super) {
  51971. __extends(TonemapPostProcess, _super);
  51972. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  51973. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51974. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51975. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  51976. _this._operator = _operator;
  51977. _this.exposureAdjustment = exposureAdjustment;
  51978. var defines = "#define ";
  51979. if (_this._operator === TonemappingOperator.Hable)
  51980. defines += "HABLE_TONEMAPPING";
  51981. else if (_this._operator === TonemappingOperator.Reinhard)
  51982. defines += "REINHARD_TONEMAPPING";
  51983. else if (_this._operator === TonemappingOperator.HejiDawson)
  51984. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  51985. else if (_this._operator === TonemappingOperator.Photographic)
  51986. defines += "PHOTOGRAPHIC_TONEMAPPING";
  51987. //sadly a second call to create the effect.
  51988. _this.updateEffect(defines);
  51989. _this.onApply = function (effect) {
  51990. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  51991. };
  51992. return _this;
  51993. }
  51994. return TonemapPostProcess;
  51995. }(BABYLON.PostProcess));
  51996. BABYLON.TonemapPostProcess = TonemapPostProcess;
  51997. })(BABYLON || (BABYLON = {}));
  51998. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  51999. var BABYLON;
  52000. (function (BABYLON) {
  52001. var ReflectionProbe = (function () {
  52002. function ReflectionProbe(name, size, scene, generateMipMaps) {
  52003. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52004. var _this = this;
  52005. this.name = name;
  52006. this._viewMatrix = BABYLON.Matrix.Identity();
  52007. this._target = BABYLON.Vector3.Zero();
  52008. this._add = BABYLON.Vector3.Zero();
  52009. this.invertYAxis = false;
  52010. this.position = BABYLON.Vector3.Zero();
  52011. this._scene = scene;
  52012. this._scene.reflectionProbes.push(this);
  52013. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  52014. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  52015. switch (faceIndex) {
  52016. case 0:
  52017. _this._add.copyFromFloats(1, 0, 0);
  52018. break;
  52019. case 1:
  52020. _this._add.copyFromFloats(-1, 0, 0);
  52021. break;
  52022. case 2:
  52023. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  52024. break;
  52025. case 3:
  52026. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  52027. break;
  52028. case 4:
  52029. _this._add.copyFromFloats(0, 0, 1);
  52030. break;
  52031. case 5:
  52032. _this._add.copyFromFloats(0, 0, -1);
  52033. break;
  52034. }
  52035. if (_this._attachedMesh) {
  52036. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  52037. }
  52038. _this.position.addToRef(_this._add, _this._target);
  52039. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  52040. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  52041. });
  52042. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  52043. scene.updateTransformMatrix(true);
  52044. });
  52045. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  52046. }
  52047. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  52048. get: function () {
  52049. return this._renderTargetTexture.refreshRate;
  52050. },
  52051. set: function (value) {
  52052. this._renderTargetTexture.refreshRate = value;
  52053. },
  52054. enumerable: true,
  52055. configurable: true
  52056. });
  52057. ReflectionProbe.prototype.getScene = function () {
  52058. return this._scene;
  52059. };
  52060. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  52061. get: function () {
  52062. return this._renderTargetTexture;
  52063. },
  52064. enumerable: true,
  52065. configurable: true
  52066. });
  52067. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  52068. get: function () {
  52069. return this._renderTargetTexture.renderList;
  52070. },
  52071. enumerable: true,
  52072. configurable: true
  52073. });
  52074. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  52075. this._attachedMesh = mesh;
  52076. };
  52077. ReflectionProbe.prototype.dispose = function () {
  52078. var index = this._scene.reflectionProbes.indexOf(this);
  52079. if (index !== -1) {
  52080. // Remove from the scene if found
  52081. this._scene.reflectionProbes.splice(index, 1);
  52082. }
  52083. if (this._renderTargetTexture) {
  52084. this._renderTargetTexture.dispose();
  52085. this._renderTargetTexture = null;
  52086. }
  52087. };
  52088. return ReflectionProbe;
  52089. }());
  52090. BABYLON.ReflectionProbe = ReflectionProbe;
  52091. })(BABYLON || (BABYLON = {}));
  52092. //# sourceMappingURL=babylon.reflectionProbe.js.map
  52093. var BABYLON;
  52094. (function (BABYLON) {
  52095. var SolidParticle = (function () {
  52096. /**
  52097. * Creates a Solid Particle object.
  52098. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52099. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52100. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52101. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  52102. * `shapeId` (integer) is the model shape identifier in the SPS.
  52103. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52104. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  52105. */
  52106. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52107. this.idx = 0; // particle global index
  52108. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  52109. this.position = BABYLON.Vector3.Zero(); // position
  52110. this.rotation = BABYLON.Vector3.Zero(); // rotation
  52111. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  52112. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  52113. this.velocity = BABYLON.Vector3.Zero(); // velocity
  52114. this.alive = true; // alive
  52115. this.isVisible = true; // visibility
  52116. this._pos = 0; // index of this particle in the global "positions" array
  52117. this.shapeId = 0; // model shape id
  52118. this.idxInShape = 0; // index of the particle in its shape id
  52119. this.idx = particleIndex;
  52120. this._pos = positionIndex;
  52121. this._model = model;
  52122. this.shapeId = shapeId;
  52123. this.idxInShape = idxInShape;
  52124. this._sps = sps;
  52125. if (modelBoundingInfo) {
  52126. this._modelBoundingInfo = modelBoundingInfo;
  52127. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52128. }
  52129. }
  52130. Object.defineProperty(SolidParticle.prototype, "scale", {
  52131. /**
  52132. * legacy support, changed scale to scaling
  52133. */
  52134. get: function () {
  52135. return this.scaling;
  52136. },
  52137. set: function (scale) {
  52138. this.scaling = scale;
  52139. },
  52140. enumerable: true,
  52141. configurable: true
  52142. });
  52143. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52144. /**
  52145. * legacy support, changed quaternion to rotationQuaternion
  52146. */
  52147. get: function () {
  52148. return this.rotationQuaternion;
  52149. },
  52150. set: function (q) {
  52151. this.rotationQuaternion = q;
  52152. },
  52153. enumerable: true,
  52154. configurable: true
  52155. });
  52156. /**
  52157. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52158. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52159. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  52160. */
  52161. SolidParticle.prototype.intersectsMesh = function (target) {
  52162. if (!this._boundingInfo || !target._boundingInfo) {
  52163. return false;
  52164. }
  52165. if (this._sps._bSphereOnly) {
  52166. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52167. }
  52168. return this._boundingInfo.intersects(target._boundingInfo, false);
  52169. };
  52170. return SolidParticle;
  52171. }());
  52172. BABYLON.SolidParticle = SolidParticle;
  52173. var ModelShape = (function () {
  52174. /**
  52175. * 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.
  52176. * SPS internal tool, don't use it manually.
  52177. */
  52178. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  52179. this.shapeID = id;
  52180. this._shape = shape;
  52181. this._shapeUV = shapeUV;
  52182. this._positionFunction = posFunction;
  52183. this._vertexFunction = vtxFunction;
  52184. }
  52185. return ModelShape;
  52186. }());
  52187. BABYLON.ModelShape = ModelShape;
  52188. })(BABYLON || (BABYLON = {}));
  52189. //# sourceMappingURL=babylon.solidParticle.js.map
  52190. var BABYLON;
  52191. (function (BABYLON) {
  52192. /**
  52193. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52194. */
  52195. var SolidParticleSystem = (function () {
  52196. /**
  52197. * Creates a SPS (Solid Particle System) object.
  52198. * `name` (String) is the SPS name, this will be the underlying mesh name.
  52199. * `scene` (Scene) is the scene in which the SPS is added.
  52200. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  52201. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  52202. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  52203. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52204. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52205. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52206. */
  52207. function SolidParticleSystem(name, scene, options) {
  52208. // public members
  52209. /**
  52210. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52211. * Example : var p = SPS.particles[i];
  52212. */
  52213. this.particles = new Array();
  52214. /**
  52215. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52216. */
  52217. this.nbParticles = 0;
  52218. /**
  52219. * If the particles must ever face the camera (default false). Useful for planar particles.
  52220. */
  52221. this.billboard = false;
  52222. /**
  52223. * Recompute normals when adding a shape
  52224. */
  52225. this.recomputeNormals = true;
  52226. /**
  52227. * This a counter ofr your own usage. It's not set by any SPS functions.
  52228. */
  52229. this.counter = 0;
  52230. /**
  52231. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52232. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52233. */
  52234. this.vars = {};
  52235. this._positions = new Array();
  52236. this._indices = new Array();
  52237. this._normals = new Array();
  52238. this._colors = new Array();
  52239. this._uvs = new Array();
  52240. this._index = 0; // indices index
  52241. this._updatable = true;
  52242. this._pickable = false;
  52243. this._isVisibilityBoxLocked = false;
  52244. this._alwaysVisible = false;
  52245. this._shapeCounter = 0;
  52246. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  52247. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52248. this._computeParticleColor = true;
  52249. this._computeParticleTexture = true;
  52250. this._computeParticleRotation = true;
  52251. this._computeParticleVertex = false;
  52252. this._computeBoundingBox = false;
  52253. this._cam_axisZ = BABYLON.Vector3.Zero();
  52254. this._cam_axisY = BABYLON.Vector3.Zero();
  52255. this._cam_axisX = BABYLON.Vector3.Zero();
  52256. this._axisX = BABYLON.Axis.X;
  52257. this._axisY = BABYLON.Axis.Y;
  52258. this._axisZ = BABYLON.Axis.Z;
  52259. this._camDir = BABYLON.Vector3.Zero();
  52260. this._rotMatrix = new BABYLON.Matrix();
  52261. this._invertMatrix = new BABYLON.Matrix();
  52262. this._rotated = BABYLON.Vector3.Zero();
  52263. this._quaternion = new BABYLON.Quaternion();
  52264. this._vertex = BABYLON.Vector3.Zero();
  52265. this._normal = BABYLON.Vector3.Zero();
  52266. this._yaw = 0.0;
  52267. this._pitch = 0.0;
  52268. this._roll = 0.0;
  52269. this._halfroll = 0.0;
  52270. this._halfpitch = 0.0;
  52271. this._halfyaw = 0.0;
  52272. this._sinRoll = 0.0;
  52273. this._cosRoll = 0.0;
  52274. this._sinPitch = 0.0;
  52275. this._cosPitch = 0.0;
  52276. this._sinYaw = 0.0;
  52277. this._cosYaw = 0.0;
  52278. this._w = 0.0;
  52279. this._mustUnrotateFixedNormals = false;
  52280. this._minimum = BABYLON.Tmp.Vector3[0];
  52281. this._maximum = BABYLON.Tmp.Vector3[1];
  52282. this._scale = BABYLON.Tmp.Vector3[2];
  52283. this._translation = BABYLON.Tmp.Vector3[3];
  52284. this._minBbox = BABYLON.Tmp.Vector3[4];
  52285. this._maxBbox = BABYLON.Tmp.Vector3[5];
  52286. this._particlesIntersect = false;
  52287. this._bSphereOnly = false;
  52288. this._bSphereRadiusFactor = 1.0;
  52289. this.name = name;
  52290. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52291. this._camera = scene.activeCamera;
  52292. this._pickable = options ? options.isPickable : false;
  52293. this._particlesIntersect = options ? options.particleIntersection : false;
  52294. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52295. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52296. if (options && options.updatable) {
  52297. this._updatable = options.updatable;
  52298. }
  52299. else {
  52300. this._updatable = true;
  52301. }
  52302. if (this._pickable) {
  52303. this.pickedParticles = [];
  52304. }
  52305. }
  52306. /**
  52307. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52308. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52309. */
  52310. SolidParticleSystem.prototype.buildMesh = function () {
  52311. if (this.nbParticles === 0) {
  52312. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52313. this.addShape(triangle, 1);
  52314. triangle.dispose();
  52315. }
  52316. this._positions32 = new Float32Array(this._positions);
  52317. this._uvs32 = new Float32Array(this._uvs);
  52318. this._colors32 = new Float32Array(this._colors);
  52319. if (this.recomputeNormals) {
  52320. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  52321. }
  52322. this._normals32 = new Float32Array(this._normals);
  52323. this._fixedNormal32 = new Float32Array(this._normals);
  52324. if (this._mustUnrotateFixedNormals) {
  52325. this._unrotateFixedNormals();
  52326. }
  52327. var vertexData = new BABYLON.VertexData();
  52328. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52329. vertexData.indices = this._indices;
  52330. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52331. if (this._uvs32) {
  52332. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52333. ;
  52334. }
  52335. if (this._colors32) {
  52336. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52337. }
  52338. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52339. vertexData.applyToMesh(mesh, this._updatable);
  52340. this.mesh = mesh;
  52341. this.mesh.isPickable = this._pickable;
  52342. // free memory
  52343. this._positions = null;
  52344. this._normals = null;
  52345. this._uvs = null;
  52346. this._colors = null;
  52347. if (!this._updatable) {
  52348. this.particles.length = 0;
  52349. }
  52350. return mesh;
  52351. };
  52352. /**
  52353. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52354. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52355. * Thus the particles generated from `digest()` have their property `position` set yet.
  52356. * `mesh` ( Mesh ) is the mesh to be digested
  52357. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  52358. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52359. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52360. */
  52361. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52362. var size = (options && options.facetNb) || 1;
  52363. var number = (options && options.number);
  52364. var delta = (options && options.delta) || 0;
  52365. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52366. var meshInd = mesh.getIndices();
  52367. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52368. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52369. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52370. var f = 0; // facet counter
  52371. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52372. // compute size from number
  52373. if (number) {
  52374. number = (number > totalFacets) ? totalFacets : number;
  52375. size = Math.round(totalFacets / number);
  52376. delta = 0;
  52377. }
  52378. else {
  52379. size = (size > totalFacets) ? totalFacets : size;
  52380. }
  52381. var facetPos = []; // submesh positions
  52382. var facetInd = []; // submesh indices
  52383. var facetUV = []; // submesh UV
  52384. var facetCol = []; // submesh colors
  52385. var barycenter = BABYLON.Tmp.Vector3[0];
  52386. var rand;
  52387. var sizeO = size;
  52388. while (f < totalFacets) {
  52389. size = sizeO + Math.floor((1 + delta) * Math.random());
  52390. if (f > totalFacets - size) {
  52391. size = totalFacets - f;
  52392. }
  52393. // reset temp arrays
  52394. facetPos.length = 0;
  52395. facetInd.length = 0;
  52396. facetUV.length = 0;
  52397. facetCol.length = 0;
  52398. // iterate over "size" facets
  52399. var fi = 0;
  52400. for (var j = f * 3; j < (f + size) * 3; j++) {
  52401. facetInd.push(fi);
  52402. var i = meshInd[j];
  52403. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52404. if (meshUV) {
  52405. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52406. }
  52407. if (meshCol) {
  52408. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  52409. }
  52410. fi++;
  52411. }
  52412. // create a model shape for each single particle
  52413. var idx = this.nbParticles;
  52414. var shape = this._posToShape(facetPos);
  52415. var shapeUV = this._uvsToShapeUV(facetUV);
  52416. // compute the barycenter of the shape
  52417. var v;
  52418. for (v = 0; v < shape.length; v++) {
  52419. barycenter.addInPlace(shape[v]);
  52420. }
  52421. barycenter.scaleInPlace(1 / shape.length);
  52422. // shift the shape from its barycenter to the origin
  52423. for (v = 0; v < shape.length; v++) {
  52424. shape[v].subtractInPlace(barycenter);
  52425. }
  52426. var bInfo;
  52427. if (this._particlesIntersect) {
  52428. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  52429. }
  52430. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  52431. // add the particle in the SPS
  52432. var currentPos = this._positions.length;
  52433. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  52434. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  52435. // initialize the particle position
  52436. this.particles[this.nbParticles].position.addInPlace(barycenter);
  52437. this._index += shape.length;
  52438. idx++;
  52439. this.nbParticles++;
  52440. this._shapeCounter++;
  52441. f += size;
  52442. }
  52443. return this;
  52444. };
  52445. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  52446. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  52447. var index = 0;
  52448. var idx = 0;
  52449. for (var p = 0; p < this.particles.length; p++) {
  52450. this._particle = this.particles[p];
  52451. this._shape = this._particle._model._shape;
  52452. if (this._particle.rotationQuaternion) {
  52453. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52454. }
  52455. else {
  52456. this._yaw = this._particle.rotation.y;
  52457. this._pitch = this._particle.rotation.x;
  52458. this._roll = this._particle.rotation.z;
  52459. this._quaternionRotationYPR();
  52460. }
  52461. this._quaternionToRotationMatrix();
  52462. this._rotMatrix.invertToRef(this._invertMatrix);
  52463. for (var pt = 0; pt < this._shape.length; pt++) {
  52464. idx = index + pt * 3;
  52465. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  52466. this._fixedNormal32[idx] = this._normal.x;
  52467. this._fixedNormal32[idx + 1] = this._normal.y;
  52468. this._fixedNormal32[idx + 2] = this._normal.z;
  52469. }
  52470. index = idx + 3;
  52471. }
  52472. };
  52473. //reset copy
  52474. SolidParticleSystem.prototype._resetCopy = function () {
  52475. this._copy.position.x = 0;
  52476. this._copy.position.y = 0;
  52477. this._copy.position.z = 0;
  52478. this._copy.rotation.x = 0;
  52479. this._copy.rotation.y = 0;
  52480. this._copy.rotation.z = 0;
  52481. this._copy.rotationQuaternion = null;
  52482. this._copy.scaling.x = 1;
  52483. this._copy.scaling.y = 1;
  52484. this._copy.scaling.z = 1;
  52485. this._copy.uvs.x = 0;
  52486. this._copy.uvs.y = 0;
  52487. this._copy.uvs.z = 1;
  52488. this._copy.uvs.w = 1;
  52489. this._copy.color = null;
  52490. };
  52491. // _meshBuilder : inserts the shape model in the global SPS mesh
  52492. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  52493. var i;
  52494. var u = 0;
  52495. var c = 0;
  52496. var n = 0;
  52497. this._resetCopy();
  52498. if (options && options.positionFunction) {
  52499. options.positionFunction(this._copy, idx, idxInShape);
  52500. this._mustUnrotateFixedNormals = true;
  52501. }
  52502. if (this._copy.rotationQuaternion) {
  52503. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52504. }
  52505. else {
  52506. this._yaw = this._copy.rotation.y;
  52507. this._pitch = this._copy.rotation.x;
  52508. this._roll = this._copy.rotation.z;
  52509. this._quaternionRotationYPR();
  52510. }
  52511. this._quaternionToRotationMatrix();
  52512. for (i = 0; i < shape.length; i++) {
  52513. this._vertex.x = shape[i].x;
  52514. this._vertex.y = shape[i].y;
  52515. this._vertex.z = shape[i].z;
  52516. if (options && options.vertexFunction) {
  52517. options.vertexFunction(this._copy, this._vertex, i);
  52518. }
  52519. this._vertex.x *= this._copy.scaling.x;
  52520. this._vertex.y *= this._copy.scaling.y;
  52521. this._vertex.z *= this._copy.scaling.z;
  52522. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52523. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  52524. if (meshUV) {
  52525. 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);
  52526. u += 2;
  52527. }
  52528. if (this._copy.color) {
  52529. this._color = this._copy.color;
  52530. }
  52531. else if (meshCol && meshCol[c] !== undefined) {
  52532. this._color.r = meshCol[c];
  52533. this._color.g = meshCol[c + 1];
  52534. this._color.b = meshCol[c + 2];
  52535. this._color.a = meshCol[c + 3];
  52536. }
  52537. else {
  52538. this._color.r = 1;
  52539. this._color.g = 1;
  52540. this._color.b = 1;
  52541. this._color.a = 1;
  52542. }
  52543. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  52544. c += 4;
  52545. if (!this.recomputeNormals && meshNor) {
  52546. this._normal.x = meshNor[n];
  52547. this._normal.y = meshNor[n + 1];
  52548. this._normal.z = meshNor[n + 2];
  52549. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  52550. normals.push(this._normal.x, this._normal.y, this._normal.z);
  52551. n += 3;
  52552. }
  52553. }
  52554. for (i = 0; i < meshInd.length; i++) {
  52555. indices.push(p + meshInd[i]);
  52556. }
  52557. if (this._pickable) {
  52558. var nbfaces = meshInd.length / 3;
  52559. for (i = 0; i < nbfaces; i++) {
  52560. this.pickedParticles.push({ idx: idx, faceId: i });
  52561. }
  52562. }
  52563. return this._copy;
  52564. };
  52565. // returns a shape array from positions array
  52566. SolidParticleSystem.prototype._posToShape = function (positions) {
  52567. var shape = [];
  52568. for (var i = 0; i < positions.length; i += 3) {
  52569. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  52570. }
  52571. return shape;
  52572. };
  52573. // returns a shapeUV array from a Vector4 uvs
  52574. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  52575. var shapeUV = [];
  52576. if (uvs) {
  52577. for (var i = 0; i < uvs.length; i++)
  52578. shapeUV.push(uvs[i]);
  52579. }
  52580. return shapeUV;
  52581. };
  52582. // adds a new particle object in the particles array
  52583. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  52584. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  52585. this.particles.push(sp);
  52586. return sp;
  52587. };
  52588. /**
  52589. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52590. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52591. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  52592. * `nb` (positive integer) the number of particles to be created from this model
  52593. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  52594. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  52595. */
  52596. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52597. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52598. var meshInd = mesh.getIndices();
  52599. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52600. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52601. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52602. var bbInfo;
  52603. if (this._particlesIntersect) {
  52604. bbInfo = mesh.getBoundingInfo();
  52605. }
  52606. var shape = this._posToShape(meshPos);
  52607. var shapeUV = this._uvsToShapeUV(meshUV);
  52608. var posfunc = options ? options.positionFunction : null;
  52609. var vtxfunc = options ? options.vertexFunction : null;
  52610. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  52611. // particles
  52612. var sp;
  52613. var currentCopy;
  52614. var idx = this.nbParticles;
  52615. for (var i = 0; i < nb; i++) {
  52616. var currentPos = this._positions.length;
  52617. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52618. if (this._updatable) {
  52619. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  52620. sp.position.copyFrom(currentCopy.position);
  52621. sp.rotation.copyFrom(currentCopy.rotation);
  52622. if (currentCopy.rotationQuaternion) {
  52623. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52624. }
  52625. if (currentCopy.color) {
  52626. sp.color.copyFrom(currentCopy.color);
  52627. }
  52628. sp.scaling.copyFrom(currentCopy.scaling);
  52629. sp.uvs.copyFrom(currentCopy.uvs);
  52630. }
  52631. this._index += shape.length;
  52632. idx++;
  52633. }
  52634. this.nbParticles += nb;
  52635. this._shapeCounter++;
  52636. return this._shapeCounter - 1;
  52637. };
  52638. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52639. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52640. this._resetCopy();
  52641. if (particle._model._positionFunction) {
  52642. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52643. }
  52644. if (this._copy.rotationQuaternion) {
  52645. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52646. }
  52647. else {
  52648. this._yaw = this._copy.rotation.y;
  52649. this._pitch = this._copy.rotation.x;
  52650. this._roll = this._copy.rotation.z;
  52651. this._quaternionRotationYPR();
  52652. }
  52653. this._quaternionToRotationMatrix();
  52654. this._shape = particle._model._shape;
  52655. for (var pt = 0; pt < this._shape.length; pt++) {
  52656. this._vertex.x = this._shape[pt].x;
  52657. this._vertex.y = this._shape[pt].y;
  52658. this._vertex.z = this._shape[pt].z;
  52659. if (particle._model._vertexFunction) {
  52660. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52661. }
  52662. this._vertex.x *= this._copy.scaling.x;
  52663. this._vertex.y *= this._copy.scaling.y;
  52664. this._vertex.z *= this._copy.scaling.z;
  52665. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52666. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52667. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52668. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52669. }
  52670. particle.position.x = 0.0;
  52671. particle.position.y = 0.0;
  52672. particle.position.z = 0.0;
  52673. particle.rotation.x = 0.0;
  52674. particle.rotation.y = 0.0;
  52675. particle.rotation.z = 0.0;
  52676. particle.rotationQuaternion = null;
  52677. particle.scaling.x = 1.0;
  52678. particle.scaling.y = 1.0;
  52679. particle.scaling.z = 1.0;
  52680. };
  52681. /**
  52682. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  52683. * Returns the SPS.
  52684. */
  52685. SolidParticleSystem.prototype.rebuildMesh = function () {
  52686. for (var p = 0; p < this.particles.length; p++) {
  52687. this._rebuildParticle(this.particles[p]);
  52688. }
  52689. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52690. return this;
  52691. };
  52692. /**
  52693. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  52694. * This method calls `updateParticle()` for each particle of the SPS.
  52695. * For an animated SPS, it is usually called within the render loop.
  52696. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  52697. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  52698. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  52699. * Returns the SPS.
  52700. */
  52701. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  52702. if (start === void 0) { start = 0; }
  52703. if (end === void 0) { end = this.nbParticles - 1; }
  52704. if (update === void 0) { update = true; }
  52705. if (!this._updatable) {
  52706. return;
  52707. }
  52708. // custom beforeUpdate
  52709. this.beforeUpdateParticles(start, end, update);
  52710. this._cam_axisX.x = 1.0;
  52711. this._cam_axisX.y = 0.0;
  52712. this._cam_axisX.z = 0.0;
  52713. this._cam_axisY.x = 0.0;
  52714. this._cam_axisY.y = 1.0;
  52715. this._cam_axisY.z = 0.0;
  52716. this._cam_axisZ.x = 0.0;
  52717. this._cam_axisZ.y = 0.0;
  52718. this._cam_axisZ.z = 1.0;
  52719. // if the particles will always face the camera
  52720. if (this.billboard) {
  52721. // compute the camera position and un-rotate it by the current mesh rotation
  52722. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  52723. this._quaternionToRotationMatrix();
  52724. this._rotMatrix.invertToRef(this._invertMatrix);
  52725. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  52726. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  52727. this._cam_axisZ.normalize();
  52728. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  52729. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  52730. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  52731. this._cam_axisY.normalize();
  52732. this._cam_axisX.normalize();
  52733. }
  52734. }
  52735. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  52736. var idx = 0; // current position index in the global array positions32
  52737. var index = 0; // position start index in the global array positions32 of the current particle
  52738. var colidx = 0; // current color index in the global array colors32
  52739. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  52740. var uvidx = 0; // current uv index in the global array uvs32
  52741. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  52742. var pt = 0; // current index in the particle model shape
  52743. if (this.mesh.isFacetDataEnabled) {
  52744. this._computeBoundingBox = true;
  52745. }
  52746. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  52747. if (this._computeBoundingBox) {
  52748. if (start == 0 && end == this.nbParticles - 1) {
  52749. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  52750. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  52751. }
  52752. else {
  52753. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  52754. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  52755. }
  52756. }
  52757. // particle loop
  52758. index = this.particles[start]._pos;
  52759. var vpos = (index / 3) | 0;
  52760. colorIndex = vpos * 4;
  52761. uvIndex = vpos * 2;
  52762. for (var p = start; p <= end; p++) {
  52763. this._particle = this.particles[p];
  52764. this._shape = this._particle._model._shape;
  52765. this._shapeUV = this._particle._model._shapeUV;
  52766. // call to custom user function to update the particle properties
  52767. this.updateParticle(this._particle);
  52768. if (this._particle.isVisible) {
  52769. // particle rotation matrix
  52770. if (this.billboard) {
  52771. this._particle.rotation.x = 0.0;
  52772. this._particle.rotation.y = 0.0;
  52773. }
  52774. if (this._computeParticleRotation || this.billboard) {
  52775. if (this._particle.rotationQuaternion) {
  52776. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52777. }
  52778. else {
  52779. this._yaw = this._particle.rotation.y;
  52780. this._pitch = this._particle.rotation.x;
  52781. this._roll = this._particle.rotation.z;
  52782. this._quaternionRotationYPR();
  52783. }
  52784. this._quaternionToRotationMatrix();
  52785. }
  52786. // particle vertex loop
  52787. for (pt = 0; pt < this._shape.length; pt++) {
  52788. idx = index + pt * 3;
  52789. colidx = colorIndex + pt * 4;
  52790. uvidx = uvIndex + pt * 2;
  52791. this._vertex.x = this._shape[pt].x;
  52792. this._vertex.y = this._shape[pt].y;
  52793. this._vertex.z = this._shape[pt].z;
  52794. if (this._computeParticleVertex) {
  52795. this.updateParticleVertex(this._particle, this._vertex, pt);
  52796. }
  52797. // positions
  52798. this._vertex.x *= this._particle.scaling.x;
  52799. this._vertex.y *= this._particle.scaling.y;
  52800. this._vertex.z *= this._particle.scaling.z;
  52801. 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];
  52802. 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;
  52803. 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;
  52804. 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;
  52805. 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;
  52806. 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;
  52807. 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;
  52808. if (this._computeBoundingBox) {
  52809. if (this._positions32[idx] < this._minimum.x) {
  52810. this._minimum.x = this._positions32[idx];
  52811. }
  52812. if (this._positions32[idx] > this._maximum.x) {
  52813. this._maximum.x = this._positions32[idx];
  52814. }
  52815. if (this._positions32[idx + 1] < this._minimum.y) {
  52816. this._minimum.y = this._positions32[idx + 1];
  52817. }
  52818. if (this._positions32[idx + 1] > this._maximum.y) {
  52819. this._maximum.y = this._positions32[idx + 1];
  52820. }
  52821. if (this._positions32[idx + 2] < this._minimum.z) {
  52822. this._minimum.z = this._positions32[idx + 2];
  52823. }
  52824. if (this._positions32[idx + 2] > this._maximum.z) {
  52825. this._maximum.z = this._positions32[idx + 2];
  52826. }
  52827. }
  52828. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  52829. if (!this._computeParticleVertex) {
  52830. this._normal.x = this._fixedNormal32[idx];
  52831. this._normal.y = this._fixedNormal32[idx + 1];
  52832. this._normal.z = this._fixedNormal32[idx + 2];
  52833. 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]);
  52834. 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]);
  52835. 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]);
  52836. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52837. 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;
  52838. 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;
  52839. }
  52840. if (this._computeParticleColor) {
  52841. this._colors32[colidx] = this._particle.color.r;
  52842. this._colors32[colidx + 1] = this._particle.color.g;
  52843. this._colors32[colidx + 2] = this._particle.color.b;
  52844. this._colors32[colidx + 3] = this._particle.color.a;
  52845. }
  52846. if (this._computeParticleTexture) {
  52847. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52848. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52849. }
  52850. }
  52851. }
  52852. else {
  52853. for (pt = 0; pt < this._shape.length; pt++) {
  52854. idx = index + pt * 3;
  52855. colidx = colorIndex + pt * 4;
  52856. uvidx = uvIndex + pt * 2;
  52857. this._positions32[idx] = this._camera.position.x;
  52858. this._positions32[idx + 1] = this._camera.position.y;
  52859. this._positions32[idx + 2] = this._camera.position.z;
  52860. this._normals32[idx] = 0.0;
  52861. this._normals32[idx + 1] = 0.0;
  52862. this._normals32[idx + 2] = 0.0;
  52863. if (this._computeParticleColor) {
  52864. this._colors32[colidx] = this._particle.color.r;
  52865. this._colors32[colidx + 1] = this._particle.color.g;
  52866. this._colors32[colidx + 2] = this._particle.color.b;
  52867. this._colors32[colidx + 3] = this._particle.color.a;
  52868. }
  52869. if (this._computeParticleTexture) {
  52870. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52871. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52872. }
  52873. }
  52874. }
  52875. // if the particle intersections must be computed : update the bbInfo
  52876. if (this._particlesIntersect) {
  52877. var bInfo = this._particle._boundingInfo;
  52878. var bBox = bInfo.boundingBox;
  52879. var bSphere = bInfo.boundingSphere;
  52880. if (!this._bSphereOnly) {
  52881. // place, scale and rotate the particle bbox within the SPS local system, then update it
  52882. for (var b = 0; b < bBox.vectors.length; b++) {
  52883. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  52884. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  52885. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  52886. 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];
  52887. 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;
  52888. 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;
  52889. 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;
  52890. 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;
  52891. 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;
  52892. 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;
  52893. }
  52894. bBox._update(this.mesh._worldMatrix);
  52895. }
  52896. // place and scale the particle bouding sphere in the SPS local system, then update it
  52897. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  52898. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  52899. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  52900. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  52901. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  52902. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  52903. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  52904. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  52905. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  52906. 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));
  52907. bSphere._update(this.mesh._worldMatrix);
  52908. }
  52909. // increment indexes for the next particle
  52910. index = idx + 3;
  52911. colorIndex = colidx + 4;
  52912. uvIndex = uvidx + 2;
  52913. }
  52914. // if the VBO must be updated
  52915. if (update) {
  52916. if (this._computeParticleColor) {
  52917. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  52918. }
  52919. if (this._computeParticleTexture) {
  52920. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  52921. }
  52922. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52923. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  52924. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  52925. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  52926. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  52927. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  52928. for (var i = 0; i < this._normals32.length; i++) {
  52929. this._fixedNormal32[i] = this._normals32[i];
  52930. }
  52931. }
  52932. if (!this.mesh.areNormalsFrozen) {
  52933. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  52934. }
  52935. }
  52936. }
  52937. if (this._computeBoundingBox) {
  52938. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  52939. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  52940. }
  52941. this.afterUpdateParticles(start, end, update);
  52942. return this;
  52943. };
  52944. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  52945. this._halfroll = this._roll * 0.5;
  52946. this._halfpitch = this._pitch * 0.5;
  52947. this._halfyaw = this._yaw * 0.5;
  52948. this._sinRoll = Math.sin(this._halfroll);
  52949. this._cosRoll = Math.cos(this._halfroll);
  52950. this._sinPitch = Math.sin(this._halfpitch);
  52951. this._cosPitch = Math.cos(this._halfpitch);
  52952. this._sinYaw = Math.sin(this._halfyaw);
  52953. this._cosYaw = Math.cos(this._halfyaw);
  52954. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  52955. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  52956. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  52957. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  52958. };
  52959. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  52960. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  52961. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  52962. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  52963. this._rotMatrix.m[3] = 0;
  52964. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  52965. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  52966. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  52967. this._rotMatrix.m[7] = 0;
  52968. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  52969. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  52970. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  52971. this._rotMatrix.m[11] = 0;
  52972. this._rotMatrix.m[12] = 0;
  52973. this._rotMatrix.m[13] = 0;
  52974. this._rotMatrix.m[14] = 0;
  52975. this._rotMatrix.m[15] = 1.0;
  52976. };
  52977. /**
  52978. * Disposes the SPS.
  52979. * Returns nothing.
  52980. */
  52981. SolidParticleSystem.prototype.dispose = function () {
  52982. this.mesh.dispose();
  52983. this.vars = null;
  52984. // drop references to internal big arrays for the GC
  52985. this._positions = null;
  52986. this._indices = null;
  52987. this._normals = null;
  52988. this._uvs = null;
  52989. this._colors = null;
  52990. this._positions32 = null;
  52991. this._normals32 = null;
  52992. this._fixedNormal32 = null;
  52993. this._uvs32 = null;
  52994. this._colors32 = null;
  52995. this.pickedParticles = null;
  52996. };
  52997. /**
  52998. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  52999. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53000. * Returns the SPS.
  53001. */
  53002. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53003. if (!this._isVisibilityBoxLocked) {
  53004. this.mesh.refreshBoundingInfo();
  53005. }
  53006. return this;
  53007. };
  53008. /**
  53009. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53010. * @param size the size (float) of the visibility box
  53011. * note : this doesn't lock the SPS mesh bounding box.
  53012. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53013. */
  53014. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53015. var vis = size / 2;
  53016. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53017. };
  53018. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53019. // getter and setter
  53020. get: function () {
  53021. return this._alwaysVisible;
  53022. },
  53023. /**
  53024. * Sets the SPS as always visible or not
  53025. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53026. */
  53027. set: function (val) {
  53028. this._alwaysVisible = val;
  53029. this.mesh.alwaysSelectAsActiveMesh = val;
  53030. },
  53031. enumerable: true,
  53032. configurable: true
  53033. });
  53034. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53035. get: function () {
  53036. return this._isVisibilityBoxLocked;
  53037. },
  53038. /**
  53039. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53040. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53041. */
  53042. set: function (val) {
  53043. this._isVisibilityBoxLocked = val;
  53044. this.mesh.getBoundingInfo().isLocked = val;
  53045. },
  53046. enumerable: true,
  53047. configurable: true
  53048. });
  53049. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53050. // getters
  53051. get: function () {
  53052. return this._computeParticleRotation;
  53053. },
  53054. // Optimizer setters
  53055. /**
  53056. * Tells to `setParticles()` to compute the particle rotations or not.
  53057. * Default value : true. The SPS is faster when it's set to false.
  53058. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53059. */
  53060. set: function (val) {
  53061. this._computeParticleRotation = val;
  53062. },
  53063. enumerable: true,
  53064. configurable: true
  53065. });
  53066. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53067. get: function () {
  53068. return this._computeParticleColor;
  53069. },
  53070. /**
  53071. * Tells to `setParticles()` to compute the particle colors or not.
  53072. * Default value : true. The SPS is faster when it's set to false.
  53073. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53074. */
  53075. set: function (val) {
  53076. this._computeParticleColor = val;
  53077. },
  53078. enumerable: true,
  53079. configurable: true
  53080. });
  53081. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53082. get: function () {
  53083. return this._computeParticleTexture;
  53084. },
  53085. /**
  53086. * Tells to `setParticles()` to compute the particle textures or not.
  53087. * Default value : true. The SPS is faster when it's set to false.
  53088. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53089. */
  53090. set: function (val) {
  53091. this._computeParticleTexture = val;
  53092. },
  53093. enumerable: true,
  53094. configurable: true
  53095. });
  53096. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53097. get: function () {
  53098. return this._computeParticleVertex;
  53099. },
  53100. /**
  53101. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53102. * Default value : false. The SPS is faster when it's set to false.
  53103. * Note : the particle custom vertex positions aren't stored values.
  53104. */
  53105. set: function (val) {
  53106. this._computeParticleVertex = val;
  53107. },
  53108. enumerable: true,
  53109. configurable: true
  53110. });
  53111. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53112. get: function () {
  53113. return this._computeBoundingBox;
  53114. },
  53115. /**
  53116. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53117. */
  53118. set: function (val) {
  53119. this._computeBoundingBox = val;
  53120. },
  53121. enumerable: true,
  53122. configurable: true
  53123. });
  53124. // =======================================================================
  53125. // Particle behavior logic
  53126. // these following methods may be overwritten by the user to fit his needs
  53127. /**
  53128. * This function does nothing. It may be overwritten to set all the particle first values.
  53129. * The SPS doesn't call this function, you may have to call it by your own.
  53130. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53131. */
  53132. SolidParticleSystem.prototype.initParticles = function () {
  53133. };
  53134. /**
  53135. * This function does nothing. It may be overwritten to recycle a particle.
  53136. * The SPS doesn't call this function, you may have to call it by your own.
  53137. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53138. */
  53139. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53140. return particle;
  53141. };
  53142. /**
  53143. * Updates a particle : this function should be overwritten by the user.
  53144. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53145. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53146. * ex : just set a particle position or velocity and recycle conditions
  53147. */
  53148. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53149. return particle;
  53150. };
  53151. /**
  53152. * Updates a vertex of a particle : it can be overwritten by the user.
  53153. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53154. * @param particle the current particle
  53155. * @param vertex the current index of the current particle
  53156. * @param pt the index of the current vertex in the particle shape
  53157. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53158. * ex : just set a vertex particle position
  53159. */
  53160. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53161. return vertex;
  53162. };
  53163. /**
  53164. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53165. * This does nothing and may be overwritten by the user.
  53166. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53167. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53168. * @param update the boolean update value actually passed to setParticles()
  53169. */
  53170. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53171. };
  53172. /**
  53173. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53174. * This will be passed three parameters.
  53175. * This does nothing and may be overwritten by the user.
  53176. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53177. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53178. * @param update the boolean update value actually passed to setParticles()
  53179. */
  53180. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53181. };
  53182. return SolidParticleSystem;
  53183. }());
  53184. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53185. })(BABYLON || (BABYLON = {}));
  53186. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53187. var BABYLON;
  53188. (function (BABYLON) {
  53189. var Internals;
  53190. (function (Internals) {
  53191. var FileFaceOrientation = (function () {
  53192. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  53193. this.name = name;
  53194. this.worldAxisForNormal = worldAxisForNormal;
  53195. this.worldAxisForFileX = worldAxisForFileX;
  53196. this.worldAxisForFileY = worldAxisForFileY;
  53197. }
  53198. return FileFaceOrientation;
  53199. }());
  53200. ;
  53201. /**
  53202. * Helper class dealing with the extraction of spherical polynomial dataArray
  53203. * from a cube map.
  53204. */
  53205. var CubeMapToSphericalPolynomialTools = (function () {
  53206. function CubeMapToSphericalPolynomialTools() {
  53207. }
  53208. /**
  53209. * Converts a cubemap to the according Spherical Polynomial data.
  53210. * This extracts the first 3 orders only as they are the only one used in the lighting.
  53211. *
  53212. * @param cubeInfo The Cube map to extract the information from.
  53213. * @return The Spherical Polynomial data.
  53214. */
  53215. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  53216. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  53217. var totalSolidAngle = 0.0;
  53218. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  53219. var du = 2.0 / cubeInfo.size;
  53220. var dv = du;
  53221. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  53222. var minUV = du * 0.5 - 1.0;
  53223. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  53224. var fileFace = this.FileFaces[faceIndex];
  53225. var dataArray = cubeInfo[fileFace.name];
  53226. var v = minUV;
  53227. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  53228. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  53229. // Because SP is still linear, so summation is fine in that basis.
  53230. for (var y = 0; y < cubeInfo.size; y++) {
  53231. var u = minUV;
  53232. for (var x = 0; x < cubeInfo.size; x++) {
  53233. // World direction (not normalised)
  53234. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  53235. worldDirection.normalize();
  53236. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  53237. if (1) {
  53238. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  53239. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  53240. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  53241. var color = new BABYLON.Color3(r, g, b);
  53242. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  53243. }
  53244. else {
  53245. if (faceIndex == 0) {
  53246. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53247. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53248. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53249. }
  53250. else if (faceIndex == 1) {
  53251. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53252. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53253. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53254. }
  53255. else if (faceIndex == 2) {
  53256. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53257. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53258. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53259. }
  53260. else if (faceIndex == 3) {
  53261. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53262. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53263. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53264. }
  53265. else if (faceIndex == 4) {
  53266. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53267. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53268. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53269. }
  53270. else if (faceIndex == 5) {
  53271. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53272. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53273. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53274. }
  53275. 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]);
  53276. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  53277. }
  53278. totalSolidAngle += deltaSolidAngle;
  53279. u += du;
  53280. }
  53281. v += dv;
  53282. }
  53283. }
  53284. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  53285. var correction = correctSolidAngle / totalSolidAngle;
  53286. sphericalHarmonics.scale(correction);
  53287. // Additionally scale by pi -- audit needed
  53288. sphericalHarmonics.scale(1.0 / Math.PI);
  53289. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  53290. };
  53291. return CubeMapToSphericalPolynomialTools;
  53292. }());
  53293. CubeMapToSphericalPolynomialTools.FileFaces = [
  53294. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  53295. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  53296. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  53297. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  53298. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  53299. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  53300. ];
  53301. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  53302. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53303. })(BABYLON || (BABYLON = {}));
  53304. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  53305. var BABYLON;
  53306. (function (BABYLON) {
  53307. var Internals;
  53308. (function (Internals) {
  53309. /**
  53310. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  53311. */
  53312. var PanoramaToCubeMapTools = (function () {
  53313. function PanoramaToCubeMapTools() {
  53314. }
  53315. /**
  53316. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  53317. *
  53318. * @param float32Array The source data.
  53319. * @param inputWidth The width of the input panorama.
  53320. * @param inputhHeight The height of the input panorama.
  53321. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  53322. * @return The cubemap data
  53323. */
  53324. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  53325. if (!float32Array) {
  53326. throw "ConvertPanoramaToCubemap: input cannot be null";
  53327. }
  53328. if (float32Array.length != inputWidth * inputHeight * 3) {
  53329. throw "ConvertPanoramaToCubemap: input size is wrong";
  53330. }
  53331. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  53332. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  53333. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  53334. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  53335. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  53336. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  53337. return {
  53338. front: textureFront,
  53339. back: textureBack,
  53340. left: textureLeft,
  53341. right: textureRight,
  53342. up: textureUp,
  53343. down: textureDown,
  53344. size: size
  53345. };
  53346. };
  53347. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  53348. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  53349. var textureArray = new Float32Array(buffer);
  53350. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  53351. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  53352. var dy = 1 / texSize;
  53353. var fy = 0;
  53354. for (var y = 0; y < texSize; y++) {
  53355. var xv1 = faceData[0];
  53356. var xv2 = faceData[2];
  53357. for (var x = 0; x < texSize; x++) {
  53358. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  53359. v.normalize();
  53360. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  53361. // 3 channels per pixels
  53362. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  53363. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  53364. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  53365. xv1 = xv1.add(rotDX1);
  53366. xv2 = xv2.add(rotDX2);
  53367. }
  53368. fy += dy;
  53369. }
  53370. return textureArray;
  53371. };
  53372. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  53373. var theta = Math.atan2(vDir.z, vDir.x);
  53374. var phi = Math.acos(vDir.y);
  53375. while (theta < -Math.PI)
  53376. theta += 2 * Math.PI;
  53377. while (theta > Math.PI)
  53378. theta -= 2 * Math.PI;
  53379. var dx = theta / Math.PI;
  53380. var dy = phi / Math.PI;
  53381. // recenter.
  53382. dx = dx * 0.5 + 0.5;
  53383. var px = Math.round(dx * inputWidth);
  53384. if (px < 0)
  53385. px = 0;
  53386. else if (px >= inputWidth)
  53387. px = inputWidth - 1;
  53388. var py = Math.round(dy * inputHeight);
  53389. if (py < 0)
  53390. py = 0;
  53391. else if (py >= inputHeight)
  53392. py = inputHeight - 1;
  53393. var inputY = (inputHeight - py - 1);
  53394. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  53395. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  53396. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  53397. return {
  53398. r: r,
  53399. g: g,
  53400. b: b
  53401. };
  53402. };
  53403. return PanoramaToCubeMapTools;
  53404. }());
  53405. PanoramaToCubeMapTools.FACE_FRONT = [
  53406. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  53407. new BABYLON.Vector3(1.0, -1.0, -1.0),
  53408. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  53409. new BABYLON.Vector3(1.0, 1.0, -1.0)
  53410. ];
  53411. PanoramaToCubeMapTools.FACE_BACK = [
  53412. new BABYLON.Vector3(1.0, -1.0, 1.0),
  53413. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  53414. new BABYLON.Vector3(1.0, 1.0, 1.0),
  53415. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  53416. ];
  53417. PanoramaToCubeMapTools.FACE_RIGHT = [
  53418. new BABYLON.Vector3(1.0, -1.0, -1.0),
  53419. new BABYLON.Vector3(1.0, -1.0, 1.0),
  53420. new BABYLON.Vector3(1.0, 1.0, -1.0),
  53421. new BABYLON.Vector3(1.0, 1.0, 1.0)
  53422. ];
  53423. PanoramaToCubeMapTools.FACE_LEFT = [
  53424. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  53425. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  53426. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  53427. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  53428. ];
  53429. PanoramaToCubeMapTools.FACE_DOWN = [
  53430. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  53431. new BABYLON.Vector3(1.0, 1.0, -1.0),
  53432. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  53433. new BABYLON.Vector3(1.0, 1.0, 1.0)
  53434. ];
  53435. PanoramaToCubeMapTools.FACE_UP = [
  53436. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  53437. new BABYLON.Vector3(1.0, -1.0, 1.0),
  53438. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  53439. new BABYLON.Vector3(1.0, -1.0, -1.0)
  53440. ];
  53441. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  53442. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53443. })(BABYLON || (BABYLON = {}));
  53444. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  53445. var BABYLON;
  53446. (function (BABYLON) {
  53447. var Internals;
  53448. (function (Internals) {
  53449. ;
  53450. /**
  53451. * This groups tools to convert HDR texture to native colors array.
  53452. */
  53453. var HDRTools = (function () {
  53454. function HDRTools() {
  53455. }
  53456. HDRTools.Ldexp = function (mantissa, exponent) {
  53457. if (exponent > 1023) {
  53458. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  53459. }
  53460. if (exponent < -1074) {
  53461. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  53462. }
  53463. return mantissa * Math.pow(2, exponent);
  53464. };
  53465. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  53466. if (exponent > 0) {
  53467. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  53468. float32array[index + 0] = red * exponent;
  53469. float32array[index + 1] = green * exponent;
  53470. float32array[index + 2] = blue * exponent;
  53471. }
  53472. else {
  53473. float32array[index + 0] = 0;
  53474. float32array[index + 1] = 0;
  53475. float32array[index + 2] = 0;
  53476. }
  53477. };
  53478. HDRTools.readStringLine = function (uint8array, startIndex) {
  53479. var line = "";
  53480. var character = "";
  53481. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  53482. character = String.fromCharCode(uint8array[i]);
  53483. if (character == "\n") {
  53484. break;
  53485. }
  53486. line += character;
  53487. }
  53488. return line;
  53489. };
  53490. /**
  53491. * Reads header information from an RGBE texture stored in a native array.
  53492. * More information on this format are available here:
  53493. * https://en.wikipedia.org/wiki/RGBE_image_format
  53494. *
  53495. * @param uint8array The binary file stored in native array.
  53496. * @return The header information.
  53497. */
  53498. HDRTools.RGBE_ReadHeader = function (uint8array) {
  53499. var height = 0;
  53500. var width = 0;
  53501. var line = this.readStringLine(uint8array, 0);
  53502. if (line[0] != '#' || line[1] != '?') {
  53503. throw "Bad HDR Format.";
  53504. }
  53505. var endOfHeader = false;
  53506. var findFormat = false;
  53507. var lineIndex = 0;
  53508. do {
  53509. lineIndex += (line.length + 1);
  53510. line = this.readStringLine(uint8array, lineIndex);
  53511. if (line == "FORMAT=32-bit_rle_rgbe") {
  53512. findFormat = true;
  53513. }
  53514. else if (line.length == 0) {
  53515. endOfHeader = true;
  53516. }
  53517. } while (!endOfHeader);
  53518. if (!findFormat) {
  53519. throw "HDR Bad header format, unsupported FORMAT";
  53520. }
  53521. lineIndex += (line.length + 1);
  53522. line = this.readStringLine(uint8array, lineIndex);
  53523. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  53524. var match = sizeRegexp.exec(line);
  53525. // TODO. Support +Y and -X if needed.
  53526. if (match.length < 3) {
  53527. throw "HDR Bad header format, no size";
  53528. }
  53529. width = parseInt(match[2]);
  53530. height = parseInt(match[1]);
  53531. if (width < 8 || width > 0x7fff) {
  53532. throw "HDR Bad header format, unsupported size";
  53533. }
  53534. lineIndex += (line.length + 1);
  53535. return {
  53536. height: height,
  53537. width: width,
  53538. dataPosition: lineIndex
  53539. };
  53540. };
  53541. /**
  53542. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  53543. * This RGBE texture needs to store the information as a panorama.
  53544. *
  53545. * More information on this format are available here:
  53546. * https://en.wikipedia.org/wiki/RGBE_image_format
  53547. *
  53548. * @param buffer The binary file stored in an array buffer.
  53549. * @param size The expected size of the extracted cubemap.
  53550. * @return The Cube Map information.
  53551. */
  53552. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  53553. var uint8array = new Uint8Array(buffer);
  53554. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  53555. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  53556. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  53557. return cubeMapData;
  53558. };
  53559. /**
  53560. * Returns the pixels data extracted from an RGBE texture.
  53561. * This pixels will be stored left to right up to down in the R G B order in one array.
  53562. *
  53563. * More information on this format are available here:
  53564. * https://en.wikipedia.org/wiki/RGBE_image_format
  53565. *
  53566. * @param uint8array The binary file stored in an array buffer.
  53567. * @param hdrInfo The header information of the file.
  53568. * @return The pixels data in RGB right to left up to down order.
  53569. */
  53570. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  53571. // Keep for multi format supports.
  53572. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  53573. };
  53574. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  53575. var num_scanlines = hdrInfo.height;
  53576. var scanline_width = hdrInfo.width;
  53577. var a, b, c, d, count;
  53578. var dataIndex = hdrInfo.dataPosition;
  53579. var index = 0, endIndex = 0, i = 0;
  53580. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  53581. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  53582. // 3 channels of 4 bytes per pixel in float.
  53583. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  53584. var resultArray = new Float32Array(resultBuffer);
  53585. // read in each successive scanline
  53586. while (num_scanlines > 0) {
  53587. a = uint8array[dataIndex++];
  53588. b = uint8array[dataIndex++];
  53589. c = uint8array[dataIndex++];
  53590. d = uint8array[dataIndex++];
  53591. if (a != 2 || b != 2 || (c & 0x80)) {
  53592. // this file is not run length encoded
  53593. throw "HDR Bad header format, not RLE";
  53594. }
  53595. if (((c << 8) | d) != scanline_width) {
  53596. throw "HDR Bad header format, wrong scan line width";
  53597. }
  53598. index = 0;
  53599. // read each of the four channels for the scanline into the buffer
  53600. for (i = 0; i < 4; i++) {
  53601. endIndex = (i + 1) * scanline_width;
  53602. while (index < endIndex) {
  53603. a = uint8array[dataIndex++];
  53604. b = uint8array[dataIndex++];
  53605. if (a > 128) {
  53606. // a run of the same value
  53607. count = a - 128;
  53608. if ((count == 0) || (count > endIndex - index)) {
  53609. throw "HDR Bad Format, bad scanline data (run)";
  53610. }
  53611. while (count-- > 0) {
  53612. scanLineArray[index++] = b;
  53613. }
  53614. }
  53615. else {
  53616. // a non-run
  53617. count = a;
  53618. if ((count == 0) || (count > endIndex - index)) {
  53619. throw "HDR Bad Format, bad scanline data (non-run)";
  53620. }
  53621. scanLineArray[index++] = b;
  53622. if (--count > 0) {
  53623. for (var j = 0; j < count; j++) {
  53624. scanLineArray[index++] = uint8array[dataIndex++];
  53625. }
  53626. }
  53627. }
  53628. }
  53629. }
  53630. // now convert data from buffer into floats
  53631. for (i = 0; i < scanline_width; i++) {
  53632. a = scanLineArray[i];
  53633. b = scanLineArray[i + scanline_width];
  53634. c = scanLineArray[i + 2 * scanline_width];
  53635. d = scanLineArray[i + 3 * scanline_width];
  53636. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  53637. }
  53638. num_scanlines--;
  53639. }
  53640. return resultArray;
  53641. };
  53642. return HDRTools;
  53643. }());
  53644. Internals.HDRTools = HDRTools;
  53645. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53646. })(BABYLON || (BABYLON = {}));
  53647. //# sourceMappingURL=babylon.tools.hdr.js.map
  53648. //_______________________________________________________________
  53649. // Extracted from CubeMapGen:
  53650. // https://code.google.com/archive/p/cubemapgen/
  53651. //
  53652. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  53653. //_______________________________________________________________
  53654. var BABYLON;
  53655. (function (BABYLON) {
  53656. var Internals;
  53657. (function (Internals) {
  53658. /**
  53659. * The bounding box information used during the conversion process.
  53660. */
  53661. var CMGBoundinBox = (function () {
  53662. function CMGBoundinBox() {
  53663. this.min = new BABYLON.Vector3(0, 0, 0);
  53664. this.max = new BABYLON.Vector3(0, 0, 0);
  53665. this.clear();
  53666. }
  53667. CMGBoundinBox.prototype.clear = function () {
  53668. this.min.x = CMGBoundinBox.MAX;
  53669. this.min.y = CMGBoundinBox.MAX;
  53670. this.min.z = CMGBoundinBox.MAX;
  53671. this.max.x = CMGBoundinBox.MIN;
  53672. this.max.y = CMGBoundinBox.MIN;
  53673. this.max.z = CMGBoundinBox.MIN;
  53674. };
  53675. CMGBoundinBox.prototype.augment = function (x, y, z) {
  53676. this.min.x = Math.min(this.min.x, x);
  53677. this.min.y = Math.min(this.min.y, y);
  53678. this.min.z = Math.min(this.min.z, z);
  53679. this.max.x = Math.max(this.max.x, x);
  53680. this.max.y = Math.max(this.max.y, y);
  53681. this.max.z = Math.max(this.max.z, z);
  53682. };
  53683. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  53684. this.min.x = Math.max(this.min.x, x);
  53685. this.min.y = Math.max(this.min.y, y);
  53686. this.min.z = Math.max(this.min.z, z);
  53687. };
  53688. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  53689. this.max.x = Math.min(this.max.x, x);
  53690. this.max.y = Math.min(this.max.y, y);
  53691. this.max.z = Math.min(this.max.z, z);
  53692. };
  53693. CMGBoundinBox.prototype.empty = function () {
  53694. if ((this.min.x > this.max.y) ||
  53695. (this.min.y > this.max.y) ||
  53696. (this.min.z > this.max.y)) {
  53697. return true;
  53698. }
  53699. else {
  53700. return false;
  53701. }
  53702. };
  53703. return CMGBoundinBox;
  53704. }());
  53705. CMGBoundinBox.MAX = Number.MAX_VALUE;
  53706. CMGBoundinBox.MIN = Number.MIN_VALUE;
  53707. /**
  53708. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  53709. * required by the glossinees of a material.
  53710. *
  53711. * This only supports the cosine drop power as well as Warp fixup generation method.
  53712. *
  53713. * This is using the process from CubeMapGen described here:
  53714. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  53715. */
  53716. var PMREMGenerator = (function () {
  53717. /**
  53718. * Constructor of the generator.
  53719. *
  53720. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  53721. * @param inputSize The size of the cubemap faces
  53722. * @param outputSize The size of the output cubemap faces
  53723. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  53724. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  53725. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  53726. * @param specularPower The max specular level of the desired cubemap
  53727. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  53728. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  53729. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  53730. */
  53731. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  53732. this.input = input;
  53733. this.inputSize = inputSize;
  53734. this.outputSize = outputSize;
  53735. this.maxNumMipLevels = maxNumMipLevels;
  53736. this.numChannels = numChannels;
  53737. this.isFloat = isFloat;
  53738. this.specularPower = specularPower;
  53739. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  53740. this.excludeBase = excludeBase;
  53741. this.fixup = fixup;
  53742. this._outputSurface = [];
  53743. this._numMipLevels = 0;
  53744. }
  53745. /**
  53746. * Launches the filter process and return the result.
  53747. *
  53748. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  53749. */
  53750. PMREMGenerator.prototype.filterCubeMap = function () {
  53751. // Init cubemap processor
  53752. this.init();
  53753. // Filters the cubemap
  53754. this.filterCubeMapMipChain();
  53755. // Returns the filtered mips.
  53756. return this._outputSurface;
  53757. };
  53758. PMREMGenerator.prototype.init = function () {
  53759. var i;
  53760. var j;
  53761. var mipLevelSize;
  53762. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  53763. if (this.maxNumMipLevels == 0) {
  53764. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  53765. }
  53766. //first miplevel size
  53767. mipLevelSize = this.outputSize;
  53768. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  53769. for (j = 0; j < this.maxNumMipLevels; j++) {
  53770. this._outputSurface.length++;
  53771. this._outputSurface[j] = [];
  53772. //Iterate over faces for output images
  53773. for (i = 0; i < 6; i++) {
  53774. this._outputSurface[j].length++;
  53775. // Initializes a new array for the output.
  53776. if (this.isFloat) {
  53777. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  53778. }
  53779. else {
  53780. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  53781. }
  53782. }
  53783. //next mip level is half size
  53784. mipLevelSize >>= 1;
  53785. this._numMipLevels++;
  53786. //terminate if mip chain becomes too small
  53787. if (mipLevelSize == 0) {
  53788. this.maxNumMipLevels = j;
  53789. return;
  53790. }
  53791. }
  53792. };
  53793. //--------------------------------------------------------------------------------------
  53794. //Cube map filtering and mip chain generation.
  53795. // the cube map filtereing is specified using a number of parameters:
  53796. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  53797. // indicates the region of the hemisphere to filter over for each tap.
  53798. //
  53799. // Note that the top mip level is also a filtered version of the original input images
  53800. // as well in order to create mip chains for diffuse environment illumination.
  53801. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  53802. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  53803. //
  53804. // Then the mip angle used to genreate the next level of the mip chain from the first level
  53805. // is a_InitialMipAngle
  53806. //
  53807. // The angle for the subsequent levels of the mip chain are specified by their parents
  53808. // filtering angle and a per-level scale and bias
  53809. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  53810. //
  53811. //--------------------------------------------------------------------------------------
  53812. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  53813. // First, take count of the lighting model to modify SpecularPower
  53814. // 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;
  53815. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  53816. //Cone angle start (for generating subsequent mip levels)
  53817. var currentSpecularPower = this.specularPower;
  53818. //Build filter lookup tables based on the source miplevel size
  53819. this.precomputeFilterLookupTables(this.inputSize);
  53820. // Note that we need to filter the first level before generating mipmap
  53821. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  53822. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  53823. // TODO : Write a function to copy and scale the base mipmap in output
  53824. // I am just lazy here and just put a high specular power value, and do some if.
  53825. if (this.excludeBase && (levelIndex == 0)) {
  53826. // 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).
  53827. currentSpecularPower = 100000.0;
  53828. }
  53829. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  53830. var srcCubeImage = this.input;
  53831. var dstCubeImage = this._outputSurface[levelIndex];
  53832. var dstSize = this.outputSize >> levelIndex;
  53833. // Compute required angle.
  53834. var angle = this.getBaseFilterAngle(currentSpecularPower);
  53835. // filter cube surfaces
  53836. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  53837. // fix seams
  53838. if (this.fixup) {
  53839. this.fixupCubeEdges(dstCubeImage, dstSize);
  53840. }
  53841. // Decrease the specular power to generate the mipmap chain
  53842. // TODO : Use another method for Exclude (see first comment at start of the function
  53843. if (this.excludeBase && (levelIndex == 0)) {
  53844. currentSpecularPower = this.specularPower;
  53845. }
  53846. currentSpecularPower *= this.cosinePowerDropPerMip;
  53847. }
  53848. };
  53849. //--------------------------------------------------------------------------------------
  53850. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  53851. // It allow to optimize the texel to access base on the specular power.
  53852. //--------------------------------------------------------------------------------------
  53853. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  53854. // We want to find the alpha such that:
  53855. // cos(alpha)^cosinePower = epsilon
  53856. // That's: acos(epsilon^(1/cosinePower))
  53857. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  53858. var angle = 180.0;
  53859. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  53860. angle *= 180.0 / Math.PI; // Convert to degree
  53861. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  53862. return angle;
  53863. };
  53864. //--------------------------------------------------------------------------------------
  53865. //Builds the following lookup tables prior to filtering:
  53866. // -normalizer cube map
  53867. // -tap weight lookup table
  53868. //
  53869. //--------------------------------------------------------------------------------------
  53870. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  53871. var srcTexelAngle;
  53872. var iCubeFace;
  53873. //clear pre-existing normalizer cube map
  53874. this._normCubeMap = [];
  53875. //Normalized vectors per cubeface and per-texel solid angle
  53876. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  53877. };
  53878. //--------------------------------------------------------------------------------------
  53879. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  53880. //
  53881. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  53882. //
  53883. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  53884. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  53885. // below
  53886. //--------------------------------------------------------------------------------------
  53887. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  53888. var iCubeFace;
  53889. var u;
  53890. var v;
  53891. //iterate over cube faces
  53892. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  53893. //First three channels for norm cube, and last channel for solid angle
  53894. this._normCubeMap.push(new Float32Array(size * size * 4));
  53895. //fast texture walk, build normalizer cube map
  53896. var facesData = this.input[iCubeFace];
  53897. for (v = 0; v < size; v++) {
  53898. for (u = 0; u < size; u++) {
  53899. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  53900. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  53901. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  53902. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  53903. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  53904. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  53905. }
  53906. }
  53907. }
  53908. };
  53909. //--------------------------------------------------------------------------------------
  53910. // Convert cubemap face texel coordinates and face idx to 3D vector
  53911. // note the U and V coords are integer coords and range from 0 to size-1
  53912. // this routine can be used to generate a normalizer cube map
  53913. //--------------------------------------------------------------------------------------
  53914. // SL BEGIN
  53915. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  53916. var nvcU;
  53917. var nvcV;
  53918. var tempVec;
  53919. // Change from original AMD code
  53920. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  53921. // + 0.5f is for texel center addressing
  53922. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  53923. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  53924. // warp fixup
  53925. if (fixup && size > 1) {
  53926. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  53927. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  53928. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  53929. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  53930. }
  53931. // Get current vector
  53932. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  53933. // U contribution
  53934. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  53935. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  53936. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  53937. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  53938. // V contribution and Sum
  53939. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  53940. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  53941. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  53942. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  53943. //add face axis
  53944. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  53945. PMREMGenerator._vectorTemp.x += faceAxis[0];
  53946. PMREMGenerator._vectorTemp.y += faceAxis[1];
  53947. PMREMGenerator._vectorTemp.z += faceAxis[2];
  53948. //normalize vector
  53949. PMREMGenerator._vectorTemp.normalize();
  53950. return PMREMGenerator._vectorTemp;
  53951. };
  53952. //--------------------------------------------------------------------------------------
  53953. // Convert 3D vector to cubemap face texel coordinates and face idx
  53954. // note the U and V coords are integer coords and range from 0 to size-1
  53955. // this routine can be used to generate a normalizer cube map
  53956. //
  53957. // returns face IDX and texel coords
  53958. //--------------------------------------------------------------------------------------
  53959. // SL BEGIN
  53960. /*
  53961. Mapping Texture Coordinates to Cube Map Faces
  53962. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  53963. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  53964. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  53965. map arrangement in Pixar's RenderMan package.
  53966. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  53967. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  53968. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  53969. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  53970. the major axis direction). The target column in the table below explains how the major axis direction
  53971. maps to the 2D image of a particular cube map target.
  53972. major axis
  53973. direction target sc tc ma
  53974. ---------- --------------------------------- --- --- ---
  53975. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  53976. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  53977. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  53978. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  53979. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  53980. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  53981. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  53982. an updated (s,t) is calculated as follows
  53983. s = ( sc/|ma| + 1 ) / 2
  53984. t = ( tc/|ma| + 1 ) / 2
  53985. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  53986. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  53987. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  53988. */
  53989. // Note this method return U and V in range from 0 to size-1
  53990. // SL END
  53991. // Store the information in vector3 for convenience (faceindex, u, v)
  53992. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  53993. var maxCoord;
  53994. var faceIdx;
  53995. //absolute value 3
  53996. var absX = Math.abs(x);
  53997. var absY = Math.abs(y);
  53998. var absZ = Math.abs(z);
  53999. if (absX >= absY && absX >= absZ) {
  54000. maxCoord = absX;
  54001. if (x >= 0) {
  54002. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  54003. }
  54004. else {
  54005. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  54006. }
  54007. }
  54008. else if (absY >= absX && absY >= absZ) {
  54009. maxCoord = absY;
  54010. if (y >= 0) {
  54011. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  54012. }
  54013. else {
  54014. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  54015. }
  54016. }
  54017. else {
  54018. maxCoord = absZ;
  54019. if (z >= 0) {
  54020. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  54021. }
  54022. else {
  54023. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  54024. }
  54025. }
  54026. //divide through by max coord so face vector lies on cube face
  54027. var scale = 1 / maxCoord;
  54028. x *= scale;
  54029. y *= scale;
  54030. z *= scale;
  54031. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  54032. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  54033. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  54034. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  54035. // Modify original AMD code to return value from 0 to Size - 1
  54036. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  54037. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  54038. PMREMGenerator._vectorTemp.x = faceIdx;
  54039. PMREMGenerator._vectorTemp.y = u;
  54040. PMREMGenerator._vectorTemp.z = v;
  54041. return PMREMGenerator._vectorTemp;
  54042. };
  54043. //--------------------------------------------------------------------------------------
  54044. //Original code from Ignacio CastaÒo
  54045. // This formula is from Manne ÷hrstrˆm's thesis.
  54046. // Take two coordiantes in the range [-1, 1] that define a portion of a
  54047. // cube face and return the area of the projection of that portion on the
  54048. // surface of the sphere.
  54049. //--------------------------------------------------------------------------------------
  54050. PMREMGenerator.prototype.areaElement = function (x, y) {
  54051. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  54052. };
  54053. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  54054. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  54055. // (+ 0.5f is for texel center addressing)
  54056. u = (2.0 * (u + 0.5) / size) - 1.0;
  54057. v = (2.0 * (v + 0.5) / size) - 1.0;
  54058. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  54059. var invResolution = 1.0 / size;
  54060. // U and V are the -1..1 texture coordinate on the current face.
  54061. // Get projected area for this texel
  54062. var x0 = u - invResolution;
  54063. var y0 = v - invResolution;
  54064. var x1 = u + invResolution;
  54065. var y1 = v + invResolution;
  54066. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  54067. return solidAngle;
  54068. };
  54069. //--------------------------------------------------------------------------------------
  54070. //The key to the speed of these filtering routines is to quickly define a per-face
  54071. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  54072. // Later these pixels are selectively processed based on their dot products to see if
  54073. // they reside within the filtering cone.
  54074. //
  54075. //This is done by computing the smallest per-texel angle to get a conservative estimate
  54076. // of the number of texels needed to be covered in width and height order to filter the
  54077. // region. the bounding box for the center taps face is defined first, and if the
  54078. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  54079. // defined next
  54080. //--------------------------------------------------------------------------------------
  54081. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  54082. // note that pixels within these regions may be rejected
  54083. // based on the anlge
  54084. var iCubeFace;
  54085. var u;
  54086. var v;
  54087. // bounding box per face to specify region to process
  54088. var filterExtents = [];
  54089. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  54090. filterExtents.push(new CMGBoundinBox());
  54091. }
  54092. // min angle a src texel can cover (in degrees)
  54093. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  54094. // angle about center tap to define filter cone
  54095. // filter angle is 1/2 the cone angle
  54096. var filterAngle = filterConeAngle / 2.0;
  54097. //ensure filter angle is larger than a texel
  54098. if (filterAngle < srcTexelAngle) {
  54099. filterAngle = srcTexelAngle;
  54100. }
  54101. //ensure filter cone is always smaller than the hemisphere
  54102. if (filterAngle > 90.0) {
  54103. filterAngle = 90.0;
  54104. }
  54105. // the maximum number of texels in 1D the filter cone angle will cover
  54106. // used to determine bounding box size for filter extents
  54107. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  54108. // ensure conservative region always covers at least one texel
  54109. if (filterSize < 1) {
  54110. filterSize = 1;
  54111. }
  54112. // dotProdThresh threshold based on cone angle to determine whether or not taps
  54113. // reside within the cone angle
  54114. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  54115. // process required faces
  54116. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  54117. //iterate over dst cube map face texel
  54118. for (v = 0; v < dstSize; v++) {
  54119. for (u = 0; u < dstSize; u++) {
  54120. //get center tap direction
  54121. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  54122. //clear old per-face filter extents
  54123. this.clearFilterExtents(filterExtents);
  54124. //define per-face filter extents
  54125. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  54126. //perform filtering of src faces using filter extents
  54127. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  54128. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  54129. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  54130. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  54131. }
  54132. }
  54133. }
  54134. };
  54135. //--------------------------------------------------------------------------------------
  54136. //Clear filter extents for the 6 cube map faces
  54137. //--------------------------------------------------------------------------------------
  54138. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  54139. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  54140. filterExtents[iCubeFaces].clear();
  54141. }
  54142. };
  54143. //--------------------------------------------------------------------------------------
  54144. //Define per-face bounding box filter extents
  54145. //
  54146. // These define conservative texel regions in each of the faces the filter can possibly
  54147. // process. When the pixels in the regions are actually processed, the dot product
  54148. // between the tap vector and the center tap vector is used to determine the weight of
  54149. // the tap and whether or not the tap is within the cone.
  54150. //
  54151. //--------------------------------------------------------------------------------------
  54152. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  54153. //neighboring face and bleed over amount, and width of BBOX for
  54154. // left, right, top, and bottom edges of this face
  54155. var bleedOverAmount = [0, 0, 0, 0];
  54156. var bleedOverBBoxMin = [0, 0, 0, 0];
  54157. var bleedOverBBoxMax = [0, 0, 0, 0];
  54158. var neighborFace;
  54159. var neighborEdge;
  54160. var oppositeFaceIdx;
  54161. //get face idx, and u, v info from center tap dir
  54162. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  54163. var faceIdx = result.x;
  54164. var u = result.y;
  54165. var v = result.z;
  54166. //define bbox size within face
  54167. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  54168. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  54169. filterExtents[faceIdx].clampMin(0, 0, 0);
  54170. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  54171. //u and v extent in face corresponding to center tap
  54172. var minU = filterExtents[faceIdx].min.x;
  54173. var minV = filterExtents[faceIdx].min.y;
  54174. var maxU = filterExtents[faceIdx].max.x;
  54175. var maxV = filterExtents[faceIdx].max.y;
  54176. //bleed over amounts for face across u=0 edge (left)
  54177. bleedOverAmount[0] = (bboxSize - u);
  54178. bleedOverBBoxMin[0] = minV;
  54179. bleedOverBBoxMax[0] = maxV;
  54180. //bleed over amounts for face across u=1 edge (right)
  54181. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  54182. bleedOverBBoxMin[1] = minV;
  54183. bleedOverBBoxMax[1] = maxV;
  54184. //bleed over to face across v=0 edge (up)
  54185. bleedOverAmount[2] = (bboxSize - v);
  54186. bleedOverBBoxMin[2] = minU;
  54187. bleedOverBBoxMax[2] = maxU;
  54188. //bleed over to face across v=1 edge (down)
  54189. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  54190. bleedOverBBoxMin[3] = minU;
  54191. bleedOverBBoxMax[3] = maxU;
  54192. //compute bleed over regions in neighboring faces
  54193. for (var i = 0; i < 4; i++) {
  54194. if (bleedOverAmount[i] > 0) {
  54195. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  54196. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  54197. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  54198. // be flipped: the cases are
  54199. // if a left edge mates with a left or bottom edge on the neighbor
  54200. // if a top edge mates with a top or right edge on the neighbor
  54201. // if a right edge mates with a right or top edge on the neighbor
  54202. // if a bottom edge mates with a bottom or left edge on the neighbor
  54203. //Seeing as the edges are enumerated as follows
  54204. // left =0
  54205. // right =1
  54206. // top =2
  54207. // bottom =3
  54208. //
  54209. // so if the edge enums are the same, or the sum of the enums == 3,
  54210. // the bbox needs to be flipped
  54211. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  54212. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  54213. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  54214. }
  54215. //The way the bounding box is extended onto the neighboring face
  54216. // depends on which edge of neighboring face abuts with this one
  54217. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  54218. case PMREMGenerator.CP_EDGE_LEFT:
  54219. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  54220. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  54221. break;
  54222. case PMREMGenerator.CP_EDGE_RIGHT:
  54223. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  54224. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  54225. break;
  54226. case PMREMGenerator.CP_EDGE_TOP:
  54227. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  54228. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  54229. break;
  54230. case PMREMGenerator.CP_EDGE_BOTTOM:
  54231. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  54232. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  54233. break;
  54234. }
  54235. //clamp filter extents in non-center tap faces to remain within surface
  54236. filterExtents[neighborFace].clampMin(0, 0, 0);
  54237. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  54238. }
  54239. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  54240. // from the center tap face, then process the opposite face entirely for now.
  54241. //Note that the cases in which this happens, what usually happens is that
  54242. // more than one edge bleeds onto the opposite face, and the bounding box
  54243. // encompasses the entire cube map face.
  54244. if (bleedOverAmount[i] > srcSize) {
  54245. //determine opposite face
  54246. switch (faceIdx) {
  54247. case PMREMGenerator.CP_FACE_X_POS:
  54248. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  54249. break;
  54250. case PMREMGenerator.CP_FACE_X_NEG:
  54251. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  54252. break;
  54253. case PMREMGenerator.CP_FACE_Y_POS:
  54254. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  54255. break;
  54256. case PMREMGenerator.CP_FACE_Y_NEG:
  54257. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  54258. break;
  54259. case PMREMGenerator.CP_FACE_Z_POS:
  54260. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  54261. break;
  54262. case PMREMGenerator.CP_FACE_Z_NEG:
  54263. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  54264. break;
  54265. default:
  54266. break;
  54267. }
  54268. //just encompass entire face for now
  54269. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  54270. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  54271. }
  54272. }
  54273. };
  54274. //--------------------------------------------------------------------------------------
  54275. //ProcessFilterExtents
  54276. // Process bounding box in each cube face
  54277. //
  54278. //--------------------------------------------------------------------------------------
  54279. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  54280. //accumulators are 64-bit floats in order to have the precision needed
  54281. // over a summation of a large number of pixels
  54282. var dstAccum = [0, 0, 0, 0];
  54283. var weightAccum = 0;
  54284. var k = 0;
  54285. var nSrcChannels = this.numChannels;
  54286. // norm cube map and srcCubeMap have same face width
  54287. var faceWidth = srcSize;
  54288. //amount to add to pointer to move to next scanline in images
  54289. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  54290. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  54291. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  54292. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  54293. // iterate over cubefaces
  54294. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  54295. //if bbox is non empty
  54296. if (!filterExtents[iFaceIdx].empty()) {
  54297. var uStart = filterExtents[iFaceIdx].min.x;
  54298. var vStart = filterExtents[iFaceIdx].min.y;
  54299. var uEnd = filterExtents[iFaceIdx].max.x;
  54300. var vEnd = filterExtents[iFaceIdx].max.y;
  54301. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  54302. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  54303. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  54304. for (var v = vStart; v <= vEnd; v++) {
  54305. var normCubeRowWalk = 0;
  54306. var srcCubeRowWalk = 0;
  54307. for (var u = uStart; u <= uEnd; u++) {
  54308. //pointer to direction in cube map associated with texel
  54309. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  54310. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  54311. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  54312. //check dot product to see if texel is within cone
  54313. var tapDotProd = texelVectX * centerTapDir.x +
  54314. texelVectY * centerTapDir.y +
  54315. texelVectZ * centerTapDir.z;
  54316. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  54317. //solid angle stored in 4th channel of normalizer/solid angle cube map
  54318. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  54319. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  54320. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  54321. // so just adding one to specularpower do the trick.
  54322. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  54323. //iterate over channels
  54324. for (k = 0; k < nSrcChannels; k++) {
  54325. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  54326. srcCubeRowWalk++;
  54327. }
  54328. weightAccum += weight; //accumulate weight
  54329. }
  54330. else {
  54331. //step across source pixel
  54332. srcCubeRowWalk += nSrcChannels;
  54333. }
  54334. normCubeRowWalk += 4; // 4 channels per norm cube map.
  54335. }
  54336. startIndexNormCubeMap += normCubePitch;
  54337. startIndexSrcCubeMap += srcCubePitch;
  54338. }
  54339. }
  54340. }
  54341. //divide through by weights if weight is non zero
  54342. if (weightAccum != 0.0) {
  54343. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  54344. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  54345. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  54346. if (this.numChannels > 3) {
  54347. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  54348. }
  54349. }
  54350. else {
  54351. // otherwise sample nearest
  54352. // get face idx and u, v texel coordinate in face
  54353. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  54354. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  54355. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  54356. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  54357. if (this.numChannels > 3) {
  54358. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  54359. }
  54360. }
  54361. return PMREMGenerator._vectorTemp;
  54362. };
  54363. //--------------------------------------------------------------------------------------
  54364. // Fixup cube edges
  54365. //
  54366. // average texels on cube map faces across the edges
  54367. // WARP/BENT Method Only.
  54368. //--------------------------------------------------------------------------------------
  54369. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  54370. var k;
  54371. var j;
  54372. var i;
  54373. var iFace;
  54374. var iCorner = 0;
  54375. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  54376. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  54377. // note that if functionality to filter across the three texels for each corner, then
  54378. //indexed by corner and face idx. the array contains the face the start points belongs to.
  54379. var cornerPtr = [
  54380. [[], [], []],
  54381. [[], [], []],
  54382. [[], [], []],
  54383. [[], [], []],
  54384. [[], [], []],
  54385. [[], [], []],
  54386. [[], [], []],
  54387. [[], [], []]
  54388. ];
  54389. //if there is no fixup, or fixup width = 0, do nothing
  54390. if (cubeMapSize < 1) {
  54391. return;
  54392. }
  54393. //special case 1x1 cubemap, average face colors
  54394. if (cubeMapSize == 1) {
  54395. //iterate over channels
  54396. for (k = 0; k < this.numChannels; k++) {
  54397. var accum = 0.0;
  54398. //iterate over faces to accumulate face colors
  54399. for (iFace = 0; iFace < 6; iFace++) {
  54400. accum += cubeMap[iFace][k];
  54401. }
  54402. //compute average over 6 face colors
  54403. accum /= 6.0;
  54404. //iterate over faces to distribute face colors
  54405. for (iFace = 0; iFace < 6; iFace++) {
  54406. cubeMap[iFace][k] = accum;
  54407. }
  54408. }
  54409. return;
  54410. }
  54411. //iterate over faces to collect list of corner texel pointers
  54412. for (iFace = 0; iFace < 6; iFace++) {
  54413. //the 4 corner pointers for this face
  54414. faceCornerStartIndicies[0] = [iFace, 0];
  54415. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  54416. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  54417. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  54418. //iterate over face corners to collect cube corner pointers
  54419. for (iCorner = 0; iCorner < 4; iCorner++) {
  54420. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  54421. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  54422. cornerNumPtrs[corner]++;
  54423. }
  54424. }
  54425. //iterate over corners to average across corner tap values
  54426. for (iCorner = 0; iCorner < 8; iCorner++) {
  54427. for (k = 0; k < this.numChannels; k++) {
  54428. var cornerTapAccum = 0.0;
  54429. //iterate over corner texels and average results
  54430. for (i = 0; i < 3; i++) {
  54431. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  54432. }
  54433. //divide by 3 to compute average of corner tap values
  54434. cornerTapAccum *= (1.0 / 3.0);
  54435. //iterate over corner texels and average results
  54436. for (i = 0; i < 3; i++) {
  54437. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  54438. }
  54439. }
  54440. }
  54441. //iterate over the twelve edges of the cube to average across edges
  54442. for (i = 0; i < 12; i++) {
  54443. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  54444. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  54445. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  54446. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  54447. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  54448. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  54449. var edgeWalk = 0;
  54450. var neighborEdgeWalk = 0;
  54451. //Determine walking pointers based on edge type
  54452. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  54453. switch (edge) {
  54454. case PMREMGenerator.CP_EDGE_LEFT:
  54455. // no change to faceEdgeStartPtr
  54456. edgeWalk = this.numChannels * cubeMapSize;
  54457. break;
  54458. case PMREMGenerator.CP_EDGE_RIGHT:
  54459. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  54460. edgeWalk = this.numChannels * cubeMapSize;
  54461. break;
  54462. case PMREMGenerator.CP_EDGE_TOP:
  54463. // no change to faceEdgeStartPtr
  54464. edgeWalk = this.numChannels;
  54465. break;
  54466. case PMREMGenerator.CP_EDGE_BOTTOM:
  54467. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  54468. edgeWalk = this.numChannels;
  54469. break;
  54470. }
  54471. //For certain types of edge abutments, the neighbor edge walk needs to
  54472. // be flipped: the cases are
  54473. // if a left edge mates with a left or bottom edge on the neighbor
  54474. // if a top edge mates with a top or right edge on the neighbor
  54475. // if a right edge mates with a right or top edge on the neighbor
  54476. // if a bottom edge mates with a bottom or left edge on the neighbor
  54477. //Seeing as the edges are enumerated as follows
  54478. // left =0
  54479. // right =1
  54480. // top =2
  54481. // bottom =3
  54482. //
  54483. //If the edge enums are the same, or the sum of the enums == 3,
  54484. // the neighbor edge walk needs to be flipped
  54485. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  54486. switch (neighborEdge) {
  54487. case PMREMGenerator.CP_EDGE_LEFT:
  54488. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  54489. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  54490. break;
  54491. case PMREMGenerator.CP_EDGE_RIGHT:
  54492. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  54493. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  54494. break;
  54495. case PMREMGenerator.CP_EDGE_TOP:
  54496. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  54497. neighborEdgeWalk = -this.numChannels;
  54498. break;
  54499. case PMREMGenerator.CP_EDGE_BOTTOM:
  54500. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  54501. neighborEdgeWalk = -this.numChannels;
  54502. break;
  54503. }
  54504. }
  54505. else {
  54506. //swapped direction neighbor edge walk
  54507. switch (neighborEdge) {
  54508. case PMREMGenerator.CP_EDGE_LEFT:
  54509. //no change to neighborEdgeStartPtr for this case since it points
  54510. // to the upper left corner already
  54511. neighborEdgeWalk = this.numChannels * cubeMapSize;
  54512. break;
  54513. case PMREMGenerator.CP_EDGE_RIGHT:
  54514. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  54515. neighborEdgeWalk = this.numChannels * cubeMapSize;
  54516. break;
  54517. case PMREMGenerator.CP_EDGE_TOP:
  54518. //no change to neighborEdgeStartPtr for this case since it points
  54519. // to the upper left corner already
  54520. neighborEdgeWalk = this.numChannels;
  54521. break;
  54522. case PMREMGenerator.CP_EDGE_BOTTOM:
  54523. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  54524. neighborEdgeWalk = this.numChannels;
  54525. break;
  54526. }
  54527. }
  54528. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  54529. //nearby neighborhood
  54530. //step ahead one texel on edge
  54531. edgeStartIndex += edgeWalk;
  54532. neighborEdgeStartIndex += neighborEdgeWalk;
  54533. // note that this loop does not process the corner texels, since they have already been
  54534. // averaged across faces across earlier
  54535. for (j = 1; j < (cubeMapSize - 1); j++) {
  54536. //for each set of taps along edge, average them
  54537. // and rewrite the results into the edges
  54538. for (k = 0; k < this.numChannels; k++) {
  54539. var edgeTap = cubeMap[face][edgeStartIndex + k];
  54540. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  54541. //compute average of tap intensity values
  54542. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  54543. //propagate average of taps to edge taps
  54544. cubeMap[face][edgeStartIndex + k] = avgTap;
  54545. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  54546. }
  54547. edgeStartIndex += edgeWalk;
  54548. neighborEdgeStartIndex += neighborEdgeWalk;
  54549. }
  54550. }
  54551. };
  54552. return PMREMGenerator;
  54553. }());
  54554. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  54555. PMREMGenerator.CP_UDIR = 0;
  54556. PMREMGenerator.CP_VDIR = 1;
  54557. PMREMGenerator.CP_FACEAXIS = 2;
  54558. //used to index cube faces
  54559. PMREMGenerator.CP_FACE_X_POS = 0;
  54560. PMREMGenerator.CP_FACE_X_NEG = 1;
  54561. PMREMGenerator.CP_FACE_Y_POS = 2;
  54562. PMREMGenerator.CP_FACE_Y_NEG = 3;
  54563. PMREMGenerator.CP_FACE_Z_POS = 4;
  54564. PMREMGenerator.CP_FACE_Z_NEG = 5;
  54565. //used to index image edges
  54566. // NOTE.. the actual number corresponding to the edge is important
  54567. // do not change these, or the code will break
  54568. //
  54569. // CP_EDGE_LEFT is u = 0
  54570. // CP_EDGE_RIGHT is u = width-1
  54571. // CP_EDGE_TOP is v = 0
  54572. // CP_EDGE_BOTTOM is v = height-1
  54573. PMREMGenerator.CP_EDGE_LEFT = 0;
  54574. PMREMGenerator.CP_EDGE_RIGHT = 1;
  54575. PMREMGenerator.CP_EDGE_TOP = 2;
  54576. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  54577. //corners of CUBE map (P or N specifys if it corresponds to the
  54578. // positive or negative direction each of X, Y, and Z
  54579. PMREMGenerator.CP_CORNER_NNN = 0;
  54580. PMREMGenerator.CP_CORNER_NNP = 1;
  54581. PMREMGenerator.CP_CORNER_NPN = 2;
  54582. PMREMGenerator.CP_CORNER_NPP = 3;
  54583. PMREMGenerator.CP_CORNER_PNN = 4;
  54584. PMREMGenerator.CP_CORNER_PNP = 5;
  54585. PMREMGenerator.CP_CORNER_PPN = 6;
  54586. PMREMGenerator.CP_CORNER_PPP = 7;
  54587. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  54588. //3x2 matrices that map cube map indexing vectors in 3d
  54589. // (after face selection and divide through by the
  54590. // _ABSOLUTE VALUE_ of the max coord)
  54591. // into NVC space
  54592. //Note this currently assumes the D3D cube face ordering and orientation
  54593. PMREMGenerator._sgFace2DMapping = [
  54594. //XPOS face
  54595. [[0, 0, -1],
  54596. [0, -1, 0],
  54597. [1, 0, 0]],
  54598. //XNEG face
  54599. [[0, 0, 1],
  54600. [0, -1, 0],
  54601. [-1, 0, 0]],
  54602. //YPOS face
  54603. [[1, 0, 0],
  54604. [0, 0, 1],
  54605. [0, 1, 0]],
  54606. //YNEG face
  54607. [[1, 0, 0],
  54608. [0, 0, -1],
  54609. [0, -1, 0]],
  54610. //ZPOS face
  54611. [[1, 0, 0],
  54612. [0, -1, 0],
  54613. [0, 0, 1]],
  54614. //ZNEG face
  54615. [[-1, 0, 0],
  54616. [0, -1, 0],
  54617. [0, 0, -1]],
  54618. ];
  54619. //------------------------------------------------------------------------------
  54620. // D3D cube map face specification
  54621. // mapping from 3D x,y,z cube map lookup coordinates
  54622. // to 2D within face u,v coordinates
  54623. //
  54624. // --------------------> U direction
  54625. // | (within-face texture space)
  54626. // | _____
  54627. // | | |
  54628. // | | +Y |
  54629. // | _____|_____|_____ _____
  54630. // | | | | | |
  54631. // | | -X | +Z | +X | -Z |
  54632. // | |_____|_____|_____|_____|
  54633. // | | |
  54634. // | | -Y |
  54635. // | |_____|
  54636. // |
  54637. // v V direction
  54638. // (within-face texture space)
  54639. //------------------------------------------------------------------------------
  54640. //Information about neighbors and how texture coorrdinates change across faces
  54641. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  54642. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  54643. //Note this currently assumes the D3D cube face ordering and orientation
  54644. PMREMGenerator._sgCubeNgh = [
  54645. //XPOS face
  54646. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54647. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  54648. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54649. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  54650. //XNEG face
  54651. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  54652. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  54653. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  54654. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  54655. //YPOS face
  54656. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  54657. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  54658. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  54659. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  54660. //YNEG face
  54661. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  54662. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54663. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54664. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  54665. //ZPOS face
  54666. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  54667. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  54668. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54669. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  54670. //ZNEG face
  54671. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54672. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  54673. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  54674. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  54675. ];
  54676. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  54677. // this table is used to average over the edges.
  54678. PMREMGenerator._sgCubeEdgeList = [
  54679. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  54680. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  54681. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  54682. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54683. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  54684. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  54685. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  54686. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  54687. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  54688. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  54689. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  54690. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  54691. ];
  54692. //Information about which of the 8 cube corners are correspond to the
  54693. // the 4 corners in each cube face
  54694. // the order is upper left, upper right, lower left, lower right
  54695. PMREMGenerator._sgCubeCornerList = [
  54696. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  54697. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  54698. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  54699. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  54700. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  54701. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  54702. ];
  54703. Internals.PMREMGenerator = PMREMGenerator;
  54704. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54705. })(BABYLON || (BABYLON = {}));
  54706. //# sourceMappingURL=babylon.tools.pmremgenerator.js.map
  54707. var BABYLON;
  54708. (function (BABYLON) {
  54709. /**
  54710. * This represents a texture coming from an HDR input.
  54711. *
  54712. * The only supported format is currently panorama picture stored in RGBE format.
  54713. * Example of such files can be found on HDRLib: http://hdrlib.com/
  54714. */
  54715. var HDRCubeTexture = (function (_super) {
  54716. __extends(HDRCubeTexture, _super);
  54717. /**
  54718. * Instantiates an HDRTexture from the following parameters.
  54719. *
  54720. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  54721. * @param scene The scene the texture will be used in
  54722. * @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.
  54723. * @param noMipmap Forces to not generate the mipmap if true
  54724. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  54725. * @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)
  54726. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  54727. */
  54728. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  54729. if (noMipmap === void 0) { noMipmap = false; }
  54730. if (generateHarmonics === void 0) { generateHarmonics = true; }
  54731. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  54732. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  54733. if (onLoad === void 0) { onLoad = null; }
  54734. if (onError === void 0) { onError = null; }
  54735. var _this = _super.call(this, scene) || this;
  54736. _this._useInGammaSpace = false;
  54737. _this._generateHarmonics = true;
  54738. _this._isBABYLONPreprocessed = false;
  54739. _this._onLoad = null;
  54740. _this._onError = null;
  54741. /**
  54742. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  54743. */
  54744. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  54745. /**
  54746. * The spherical polynomial data extracted from the texture.
  54747. */
  54748. _this.sphericalPolynomial = null;
  54749. /**
  54750. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  54751. * This is usefull at run time to apply the good shader.
  54752. */
  54753. _this.isPMREM = false;
  54754. if (!url) {
  54755. return _this;
  54756. }
  54757. _this.name = url;
  54758. _this.url = url;
  54759. _this.hasAlpha = false;
  54760. _this.isCube = true;
  54761. _this._textureMatrix = BABYLON.Matrix.Identity();
  54762. _this._onLoad = onLoad;
  54763. _this._onError = onError;
  54764. if (size) {
  54765. _this._isBABYLONPreprocessed = false;
  54766. _this._noMipmap = noMipmap;
  54767. _this._size = size;
  54768. _this._useInGammaSpace = useInGammaSpace;
  54769. _this._usePMREMGenerator = usePMREMGenerator &&
  54770. scene.getEngine().getCaps().textureLOD &&
  54771. _this.getScene().getEngine().getCaps().textureFloat &&
  54772. !_this._useInGammaSpace;
  54773. }
  54774. else {
  54775. _this._isBABYLONPreprocessed = true;
  54776. _this._noMipmap = false;
  54777. _this._useInGammaSpace = false;
  54778. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  54779. _this.getScene().getEngine().getCaps().textureFloat &&
  54780. !_this._useInGammaSpace;
  54781. }
  54782. _this.isPMREM = _this._usePMREMGenerator;
  54783. _this._texture = _this._getFromCache(url, _this._noMipmap);
  54784. if (!_this._texture) {
  54785. if (!scene.useDelayedTextureLoading) {
  54786. _this.loadTexture();
  54787. }
  54788. else {
  54789. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  54790. }
  54791. }
  54792. return _this;
  54793. }
  54794. /**
  54795. * Occurs when the file is a preprocessed .babylon.hdr file.
  54796. */
  54797. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  54798. var _this = this;
  54799. var mipLevels = 0;
  54800. var floatArrayView = null;
  54801. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  54802. var mips = [];
  54803. var startIndex = 30;
  54804. for (var level = 0; level < mipLevels; level++) {
  54805. mips.push([]);
  54806. // Fill each pixel of the mip level.
  54807. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  54808. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54809. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  54810. mips[level].push(faceData);
  54811. startIndex += faceSize;
  54812. }
  54813. }
  54814. return mips;
  54815. } : null;
  54816. var callback = function (buffer) {
  54817. // Create Native Array Views
  54818. var intArrayView = new Int32Array(buffer);
  54819. floatArrayView = new Float32Array(buffer);
  54820. // Fill header.
  54821. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  54822. _this._size = intArrayView[1]; // CubeMap max mip face size.
  54823. // Update Texture Information.
  54824. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  54825. // Fill polynomial information.
  54826. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  54827. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  54828. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  54829. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  54830. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  54831. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  54832. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  54833. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  54834. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  54835. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  54836. // Fill pixel data.
  54837. mipLevels = intArrayView[29]; // Number of mip levels.
  54838. var startIndex = 30;
  54839. var data = [];
  54840. var faceSize = Math.pow(_this._size, 2) * 3;
  54841. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54842. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  54843. startIndex += faceSize;
  54844. }
  54845. var results = [];
  54846. var byteArray = null;
  54847. // Push each faces.
  54848. for (var k = 0; k < 6; k++) {
  54849. var dataFace = null;
  54850. // If special cases.
  54851. if (!mipmapGenerator) {
  54852. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  54853. dataFace = data[j];
  54854. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  54855. // 3 channels of 1 bytes per pixel in bytes.
  54856. var byteBuffer = new ArrayBuffer(faceSize);
  54857. byteArray = new Uint8Array(byteBuffer);
  54858. }
  54859. for (var i = 0; i < _this._size * _this._size; i++) {
  54860. // Put in gamma space if requested.
  54861. if (_this._useInGammaSpace) {
  54862. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  54863. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  54864. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  54865. }
  54866. // Convert to int texture for fallback.
  54867. if (byteArray) {
  54868. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  54869. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  54870. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  54871. // May use luminance instead if the result is not accurate.
  54872. var max = Math.max(Math.max(r, g), b);
  54873. if (max > 255) {
  54874. var scale = 255 / max;
  54875. r *= scale;
  54876. g *= scale;
  54877. b *= scale;
  54878. }
  54879. byteArray[(i * 3) + 0] = r;
  54880. byteArray[(i * 3) + 1] = g;
  54881. byteArray[(i * 3) + 2] = b;
  54882. }
  54883. }
  54884. }
  54885. else {
  54886. dataFace = data[k];
  54887. }
  54888. // Fill the array accordingly.
  54889. if (byteArray) {
  54890. results.push(byteArray);
  54891. }
  54892. else {
  54893. results.push(dataFace);
  54894. }
  54895. }
  54896. return results;
  54897. };
  54898. 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);
  54899. };
  54900. /**
  54901. * Occurs when the file is raw .hdr file.
  54902. */
  54903. HDRCubeTexture.prototype.loadHDRTexture = function () {
  54904. var _this = this;
  54905. var callback = function (buffer) {
  54906. // Extract the raw linear data.
  54907. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  54908. // Generate harmonics if needed.
  54909. if (_this._generateHarmonics) {
  54910. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  54911. }
  54912. var results = [];
  54913. var byteArray = null;
  54914. // Push each faces.
  54915. for (var j = 0; j < 6; j++) {
  54916. // Create uintarray fallback.
  54917. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  54918. // 3 channels of 1 bytes per pixel in bytes.
  54919. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  54920. byteArray = new Uint8Array(byteBuffer);
  54921. }
  54922. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  54923. // If special cases.
  54924. if (_this._useInGammaSpace || byteArray) {
  54925. for (var i = 0; i < _this._size * _this._size; i++) {
  54926. // Put in gamma space if requested.
  54927. if (_this._useInGammaSpace) {
  54928. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  54929. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  54930. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  54931. }
  54932. // Convert to int texture for fallback.
  54933. if (byteArray) {
  54934. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  54935. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  54936. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  54937. // May use luminance instead if the result is not accurate.
  54938. var max = Math.max(Math.max(r, g), b);
  54939. if (max > 255) {
  54940. var scale = 255 / max;
  54941. r *= scale;
  54942. g *= scale;
  54943. b *= scale;
  54944. }
  54945. byteArray[(i * 3) + 0] = r;
  54946. byteArray[(i * 3) + 1] = g;
  54947. byteArray[(i * 3) + 2] = b;
  54948. }
  54949. }
  54950. }
  54951. if (byteArray) {
  54952. results.push(byteArray);
  54953. }
  54954. else {
  54955. results.push(dataFace);
  54956. }
  54957. }
  54958. return results;
  54959. };
  54960. var mipmapGenerator = null;
  54961. if (!this._noMipmap &&
  54962. this._usePMREMGenerator) {
  54963. mipmapGenerator = function (data) {
  54964. // Custom setup of the generator matching with the PBR shader values.
  54965. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  54966. return generator.filterCubeMap();
  54967. };
  54968. }
  54969. 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);
  54970. };
  54971. /**
  54972. * Starts the loading process of the texture.
  54973. */
  54974. HDRCubeTexture.prototype.loadTexture = function () {
  54975. if (this._isBABYLONPreprocessed) {
  54976. this.loadBabylonTexture();
  54977. }
  54978. else {
  54979. this.loadHDRTexture();
  54980. }
  54981. };
  54982. HDRCubeTexture.prototype.clone = function () {
  54983. var size = this._isBABYLONPreprocessed ? null : this._size;
  54984. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  54985. // Base texture
  54986. newTexture.level = this.level;
  54987. newTexture.wrapU = this.wrapU;
  54988. newTexture.wrapV = this.wrapV;
  54989. newTexture.coordinatesIndex = this.coordinatesIndex;
  54990. newTexture.coordinatesMode = this.coordinatesMode;
  54991. return newTexture;
  54992. };
  54993. // Methods
  54994. HDRCubeTexture.prototype.delayLoad = function () {
  54995. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  54996. return;
  54997. }
  54998. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  54999. this._texture = this._getFromCache(this.url, this._noMipmap);
  55000. if (!this._texture) {
  55001. this.loadTexture();
  55002. }
  55003. };
  55004. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  55005. return this._textureMatrix;
  55006. };
  55007. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  55008. var texture = null;
  55009. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  55010. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  55011. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  55012. texture.name = parsedTexture.name;
  55013. texture.hasAlpha = parsedTexture.hasAlpha;
  55014. texture.level = parsedTexture.level;
  55015. texture.coordinatesMode = parsedTexture.coordinatesMode;
  55016. }
  55017. return texture;
  55018. };
  55019. HDRCubeTexture.prototype.serialize = function () {
  55020. if (!this.name) {
  55021. return null;
  55022. }
  55023. var serializationObject = {};
  55024. serializationObject.name = this.name;
  55025. serializationObject.hasAlpha = this.hasAlpha;
  55026. serializationObject.isCube = true;
  55027. serializationObject.level = this.level;
  55028. serializationObject.size = this._size;
  55029. serializationObject.coordinatesMode = this.coordinatesMode;
  55030. serializationObject.useInGammaSpace = this._useInGammaSpace;
  55031. serializationObject.generateHarmonics = this._generateHarmonics;
  55032. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  55033. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  55034. serializationObject.customType = "BABYLON.HDRCubeTexture";
  55035. serializationObject.noMipmap = this._noMipmap;
  55036. return serializationObject;
  55037. };
  55038. /**
  55039. * Saves as a file the data contained in the texture in a binary format.
  55040. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  55041. * as the spherical used in the lighting.
  55042. * @param url The HDR file url.
  55043. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  55044. * @param onError Method called if any error happens during download.
  55045. * @return The packed binary data.
  55046. */
  55047. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  55048. if (onError === void 0) { onError = null; }
  55049. var callback = function (buffer) {
  55050. var data = new Blob([buffer], { type: 'application/octet-stream' });
  55051. // Returns a URL you can use as a href.
  55052. var objUrl = window.URL.createObjectURL(data);
  55053. // Simulates a link to it and click to dowload.
  55054. var a = document.createElement("a");
  55055. document.body.appendChild(a);
  55056. a.style.display = "none";
  55057. a.href = objUrl;
  55058. a.download = "envmap.babylon.hdr";
  55059. a.click();
  55060. };
  55061. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  55062. };
  55063. /**
  55064. * Serializes the data contained in the texture in a binary format.
  55065. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  55066. * as the spherical used in the lighting.
  55067. * @param url The HDR file url.
  55068. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  55069. * @param onError Method called if any error happens during download.
  55070. * @return The packed binary data.
  55071. */
  55072. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  55073. if (onError === void 0) { onError = null; }
  55074. // Needs the url tho create the texture.
  55075. if (!url) {
  55076. return null;
  55077. }
  55078. // Check Power of two size.
  55079. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  55080. return null;
  55081. }
  55082. var getDataCallback = function (dataBuffer) {
  55083. // Extract the raw linear data.
  55084. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  55085. // Generate harmonics if needed.
  55086. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  55087. // Generate seamless faces
  55088. var mipGeneratorArray = [];
  55089. // Data are known to be in +X +Y +Z -X -Y -Z
  55090. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  55091. mipGeneratorArray.push(cubeData.right); // +X
  55092. mipGeneratorArray.push(cubeData.left); // -X
  55093. mipGeneratorArray.push(cubeData.up); // +Y
  55094. mipGeneratorArray.push(cubeData.down); // -Y
  55095. mipGeneratorArray.push(cubeData.front); // +Z
  55096. mipGeneratorArray.push(cubeData.back); // -Z
  55097. // Custom setup of the generator matching with the PBR shader values.
  55098. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  55099. var mippedData = generator.filterCubeMap();
  55100. // Compute required byte length.
  55101. var byteLength = 1 * 4; // Raw Data Version int32.
  55102. byteLength += 4; // CubeMap max mip face size int32.
  55103. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  55104. // Add data size.
  55105. byteLength += 4; // Number of mip levels int32.
  55106. for (var level = 0; level < mippedData.length; level++) {
  55107. var mipSize = size >> level;
  55108. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  55109. }
  55110. // Prepare binary structure.
  55111. var buffer = new ArrayBuffer(byteLength);
  55112. var intArrayView = new Int32Array(buffer);
  55113. var floatArrayView = new Float32Array(buffer);
  55114. // Fill header.
  55115. intArrayView[0] = 1; // Version 1.
  55116. intArrayView[1] = size; // CubeMap max mip face size.
  55117. // Fill polynomial information.
  55118. sphericalPolynomial.x.toArray(floatArrayView, 2);
  55119. sphericalPolynomial.y.toArray(floatArrayView, 5);
  55120. sphericalPolynomial.z.toArray(floatArrayView, 8);
  55121. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  55122. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  55123. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  55124. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  55125. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  55126. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  55127. // Fill pixel data.
  55128. intArrayView[29] = mippedData.length; // Number of mip levels.
  55129. var startIndex = 30;
  55130. for (var level = 0; level < mippedData.length; level++) {
  55131. // Fill each pixel of the mip level.
  55132. var faceSize = Math.pow(size >> level, 2) * 3;
  55133. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  55134. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  55135. startIndex += faceSize;
  55136. }
  55137. }
  55138. // Callback.
  55139. callback(buffer);
  55140. };
  55141. // Download and process.
  55142. BABYLON.Tools.LoadFile(url, function (data) {
  55143. getDataCallback(data);
  55144. }, null, null, true, onError);
  55145. };
  55146. return HDRCubeTexture;
  55147. }(BABYLON.BaseTexture));
  55148. HDRCubeTexture._facesMapping = [
  55149. "right",
  55150. "up",
  55151. "front",
  55152. "left",
  55153. "down",
  55154. "back"
  55155. ];
  55156. BABYLON.HDRCubeTexture = HDRCubeTexture;
  55157. })(BABYLON || (BABYLON = {}));
  55158. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  55159. var BABYLON;
  55160. (function (BABYLON) {
  55161. var Debug;
  55162. (function (Debug) {
  55163. /**
  55164. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  55165. */
  55166. var SkeletonViewer = (function () {
  55167. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  55168. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  55169. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  55170. this.skeleton = skeleton;
  55171. this.mesh = mesh;
  55172. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  55173. this.renderingGroupId = renderingGroupId;
  55174. this.color = BABYLON.Color3.White();
  55175. this._debugLines = [];
  55176. this._isEnabled = false;
  55177. this._scene = scene;
  55178. this.update();
  55179. this._renderFunction = this.update.bind(this);
  55180. }
  55181. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  55182. get: function () {
  55183. return this._isEnabled;
  55184. },
  55185. set: function (value) {
  55186. if (this._isEnabled === value) {
  55187. return;
  55188. }
  55189. this._isEnabled = value;
  55190. if (value) {
  55191. this._scene.registerBeforeRender(this._renderFunction);
  55192. }
  55193. else {
  55194. this._scene.unregisterBeforeRender(this._renderFunction);
  55195. }
  55196. },
  55197. enumerable: true,
  55198. configurable: true
  55199. });
  55200. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  55201. if (x === void 0) { x = 0; }
  55202. if (y === void 0) { y = 0; }
  55203. if (z === void 0) { z = 0; }
  55204. var tmat = BABYLON.Tmp.Matrix[0];
  55205. var parentBone = bone.getParent();
  55206. tmat.copyFrom(bone.getLocalMatrix());
  55207. if (x !== 0 || y !== 0 || z !== 0) {
  55208. var tmat2 = BABYLON.Tmp.Matrix[1];
  55209. BABYLON.Matrix.IdentityToRef(tmat2);
  55210. tmat2.m[12] = x;
  55211. tmat2.m[13] = y;
  55212. tmat2.m[14] = z;
  55213. tmat2.multiplyToRef(tmat, tmat);
  55214. }
  55215. if (parentBone) {
  55216. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  55217. }
  55218. tmat.multiplyToRef(meshMat, tmat);
  55219. position.x = tmat.m[12];
  55220. position.y = tmat.m[13];
  55221. position.z = tmat.m[14];
  55222. };
  55223. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  55224. var len = bones.length;
  55225. for (var i = 0; i < len; i++) {
  55226. var bone = bones[i];
  55227. var points = this._debugLines[i];
  55228. if (!points) {
  55229. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55230. this._debugLines[i] = points;
  55231. }
  55232. this._getBonePosition(points[0], bone, meshMat);
  55233. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  55234. }
  55235. };
  55236. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  55237. var len = bones.length;
  55238. var boneNum = 0;
  55239. for (var i = len - 1; i >= 0; i--) {
  55240. var childBone = bones[i];
  55241. var parentBone = childBone.getParent();
  55242. if (!parentBone) {
  55243. continue;
  55244. }
  55245. var points = this._debugLines[boneNum];
  55246. if (!points) {
  55247. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55248. this._debugLines[boneNum] = points;
  55249. }
  55250. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  55251. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  55252. boneNum++;
  55253. }
  55254. };
  55255. SkeletonViewer.prototype.update = function () {
  55256. if (this.autoUpdateBonesMatrices) {
  55257. this.skeleton.computeAbsoluteTransforms();
  55258. }
  55259. if (this.skeleton.bones[0].length === undefined) {
  55260. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  55261. }
  55262. else {
  55263. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  55264. }
  55265. if (!this._debugMesh) {
  55266. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  55267. this._debugMesh.renderingGroupId = this.renderingGroupId;
  55268. }
  55269. else {
  55270. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  55271. }
  55272. this._debugMesh.color = this.color;
  55273. };
  55274. SkeletonViewer.prototype.dispose = function () {
  55275. if (this._debugMesh) {
  55276. this.isEnabled = false;
  55277. this._debugMesh.dispose();
  55278. this._debugMesh = null;
  55279. }
  55280. };
  55281. return SkeletonViewer;
  55282. }());
  55283. Debug.SkeletonViewer = SkeletonViewer;
  55284. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  55285. })(BABYLON || (BABYLON = {}));
  55286. //# sourceMappingURL=babylon.skeletonViewer.js.map
  55287. var BABYLON;
  55288. (function (BABYLON) {
  55289. var Debug;
  55290. (function (Debug) {
  55291. var AxesViewer = (function () {
  55292. function AxesViewer(scene, scaleLines) {
  55293. if (scaleLines === void 0) { scaleLines = 1; }
  55294. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55295. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55296. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  55297. this.scaleLines = 1;
  55298. this.scaleLines = scaleLines;
  55299. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  55300. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  55301. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  55302. this._xmesh.renderingGroupId = 2;
  55303. this._ymesh.renderingGroupId = 2;
  55304. this._zmesh.renderingGroupId = 2;
  55305. this._xmesh.material.checkReadyOnlyOnce = true;
  55306. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  55307. this._ymesh.material.checkReadyOnlyOnce = true;
  55308. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  55309. this._zmesh.material.checkReadyOnlyOnce = true;
  55310. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  55311. this.scene = scene;
  55312. }
  55313. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  55314. var scaleLines = this.scaleLines;
  55315. var point1 = this._xline[0];
  55316. var point2 = this._xline[1];
  55317. point1.x = position.x;
  55318. point1.y = position.y;
  55319. point1.z = position.z;
  55320. point2.x = point1.x + xaxis.x * scaleLines;
  55321. point2.y = point1.y + xaxis.y * scaleLines;
  55322. point2.z = point1.z + xaxis.z * scaleLines;
  55323. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  55324. point1 = this._yline[0];
  55325. point2 = this._yline[1];
  55326. point1.x = position.x;
  55327. point1.y = position.y;
  55328. point1.z = position.z;
  55329. point2.x = point1.x + yaxis.x * scaleLines;
  55330. point2.y = point1.y + yaxis.y * scaleLines;
  55331. point2.z = point1.z + yaxis.z * scaleLines;
  55332. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  55333. point1 = this._zline[0];
  55334. point2 = this._zline[1];
  55335. point1.x = position.x;
  55336. point1.y = position.y;
  55337. point1.z = position.z;
  55338. point2.x = point1.x + zaxis.x * scaleLines;
  55339. point2.y = point1.y + zaxis.y * scaleLines;
  55340. point2.z = point1.z + zaxis.z * scaleLines;
  55341. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  55342. };
  55343. AxesViewer.prototype.dispose = function () {
  55344. if (this._xmesh) {
  55345. this._xmesh.dispose();
  55346. this._ymesh.dispose();
  55347. this._zmesh.dispose();
  55348. this._xmesh = null;
  55349. this._ymesh = null;
  55350. this._zmesh = null;
  55351. this._xline = null;
  55352. this._yline = null;
  55353. this._zline = null;
  55354. this.scene = null;
  55355. }
  55356. };
  55357. return AxesViewer;
  55358. }());
  55359. Debug.AxesViewer = AxesViewer;
  55360. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  55361. })(BABYLON || (BABYLON = {}));
  55362. //# sourceMappingURL=babylon.axesViewer.js.map
  55363. var BABYLON;
  55364. (function (BABYLON) {
  55365. var Debug;
  55366. (function (Debug) {
  55367. var BoneAxesViewer = (function (_super) {
  55368. __extends(BoneAxesViewer, _super);
  55369. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  55370. if (scaleLines === void 0) { scaleLines = 1; }
  55371. var _this = _super.call(this, scene, scaleLines) || this;
  55372. _this.pos = BABYLON.Vector3.Zero();
  55373. _this.xaxis = BABYLON.Vector3.Zero();
  55374. _this.yaxis = BABYLON.Vector3.Zero();
  55375. _this.zaxis = BABYLON.Vector3.Zero();
  55376. _this.mesh = mesh;
  55377. _this.bone = bone;
  55378. return _this;
  55379. }
  55380. BoneAxesViewer.prototype.update = function () {
  55381. var bone = this.bone;
  55382. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  55383. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  55384. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  55385. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  55386. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  55387. };
  55388. BoneAxesViewer.prototype.dispose = function () {
  55389. if (this.pos) {
  55390. this.pos = null;
  55391. this.xaxis = null;
  55392. this.yaxis = null;
  55393. this.zaxis = null;
  55394. this.mesh = null;
  55395. this.bone = null;
  55396. _super.prototype.dispose.call(this);
  55397. }
  55398. };
  55399. return BoneAxesViewer;
  55400. }(Debug.AxesViewer));
  55401. Debug.BoneAxesViewer = BoneAxesViewer;
  55402. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  55403. })(BABYLON || (BABYLON = {}));
  55404. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  55405. var BABYLON;
  55406. (function (BABYLON) {
  55407. /**
  55408. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  55409. * It can help converting any input color in a desired output one. This can then be used to create effects
  55410. * from sepia, black and white to sixties or futuristic rendering...
  55411. *
  55412. * The only supported format is currently 3dl.
  55413. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  55414. */
  55415. var ColorGradingTexture = (function (_super) {
  55416. __extends(ColorGradingTexture, _super);
  55417. /**
  55418. * Instantiates a ColorGradingTexture from the following parameters.
  55419. *
  55420. * @param url The location of the color gradind data (currently only supporting 3dl)
  55421. * @param scene The scene the texture will be used in
  55422. */
  55423. function ColorGradingTexture(url, scene) {
  55424. var _this = _super.call(this, scene) || this;
  55425. if (!url) {
  55426. return _this;
  55427. }
  55428. _this._textureMatrix = BABYLON.Matrix.Identity();
  55429. _this.name = url;
  55430. _this.url = url;
  55431. _this.hasAlpha = false;
  55432. _this.isCube = false;
  55433. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55434. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55435. _this.anisotropicFilteringLevel = 1;
  55436. _this._texture = _this._getFromCache(url, true);
  55437. if (!_this._texture) {
  55438. if (!scene.useDelayedTextureLoading) {
  55439. _this.loadTexture();
  55440. }
  55441. else {
  55442. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  55443. }
  55444. }
  55445. return _this;
  55446. }
  55447. /**
  55448. * Returns the texture matrix used in most of the material.
  55449. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  55450. */
  55451. ColorGradingTexture.prototype.getTextureMatrix = function () {
  55452. return this._textureMatrix;
  55453. };
  55454. /**
  55455. * Occurs when the file being loaded is a .3dl LUT file.
  55456. */
  55457. ColorGradingTexture.prototype.load3dlTexture = function () {
  55458. var _this = this;
  55459. var mipLevels = 0;
  55460. var floatArrayView = null;
  55461. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55462. this._texture = texture;
  55463. var callback = function (text) {
  55464. var data;
  55465. var tempData;
  55466. var line;
  55467. var lines = text.split('\n');
  55468. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  55469. var maxColor = 0;
  55470. for (var i = 0; i < lines.length; i++) {
  55471. line = lines[i];
  55472. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  55473. continue;
  55474. if (line.indexOf('#') === 0)
  55475. continue;
  55476. var words = line.split(" ");
  55477. if (size === 0) {
  55478. // Number of space + one
  55479. size = words.length;
  55480. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  55481. tempData = new Float32Array(size * size * size * 4);
  55482. continue;
  55483. }
  55484. if (size != 0) {
  55485. var r = Math.max(parseInt(words[0]), 0);
  55486. var g = Math.max(parseInt(words[1]), 0);
  55487. var b = Math.max(parseInt(words[2]), 0);
  55488. maxColor = Math.max(r, maxColor);
  55489. maxColor = Math.max(g, maxColor);
  55490. maxColor = Math.max(b, maxColor);
  55491. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  55492. tempData[pixelStorageIndex + 0] = r;
  55493. tempData[pixelStorageIndex + 1] = g;
  55494. tempData[pixelStorageIndex + 2] = b;
  55495. tempData[pixelStorageIndex + 3] = 0;
  55496. pixelIndexSlice++;
  55497. if (pixelIndexSlice % size == 0) {
  55498. pixelIndexH++;
  55499. pixelIndexSlice = 0;
  55500. if (pixelIndexH % size == 0) {
  55501. pixelIndexW++;
  55502. pixelIndexH = 0;
  55503. }
  55504. }
  55505. }
  55506. }
  55507. for (var i = 0; i < tempData.length; i++) {
  55508. var value = tempData[i];
  55509. data[i] = (value / maxColor * 255);
  55510. }
  55511. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  55512. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  55513. };
  55514. BABYLON.Tools.LoadFile(this.url, callback);
  55515. return this._texture;
  55516. };
  55517. /**
  55518. * Starts the loading process of the texture.
  55519. */
  55520. ColorGradingTexture.prototype.loadTexture = function () {
  55521. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  55522. this.load3dlTexture();
  55523. }
  55524. };
  55525. /**
  55526. * Clones the color gradind texture.
  55527. */
  55528. ColorGradingTexture.prototype.clone = function () {
  55529. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  55530. // Base texture
  55531. newTexture.level = this.level;
  55532. return newTexture;
  55533. };
  55534. /**
  55535. * Called during delayed load for textures.
  55536. */
  55537. ColorGradingTexture.prototype.delayLoad = function () {
  55538. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  55539. return;
  55540. }
  55541. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  55542. this._texture = this._getFromCache(this.url, true);
  55543. if (!this._texture) {
  55544. this.loadTexture();
  55545. }
  55546. };
  55547. /**
  55548. * Binds the color grading to the shader.
  55549. * @param colorGrading The texture to bind
  55550. * @param effect The effect to bind to
  55551. */
  55552. ColorGradingTexture.Bind = function (colorGrading, effect) {
  55553. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  55554. var x = colorGrading.level; // Texture Level
  55555. var y = colorGrading.getSize().height; // Texture Size example with 8
  55556. var z = y - 1.0; // SizeMinusOne 8 - 1
  55557. var w = 1 / y; // Space of 1 slice 1 / 8
  55558. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  55559. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  55560. 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
  55561. 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
  55562. 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
  55563. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  55564. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  55565. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  55566. };
  55567. /**
  55568. * Prepare the list of uniforms associated with the ColorGrading effects.
  55569. * @param uniformsList The list of uniforms used in the effect
  55570. * @param samplersList The list of samplers used in the effect
  55571. */
  55572. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  55573. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  55574. samplersList.push("cameraColorGrading2DSampler");
  55575. };
  55576. /**
  55577. * Parses a color grading texture serialized by Babylon.
  55578. * @param parsedTexture The texture information being parsedTexture
  55579. * @param scene The scene to load the texture in
  55580. * @param rootUrl The root url of the data assets to load
  55581. * @return A color gradind texture
  55582. */
  55583. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  55584. var texture = null;
  55585. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  55586. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  55587. texture.name = parsedTexture.name;
  55588. texture.level = parsedTexture.level;
  55589. }
  55590. return texture;
  55591. };
  55592. /**
  55593. * Serializes the LUT texture to json format.
  55594. */
  55595. ColorGradingTexture.prototype.serialize = function () {
  55596. if (!this.name) {
  55597. return null;
  55598. }
  55599. var serializationObject = {};
  55600. serializationObject.name = this.name;
  55601. serializationObject.level = this.level;
  55602. serializationObject.customType = "BABYLON.ColorGradingTexture";
  55603. return serializationObject;
  55604. };
  55605. return ColorGradingTexture;
  55606. }(BABYLON.BaseTexture));
  55607. /**
  55608. * Empty line regex stored for GC.
  55609. */
  55610. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  55611. BABYLON.ColorGradingTexture = ColorGradingTexture;
  55612. })(BABYLON || (BABYLON = {}));
  55613. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  55614. var BABYLON;
  55615. (function (BABYLON) {
  55616. /**
  55617. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  55618. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  55619. * 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;
  55620. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  55621. */
  55622. var ColorCurves = (function () {
  55623. function ColorCurves() {
  55624. this._dirty = true;
  55625. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  55626. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  55627. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  55628. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  55629. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  55630. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  55631. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  55632. this._globalHue = 30;
  55633. this._globalDensity = 0;
  55634. this._globalSaturation = 0;
  55635. this._globalExposure = 0;
  55636. this._highlightsHue = 30;
  55637. this._highlightsDensity = 0;
  55638. this._highlightsSaturation = 0;
  55639. this._highlightsExposure = 0;
  55640. this._midtonesHue = 30;
  55641. this._midtonesDensity = 0;
  55642. this._midtonesSaturation = 0;
  55643. this._midtonesExposure = 0;
  55644. this._shadowsHue = 30;
  55645. this._shadowsDensity = 0;
  55646. this._shadowsSaturation = 0;
  55647. this._shadowsExposure = 0;
  55648. }
  55649. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  55650. /**
  55651. * Gets the global Hue value.
  55652. * 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).
  55653. */
  55654. get: function () {
  55655. return this._globalHue;
  55656. },
  55657. /**
  55658. * Sets the global Hue value.
  55659. * 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).
  55660. */
  55661. set: function (value) {
  55662. this._globalHue = value;
  55663. this._dirty = true;
  55664. },
  55665. enumerable: true,
  55666. configurable: true
  55667. });
  55668. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  55669. /**
  55670. * Gets the global Density value.
  55671. * 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.
  55672. * Values less than zero provide a filter of opposite hue.
  55673. */
  55674. get: function () {
  55675. return this._globalDensity;
  55676. },
  55677. /**
  55678. * Sets the global Density value.
  55679. * 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.
  55680. * Values less than zero provide a filter of opposite hue.
  55681. */
  55682. set: function (value) {
  55683. this._globalDensity = value;
  55684. this._dirty = true;
  55685. },
  55686. enumerable: true,
  55687. configurable: true
  55688. });
  55689. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  55690. /**
  55691. * Gets the global Saturation value.
  55692. * 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.
  55693. */
  55694. get: function () {
  55695. return this._globalSaturation;
  55696. },
  55697. /**
  55698. * Sets the global Saturation value.
  55699. * 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.
  55700. */
  55701. set: function (value) {
  55702. this._globalSaturation = value;
  55703. this._dirty = true;
  55704. },
  55705. enumerable: true,
  55706. configurable: true
  55707. });
  55708. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  55709. /**
  55710. * Gets the highlights Hue value.
  55711. * 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).
  55712. */
  55713. get: function () {
  55714. return this._highlightsHue;
  55715. },
  55716. /**
  55717. * Sets the highlights Hue value.
  55718. * 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).
  55719. */
  55720. set: function (value) {
  55721. this._highlightsHue = value;
  55722. this._dirty = true;
  55723. },
  55724. enumerable: true,
  55725. configurable: true
  55726. });
  55727. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  55728. /**
  55729. * Gets the highlights Density value.
  55730. * 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.
  55731. * Values less than zero provide a filter of opposite hue.
  55732. */
  55733. get: function () {
  55734. return this._highlightsDensity;
  55735. },
  55736. /**
  55737. * Sets the highlights Density value.
  55738. * 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.
  55739. * Values less than zero provide a filter of opposite hue.
  55740. */
  55741. set: function (value) {
  55742. this._highlightsDensity = value;
  55743. this._dirty = true;
  55744. },
  55745. enumerable: true,
  55746. configurable: true
  55747. });
  55748. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  55749. /**
  55750. * Gets the highlights Saturation value.
  55751. * 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.
  55752. */
  55753. get: function () {
  55754. return this._highlightsSaturation;
  55755. },
  55756. /**
  55757. * Sets the highlights Saturation value.
  55758. * 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.
  55759. */
  55760. set: function (value) {
  55761. this._highlightsSaturation = value;
  55762. this._dirty = true;
  55763. },
  55764. enumerable: true,
  55765. configurable: true
  55766. });
  55767. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  55768. /**
  55769. * Gets the highlights Exposure value.
  55770. * 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.
  55771. */
  55772. get: function () {
  55773. return this._highlightsExposure;
  55774. },
  55775. /**
  55776. * Sets the highlights Exposure value.
  55777. * 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.
  55778. */
  55779. set: function (value) {
  55780. this._highlightsExposure = value;
  55781. this._dirty = true;
  55782. },
  55783. enumerable: true,
  55784. configurable: true
  55785. });
  55786. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  55787. /**
  55788. * Gets the midtones Hue value.
  55789. * 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).
  55790. */
  55791. get: function () {
  55792. return this._midtonesHue;
  55793. },
  55794. /**
  55795. * Sets the midtones Hue value.
  55796. * 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).
  55797. */
  55798. set: function (value) {
  55799. this._midtonesHue = value;
  55800. this._dirty = true;
  55801. },
  55802. enumerable: true,
  55803. configurable: true
  55804. });
  55805. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  55806. /**
  55807. * Gets the midtones Density value.
  55808. * 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.
  55809. * Values less than zero provide a filter of opposite hue.
  55810. */
  55811. get: function () {
  55812. return this._midtonesDensity;
  55813. },
  55814. /**
  55815. * Sets the midtones Density value.
  55816. * 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.
  55817. * Values less than zero provide a filter of opposite hue.
  55818. */
  55819. set: function (value) {
  55820. this._midtonesDensity = value;
  55821. this._dirty = true;
  55822. },
  55823. enumerable: true,
  55824. configurable: true
  55825. });
  55826. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  55827. /**
  55828. * Gets the midtones Saturation value.
  55829. * 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.
  55830. */
  55831. get: function () {
  55832. return this._midtonesSaturation;
  55833. },
  55834. /**
  55835. * Sets the midtones Saturation value.
  55836. * 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.
  55837. */
  55838. set: function (value) {
  55839. this._midtonesSaturation = value;
  55840. this._dirty = true;
  55841. },
  55842. enumerable: true,
  55843. configurable: true
  55844. });
  55845. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  55846. /**
  55847. * Gets the midtones Exposure value.
  55848. * 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.
  55849. */
  55850. get: function () {
  55851. return this._midtonesExposure;
  55852. },
  55853. /**
  55854. * Sets the midtones Exposure value.
  55855. * 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.
  55856. */
  55857. set: function (value) {
  55858. this._midtonesExposure = value;
  55859. this._dirty = true;
  55860. },
  55861. enumerable: true,
  55862. configurable: true
  55863. });
  55864. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  55865. /**
  55866. * Gets the shadows Hue value.
  55867. * 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).
  55868. */
  55869. get: function () {
  55870. return this._shadowsHue;
  55871. },
  55872. /**
  55873. * Sets the shadows Hue value.
  55874. * 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).
  55875. */
  55876. set: function (value) {
  55877. this._shadowsHue = value;
  55878. this._dirty = true;
  55879. },
  55880. enumerable: true,
  55881. configurable: true
  55882. });
  55883. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  55884. /**
  55885. * Gets the shadows Density value.
  55886. * 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.
  55887. * Values less than zero provide a filter of opposite hue.
  55888. */
  55889. get: function () {
  55890. return this._shadowsDensity;
  55891. },
  55892. /**
  55893. * Sets the shadows Density value.
  55894. * 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.
  55895. * Values less than zero provide a filter of opposite hue.
  55896. */
  55897. set: function (value) {
  55898. this._shadowsDensity = value;
  55899. this._dirty = true;
  55900. },
  55901. enumerable: true,
  55902. configurable: true
  55903. });
  55904. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  55905. /**
  55906. * Gets the shadows Saturation value.
  55907. * 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.
  55908. */
  55909. get: function () {
  55910. return this._shadowsSaturation;
  55911. },
  55912. /**
  55913. * Sets the shadows Saturation value.
  55914. * 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.
  55915. */
  55916. set: function (value) {
  55917. this._shadowsSaturation = value;
  55918. this._dirty = true;
  55919. },
  55920. enumerable: true,
  55921. configurable: true
  55922. });
  55923. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  55924. /**
  55925. * Gets the shadows Exposure value.
  55926. * 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.
  55927. */
  55928. get: function () {
  55929. return this._shadowsExposure;
  55930. },
  55931. /**
  55932. * Sets the shadows Exposure value.
  55933. * 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.
  55934. */
  55935. set: function (value) {
  55936. this._shadowsExposure = value;
  55937. this._dirty = true;
  55938. },
  55939. enumerable: true,
  55940. configurable: true
  55941. });
  55942. /**
  55943. * Binds the color curves to the shader.
  55944. * @param colorCurves The color curve to bind
  55945. * @param effect The effect to bind to
  55946. */
  55947. ColorCurves.Bind = function (colorCurves, effect) {
  55948. if (colorCurves._dirty) {
  55949. colorCurves._dirty = false;
  55950. // Fill in global info.
  55951. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  55952. // Compute highlights info.
  55953. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  55954. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  55955. // Compute midtones info.
  55956. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  55957. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  55958. // Compute shadows info.
  55959. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  55960. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  55961. // Compute deltas (neutral is midtones).
  55962. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  55963. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  55964. }
  55965. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  55966. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  55967. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  55968. };
  55969. /**
  55970. * Prepare the list of uniforms associated with the ColorCurves effects.
  55971. * @param uniformsList The list of uniforms used in the effect
  55972. */
  55973. ColorCurves.PrepareUniforms = function (uniformsList) {
  55974. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  55975. };
  55976. /**
  55977. * Returns color grading data based on a hue, density, saturation and exposure value.
  55978. * @param filterHue The hue of the color filter.
  55979. * @param filterDensity The density of the color filter.
  55980. * @param saturation The saturation.
  55981. * @param exposure The exposure.
  55982. * @param result The result data container.
  55983. */
  55984. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  55985. if (hue == null) {
  55986. return;
  55987. }
  55988. hue = ColorCurves.clamp(hue, 0, 360);
  55989. density = ColorCurves.clamp(density, -100, 100);
  55990. saturation = ColorCurves.clamp(saturation, -100, 100);
  55991. exposure = ColorCurves.clamp(exposure, -100, 100);
  55992. // Remap the slider/config filter density with non-linear mapping and also scale by half
  55993. // so that the maximum filter density is only 50% control. This provides fine control
  55994. // for small values and reasonable range.
  55995. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  55996. density *= 0.5;
  55997. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  55998. if (density < 0) {
  55999. density *= -1;
  56000. hue = (hue + 180) % 360;
  56001. }
  56002. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  56003. result.scaleToRef(2, result);
  56004. result.a = 1 + 0.01 * saturation;
  56005. };
  56006. /**
  56007. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  56008. * @param value The input slider value in range [-100,100].
  56009. * @returns Adjusted value.
  56010. */
  56011. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  56012. value /= 100;
  56013. var x = Math.abs(value);
  56014. x = Math.pow(x, 2);
  56015. if (value < 0) {
  56016. x *= -1;
  56017. }
  56018. x *= 100;
  56019. return x;
  56020. };
  56021. /**
  56022. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  56023. * @param hue The hue (H) input.
  56024. * @param saturation The saturation (S) input.
  56025. * @param brightness The brightness (B) input.
  56026. * @result An RGBA color represented as Vector4.
  56027. */
  56028. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  56029. var h = ColorCurves.clamp(hue, 0, 360);
  56030. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  56031. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  56032. if (s === 0) {
  56033. result.r = v;
  56034. result.g = v;
  56035. result.b = v;
  56036. }
  56037. else {
  56038. // sector 0 to 5
  56039. h /= 60;
  56040. var i = Math.floor(h);
  56041. // fractional part of h
  56042. var f = h - i;
  56043. var p = v * (1 - s);
  56044. var q = v * (1 - s * f);
  56045. var t = v * (1 - s * (1 - f));
  56046. switch (i) {
  56047. case 0:
  56048. result.r = v;
  56049. result.g = t;
  56050. result.b = p;
  56051. break;
  56052. case 1:
  56053. result.r = q;
  56054. result.g = v;
  56055. result.b = p;
  56056. break;
  56057. case 2:
  56058. result.r = p;
  56059. result.g = v;
  56060. result.b = t;
  56061. break;
  56062. case 3:
  56063. result.r = p;
  56064. result.g = q;
  56065. result.b = v;
  56066. break;
  56067. case 4:
  56068. result.r = t;
  56069. result.g = p;
  56070. result.b = v;
  56071. break;
  56072. default:
  56073. result.r = v;
  56074. result.g = p;
  56075. result.b = q;
  56076. break;
  56077. }
  56078. }
  56079. result.a = 1;
  56080. };
  56081. /**
  56082. * Returns a value clamped between min and max
  56083. * @param value The value to clamp
  56084. * @param min The minimum of value
  56085. * @param max The maximum of value
  56086. * @returns The clamped value.
  56087. */
  56088. ColorCurves.clamp = function (value, min, max) {
  56089. return Math.min(Math.max(value, min), max);
  56090. };
  56091. /**
  56092. * Clones the current color curve instance.
  56093. * @return The cloned curves
  56094. */
  56095. ColorCurves.prototype.clone = function () {
  56096. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  56097. };
  56098. /**
  56099. * Serializes the current color curve instance to a json representation.
  56100. * @return a JSON representation
  56101. */
  56102. ColorCurves.prototype.serialize = function () {
  56103. return BABYLON.SerializationHelper.Serialize(this);
  56104. };
  56105. /**
  56106. * Parses the color curve from a json representation.
  56107. * @param source the JSON source to parse
  56108. * @return The parsed curves
  56109. */
  56110. ColorCurves.Parse = function (source) {
  56111. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  56112. };
  56113. return ColorCurves;
  56114. }());
  56115. __decorate([
  56116. BABYLON.serialize()
  56117. ], ColorCurves.prototype, "_globalHue", void 0);
  56118. __decorate([
  56119. BABYLON.serialize()
  56120. ], ColorCurves.prototype, "_globalDensity", void 0);
  56121. __decorate([
  56122. BABYLON.serialize()
  56123. ], ColorCurves.prototype, "_globalSaturation", void 0);
  56124. __decorate([
  56125. BABYLON.serialize()
  56126. ], ColorCurves.prototype, "_globalExposure", void 0);
  56127. __decorate([
  56128. BABYLON.serialize()
  56129. ], ColorCurves.prototype, "_highlightsHue", void 0);
  56130. __decorate([
  56131. BABYLON.serialize()
  56132. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  56133. __decorate([
  56134. BABYLON.serialize()
  56135. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  56136. __decorate([
  56137. BABYLON.serialize()
  56138. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  56139. __decorate([
  56140. BABYLON.serialize()
  56141. ], ColorCurves.prototype, "_midtonesHue", void 0);
  56142. __decorate([
  56143. BABYLON.serialize()
  56144. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  56145. __decorate([
  56146. BABYLON.serialize()
  56147. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  56148. __decorate([
  56149. BABYLON.serialize()
  56150. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  56151. BABYLON.ColorCurves = ColorCurves;
  56152. })(BABYLON || (BABYLON = {}));
  56153. //# sourceMappingURL=babylon.colorCurves.js.map
  56154. var BABYLON;
  56155. (function (BABYLON) {
  56156. var PBRMaterialDefines = (function (_super) {
  56157. __extends(PBRMaterialDefines, _super);
  56158. function PBRMaterialDefines() {
  56159. var _this = _super.call(this) || this;
  56160. _this.ALBEDO = false;
  56161. _this.AMBIENT = false;
  56162. _this.OPACITY = false;
  56163. _this.OPACITYRGB = false;
  56164. _this.REFLECTION = false;
  56165. _this.EMISSIVE = false;
  56166. _this.REFLECTIVITY = false;
  56167. _this.BUMP = false;
  56168. _this.PARALLAX = false;
  56169. _this.PARALLAXOCCLUSION = false;
  56170. _this.SPECULAROVERALPHA = false;
  56171. _this.CLIPPLANE = false;
  56172. _this.ALPHATEST = false;
  56173. _this.ALPHAFROMALBEDO = false;
  56174. _this.POINTSIZE = false;
  56175. _this.FOG = false;
  56176. _this.SPECULARTERM = false;
  56177. _this.OPACITYFRESNEL = false;
  56178. _this.EMISSIVEFRESNEL = false;
  56179. _this.FRESNEL = false;
  56180. _this.NORMAL = false;
  56181. _this.UV1 = false;
  56182. _this.UV2 = false;
  56183. _this.VERTEXCOLOR = false;
  56184. _this.VERTEXALPHA = false;
  56185. _this.NUM_BONE_INFLUENCERS = 0;
  56186. _this.BonesPerMesh = 0;
  56187. _this.INSTANCES = false;
  56188. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  56189. _this.MICROSURFACEAUTOMATIC = false;
  56190. _this.EMISSIVEASILLUMINATION = false;
  56191. _this.LINKEMISSIVEWITHALBEDO = false;
  56192. _this.LIGHTMAP = false;
  56193. _this.USELIGHTMAPASSHADOWMAP = false;
  56194. _this.REFLECTIONMAP_3D = false;
  56195. _this.REFLECTIONMAP_SPHERICAL = false;
  56196. _this.REFLECTIONMAP_PLANAR = false;
  56197. _this.REFLECTIONMAP_CUBIC = false;
  56198. _this.REFLECTIONMAP_PROJECTION = false;
  56199. _this.REFLECTIONMAP_SKYBOX = false;
  56200. _this.REFLECTIONMAP_EXPLICIT = false;
  56201. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  56202. _this.INVERTCUBICMAP = false;
  56203. _this.LOGARITHMICDEPTH = false;
  56204. _this.CAMERATONEMAP = false;
  56205. _this.CAMERACONTRAST = false;
  56206. _this.CAMERACOLORGRADING = false;
  56207. _this.CAMERACOLORCURVES = false;
  56208. _this.OVERLOADEDVALUES = false;
  56209. _this.OVERLOADEDSHADOWVALUES = false;
  56210. _this.USESPHERICALFROMREFLECTIONMAP = false;
  56211. _this.REFRACTION = false;
  56212. _this.REFRACTIONMAP_3D = false;
  56213. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  56214. _this.REFRACTIONMAPINLINEARSPACE = false;
  56215. _this.LODBASEDMICROSFURACE = false;
  56216. _this.USEPHYSICALLIGHTFALLOFF = false;
  56217. _this.RADIANCEOVERALPHA = false;
  56218. _this.USEPMREMREFLECTION = false;
  56219. _this.USEPMREMREFRACTION = false;
  56220. _this.OPENGLNORMALMAP = false;
  56221. _this.INVERTNORMALMAPX = false;
  56222. _this.INVERTNORMALMAPY = false;
  56223. _this.SHADOWFULLFLOAT = false;
  56224. _this.METALLICWORKFLOW = false;
  56225. _this.METALLICROUGHNESSMAP = false;
  56226. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  56227. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  56228. _this.rebuild();
  56229. return _this;
  56230. }
  56231. return PBRMaterialDefines;
  56232. }(BABYLON.MaterialDefines));
  56233. /**
  56234. * The Physically based material of BJS.
  56235. *
  56236. * This offers the main features of a standard PBR material.
  56237. * For more information, please refer to the documentation :
  56238. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  56239. */
  56240. var PBRMaterial = (function (_super) {
  56241. __extends(PBRMaterial, _super);
  56242. /**
  56243. * Instantiates a new PBRMaterial instance.
  56244. *
  56245. * @param name The material name
  56246. * @param scene The scene the material will be use in.
  56247. */
  56248. function PBRMaterial(name, scene) {
  56249. var _this = _super.call(this, name, scene) || this;
  56250. /**
  56251. * Intensity of the direct lights e.g. the four lights available in your scene.
  56252. * This impacts both the direct diffuse and specular highlights.
  56253. */
  56254. _this.directIntensity = 1.0;
  56255. /**
  56256. * Intensity of the emissive part of the material.
  56257. * This helps controlling the emissive effect without modifying the emissive color.
  56258. */
  56259. _this.emissiveIntensity = 1.0;
  56260. /**
  56261. * Intensity of the environment e.g. how much the environment will light the object
  56262. * either through harmonics for rough material or through the refelction for shiny ones.
  56263. */
  56264. _this.environmentIntensity = 1.0;
  56265. /**
  56266. * This is a special control allowing the reduction of the specular highlights coming from the
  56267. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  56268. */
  56269. _this.specularIntensity = 1.0;
  56270. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  56271. /**
  56272. * Debug Control allowing disabling the bump map on this material.
  56273. */
  56274. _this.disableBumpMap = false;
  56275. /**
  56276. * Debug Control helping enforcing or dropping the darkness of shadows.
  56277. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  56278. */
  56279. _this.overloadedShadowIntensity = 1.0;
  56280. /**
  56281. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  56282. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  56283. */
  56284. _this.overloadedShadeIntensity = 1.0;
  56285. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  56286. /**
  56287. * The camera exposure used on this material.
  56288. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  56289. * This corresponds to a photographic exposure.
  56290. */
  56291. _this.cameraExposure = 1.0;
  56292. /**
  56293. * The camera contrast used on this material.
  56294. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  56295. */
  56296. _this.cameraContrast = 1.0;
  56297. /**
  56298. * Color Grading 2D Lookup Texture.
  56299. * This allows special effects like sepia, black and white to sixties rendering style.
  56300. */
  56301. _this.cameraColorGradingTexture = null;
  56302. /**
  56303. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  56304. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  56305. * 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;
  56306. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  56307. */
  56308. _this.cameraColorCurves = null;
  56309. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  56310. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  56311. /**
  56312. * Debug Control allowing to overload the ambient color.
  56313. * This as to be use with the overloadedAmbientIntensity parameter.
  56314. */
  56315. _this.overloadedAmbient = BABYLON.Color3.White();
  56316. /**
  56317. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  56318. */
  56319. _this.overloadedAmbientIntensity = 0.0;
  56320. /**
  56321. * Debug Control allowing to overload the albedo color.
  56322. * This as to be use with the overloadedAlbedoIntensity parameter.
  56323. */
  56324. _this.overloadedAlbedo = BABYLON.Color3.White();
  56325. /**
  56326. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  56327. */
  56328. _this.overloadedAlbedoIntensity = 0.0;
  56329. /**
  56330. * Debug Control allowing to overload the reflectivity color.
  56331. * This as to be use with the overloadedReflectivityIntensity parameter.
  56332. */
  56333. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  56334. /**
  56335. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  56336. */
  56337. _this.overloadedReflectivityIntensity = 0.0;
  56338. /**
  56339. * Debug Control allowing to overload the emissive color.
  56340. * This as to be use with the overloadedEmissiveIntensity parameter.
  56341. */
  56342. _this.overloadedEmissive = BABYLON.Color3.White();
  56343. /**
  56344. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  56345. */
  56346. _this.overloadedEmissiveIntensity = 0.0;
  56347. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  56348. /**
  56349. * Debug Control allowing to overload the reflection color.
  56350. * This as to be use with the overloadedReflectionIntensity parameter.
  56351. */
  56352. _this.overloadedReflection = BABYLON.Color3.White();
  56353. /**
  56354. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  56355. */
  56356. _this.overloadedReflectionIntensity = 0.0;
  56357. /**
  56358. * Debug Control allowing to overload the microsurface.
  56359. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  56360. */
  56361. _this.overloadedMicroSurface = 0.0;
  56362. /**
  56363. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  56364. */
  56365. _this.overloadedMicroSurfaceIntensity = 0.0;
  56366. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  56367. /**
  56368. * AKA Occlusion Texture Intensity in other nomenclature.
  56369. */
  56370. _this.ambientTextureStrength = 1.0;
  56371. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  56372. /**
  56373. * AKA Diffuse Color in other nomenclature.
  56374. */
  56375. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  56376. /**
  56377. * AKA Specular Color in other nomenclature.
  56378. */
  56379. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  56380. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  56381. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  56382. /**
  56383. * AKA Glossiness in other nomenclature.
  56384. */
  56385. _this.microSurface = 0.9;
  56386. /**
  56387. * source material index of refraction (IOR)' / 'destination material IOR.
  56388. */
  56389. _this.indexOfRefraction = 0.66;
  56390. /**
  56391. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  56392. */
  56393. _this.invertRefractionY = false;
  56394. /**
  56395. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  56396. * Materials half opaque for instance using refraction could benefit from this control.
  56397. */
  56398. _this.linkRefractionWithTransparency = false;
  56399. /**
  56400. * The emissive and albedo are linked to never be more than one (Energy conservation).
  56401. */
  56402. _this.linkEmissiveWithAlbedo = false;
  56403. _this.useLightmapAsShadowmap = false;
  56404. /**
  56405. * In this mode, the emissive informtaion will always be added to the lighting once.
  56406. * A light for instance can be thought as emissive.
  56407. */
  56408. _this.useEmissiveAsIllumination = false;
  56409. /**
  56410. * Secifies that the alpha is coming form the albedo channel alpha channel.
  56411. */
  56412. _this.useAlphaFromAlbedoTexture = false;
  56413. /**
  56414. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  56415. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  56416. */
  56417. _this.useSpecularOverAlpha = true;
  56418. /**
  56419. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  56420. */
  56421. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  56422. /**
  56423. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  56424. */
  56425. _this.useRoughnessFromMetallicTextureAlpha = true;
  56426. /**
  56427. * Specifies if the metallic texture contains the roughness information in its green channel.
  56428. */
  56429. _this.useRoughnessFromMetallicTextureGreen = false;
  56430. /**
  56431. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  56432. * The material will try to infer what glossiness each pixel should be.
  56433. */
  56434. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  56435. /**
  56436. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  56437. * the creation of the material.
  56438. */
  56439. _this.useScalarInLinearSpace = false;
  56440. /**
  56441. * BJS is using an harcoded light falloff based on a manually sets up range.
  56442. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  56443. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  56444. */
  56445. _this.usePhysicalLightFalloff = true;
  56446. /**
  56447. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  56448. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  56449. */
  56450. _this.useRadianceOverAlpha = true;
  56451. /**
  56452. * Allows using the bump map in parallax mode.
  56453. */
  56454. _this.useParallax = false;
  56455. /**
  56456. * Allows using the bump map in parallax occlusion mode.
  56457. */
  56458. _this.useParallaxOcclusion = false;
  56459. /**
  56460. * Controls the scale bias of the parallax mode.
  56461. */
  56462. _this.parallaxScaleBias = 0.05;
  56463. /**
  56464. * If sets to true, disables all the lights affecting the material.
  56465. */
  56466. _this.disableLighting = false;
  56467. /**
  56468. * Number of Simultaneous lights allowed on the material.
  56469. */
  56470. _this.maxSimultaneousLights = 4;
  56471. /**
  56472. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  56473. */
  56474. _this.invertNormalMapX = false;
  56475. /**
  56476. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  56477. */
  56478. _this.invertNormalMapY = false;
  56479. _this._renderTargets = new BABYLON.SmartArray(16);
  56480. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  56481. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  56482. _this._tempColor = new BABYLON.Color3();
  56483. _this._defines = new PBRMaterialDefines();
  56484. _this._cachedDefines = new PBRMaterialDefines();
  56485. _this._myScene = null;
  56486. _this._myShadowGenerator = null;
  56487. _this._cachedDefines.BonesPerMesh = -1;
  56488. _this.getRenderTargetTextures = function () {
  56489. _this._renderTargets.reset();
  56490. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  56491. _this._renderTargets.push(_this.reflectionTexture);
  56492. }
  56493. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  56494. _this._renderTargets.push(_this.refractionTexture);
  56495. }
  56496. return _this._renderTargets;
  56497. };
  56498. return _this;
  56499. }
  56500. PBRMaterial.prototype.getClassName = function () {
  56501. return "PBRMaterial";
  56502. };
  56503. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  56504. get: function () {
  56505. return this._useLogarithmicDepth;
  56506. },
  56507. set: function (value) {
  56508. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  56509. },
  56510. enumerable: true,
  56511. configurable: true
  56512. });
  56513. PBRMaterial.prototype.needAlphaBlending = function () {
  56514. if (this.linkRefractionWithTransparency) {
  56515. return false;
  56516. }
  56517. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  56518. };
  56519. PBRMaterial.prototype.needAlphaTesting = function () {
  56520. if (this.linkRefractionWithTransparency) {
  56521. return false;
  56522. }
  56523. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  56524. };
  56525. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  56526. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  56527. };
  56528. PBRMaterial.prototype.getAlphaTestTexture = function () {
  56529. return this.albedoTexture;
  56530. };
  56531. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  56532. if (!mesh) {
  56533. return true;
  56534. }
  56535. if (this._defines.INSTANCES !== useInstances) {
  56536. return false;
  56537. }
  56538. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  56539. return true;
  56540. }
  56541. return false;
  56542. };
  56543. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  56544. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  56545. };
  56546. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  56547. if (!useScalarInLinear) {
  56548. color.toLinearSpaceToRef(ref);
  56549. }
  56550. else {
  56551. ref.r = color.r;
  56552. ref.g = color.g;
  56553. ref.b = color.b;
  56554. }
  56555. };
  56556. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  56557. var lightIndex = 0;
  56558. var depthValuesAlreadySet = false;
  56559. for (var index = 0; index < scene.lights.length; index++) {
  56560. var light = scene.lights[index];
  56561. if (!light.isEnabled()) {
  56562. continue;
  56563. }
  56564. if (!light.canAffectMesh(mesh)) {
  56565. continue;
  56566. }
  56567. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  56568. // GAMMA CORRECTION.
  56569. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  56570. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  56571. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  56572. if (defines["SPECULARTERM"]) {
  56573. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  56574. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  56575. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  56576. }
  56577. // Shadows
  56578. if (scene.shadowsEnabled) {
  56579. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  56580. }
  56581. lightIndex++;
  56582. if (lightIndex === maxSimultaneousLights)
  56583. break;
  56584. }
  56585. };
  56586. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  56587. if (this.isFrozen) {
  56588. if (this._wasPreviouslyReady) {
  56589. return true;
  56590. }
  56591. }
  56592. var scene = this.getScene();
  56593. var engine = scene.getEngine();
  56594. var needNormals = false;
  56595. var needUVs = false;
  56596. this._defines.reset();
  56597. if (scene.lightsEnabled && !this.disableLighting) {
  56598. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  56599. }
  56600. if (!this.checkReadyOnEveryCall) {
  56601. if (this._renderId === scene.getRenderId()) {
  56602. if (this._checkCache(scene, mesh, useInstances)) {
  56603. return true;
  56604. }
  56605. }
  56606. }
  56607. if (scene.texturesEnabled) {
  56608. if (scene.getEngine().getCaps().textureLOD) {
  56609. this._defines.LODBASEDMICROSFURACE = true;
  56610. }
  56611. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  56612. if (!this.albedoTexture.isReady()) {
  56613. return false;
  56614. }
  56615. else {
  56616. needUVs = true;
  56617. this._defines.ALBEDO = true;
  56618. }
  56619. }
  56620. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  56621. if (!this.ambientTexture.isReady()) {
  56622. return false;
  56623. }
  56624. else {
  56625. needUVs = true;
  56626. this._defines.AMBIENT = true;
  56627. }
  56628. }
  56629. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  56630. if (!this.opacityTexture.isReady()) {
  56631. return false;
  56632. }
  56633. else {
  56634. needUVs = true;
  56635. this._defines.OPACITY = true;
  56636. if (this.opacityTexture.getAlphaFromRGB) {
  56637. this._defines.OPACITYRGB = true;
  56638. }
  56639. }
  56640. }
  56641. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  56642. if (!this.reflectionTexture.isReady()) {
  56643. return false;
  56644. }
  56645. else {
  56646. needNormals = true;
  56647. this._defines.REFLECTION = true;
  56648. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  56649. this._defines.INVERTCUBICMAP = true;
  56650. }
  56651. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  56652. switch (this.reflectionTexture.coordinatesMode) {
  56653. case BABYLON.Texture.CUBIC_MODE:
  56654. case BABYLON.Texture.INVCUBIC_MODE:
  56655. this._defines.REFLECTIONMAP_CUBIC = true;
  56656. break;
  56657. case BABYLON.Texture.EXPLICIT_MODE:
  56658. this._defines.REFLECTIONMAP_EXPLICIT = true;
  56659. break;
  56660. case BABYLON.Texture.PLANAR_MODE:
  56661. this._defines.REFLECTIONMAP_PLANAR = true;
  56662. break;
  56663. case BABYLON.Texture.PROJECTION_MODE:
  56664. this._defines.REFLECTIONMAP_PROJECTION = true;
  56665. break;
  56666. case BABYLON.Texture.SKYBOX_MODE:
  56667. this._defines.REFLECTIONMAP_SKYBOX = true;
  56668. break;
  56669. case BABYLON.Texture.SPHERICAL_MODE:
  56670. this._defines.REFLECTIONMAP_SPHERICAL = true;
  56671. break;
  56672. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  56673. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  56674. break;
  56675. }
  56676. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  56677. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  56678. needNormals = true;
  56679. if (this.reflectionTexture.isPMREM) {
  56680. this._defines.USEPMREMREFLECTION = true;
  56681. }
  56682. }
  56683. }
  56684. }
  56685. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  56686. if (!this.lightmapTexture.isReady()) {
  56687. return false;
  56688. }
  56689. else {
  56690. needUVs = true;
  56691. this._defines.LIGHTMAP = true;
  56692. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  56693. }
  56694. }
  56695. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  56696. if (!this.emissiveTexture.isReady()) {
  56697. return false;
  56698. }
  56699. else {
  56700. needUVs = true;
  56701. this._defines.EMISSIVE = true;
  56702. }
  56703. }
  56704. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  56705. if (this.metallicTexture) {
  56706. if (!this.metallicTexture.isReady()) {
  56707. return false;
  56708. }
  56709. else {
  56710. needUVs = true;
  56711. this._defines.METALLICWORKFLOW = true;
  56712. this._defines.METALLICROUGHNESSMAP = true;
  56713. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  56714. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  56715. }
  56716. }
  56717. else if (this.reflectivityTexture) {
  56718. if (!this.reflectivityTexture.isReady()) {
  56719. return false;
  56720. }
  56721. else {
  56722. needUVs = true;
  56723. this._defines.REFLECTIVITY = true;
  56724. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  56725. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  56726. }
  56727. }
  56728. }
  56729. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  56730. if (!this.bumpTexture.isReady()) {
  56731. return false;
  56732. }
  56733. else {
  56734. needUVs = true;
  56735. this._defines.BUMP = true;
  56736. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  56737. this._defines.PARALLAX = true;
  56738. if (this.useParallaxOcclusion) {
  56739. this._defines.PARALLAXOCCLUSION = true;
  56740. }
  56741. }
  56742. if (this.invertNormalMapX) {
  56743. this._defines.INVERTNORMALMAPX = true;
  56744. }
  56745. if (this.invertNormalMapY) {
  56746. this._defines.INVERTNORMALMAPY = true;
  56747. }
  56748. if (scene._mirroredCameraPosition) {
  56749. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  56750. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  56751. }
  56752. }
  56753. }
  56754. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  56755. if (!this.refractionTexture.isReady()) {
  56756. return false;
  56757. }
  56758. else {
  56759. needUVs = true;
  56760. this._defines.REFRACTION = true;
  56761. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  56762. if (this.linkRefractionWithTransparency) {
  56763. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  56764. }
  56765. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  56766. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  56767. if (this.refractionTexture.isPMREM) {
  56768. this._defines.USEPMREMREFRACTION = true;
  56769. }
  56770. }
  56771. }
  56772. }
  56773. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  56774. if (!this.cameraColorGradingTexture.isReady()) {
  56775. return false;
  56776. }
  56777. else {
  56778. this._defines.CAMERACOLORGRADING = true;
  56779. }
  56780. }
  56781. }
  56782. // Effect
  56783. if (scene.clipPlane) {
  56784. this._defines.CLIPPLANE = true;
  56785. }
  56786. if (engine.getAlphaTesting()) {
  56787. this._defines.ALPHATEST = true;
  56788. }
  56789. if (this._shouldUseAlphaFromAlbedoTexture()) {
  56790. this._defines.ALPHAFROMALBEDO = true;
  56791. }
  56792. if (this.useEmissiveAsIllumination) {
  56793. this._defines.EMISSIVEASILLUMINATION = true;
  56794. }
  56795. if (this.linkEmissiveWithAlbedo) {
  56796. this._defines.LINKEMISSIVEWITHALBEDO = true;
  56797. }
  56798. if (this.useLogarithmicDepth) {
  56799. this._defines.LOGARITHMICDEPTH = true;
  56800. }
  56801. if (this.cameraContrast != 1) {
  56802. this._defines.CAMERACONTRAST = true;
  56803. }
  56804. if (this.cameraExposure != 1) {
  56805. this._defines.CAMERATONEMAP = true;
  56806. }
  56807. if (this.cameraColorCurves) {
  56808. this._defines.CAMERACOLORCURVES = true;
  56809. }
  56810. if (this.overloadedShadeIntensity != 1 ||
  56811. this.overloadedShadowIntensity != 1) {
  56812. this._defines.OVERLOADEDSHADOWVALUES = true;
  56813. }
  56814. if (this.overloadedMicroSurfaceIntensity > 0 ||
  56815. this.overloadedEmissiveIntensity > 0 ||
  56816. this.overloadedReflectivityIntensity > 0 ||
  56817. this.overloadedAlbedoIntensity > 0 ||
  56818. this.overloadedAmbientIntensity > 0 ||
  56819. this.overloadedReflectionIntensity > 0) {
  56820. this._defines.OVERLOADEDVALUES = true;
  56821. }
  56822. // Point size
  56823. if (this.pointsCloud || scene.forcePointsCloud) {
  56824. this._defines.POINTSIZE = true;
  56825. }
  56826. // Fog
  56827. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56828. this._defines.FOG = true;
  56829. }
  56830. if (BABYLON.StandardMaterial.FresnelEnabled) {
  56831. // Fresnel
  56832. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  56833. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  56834. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  56835. this._defines.OPACITYFRESNEL = true;
  56836. }
  56837. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  56838. this._defines.EMISSIVEFRESNEL = true;
  56839. }
  56840. needNormals = true;
  56841. this._defines.FRESNEL = true;
  56842. }
  56843. }
  56844. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  56845. this._defines.SPECULAROVERALPHA = true;
  56846. }
  56847. if (this.usePhysicalLightFalloff) {
  56848. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  56849. }
  56850. if (this.useRadianceOverAlpha) {
  56851. this._defines.RADIANCEOVERALPHA = true;
  56852. }
  56853. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  56854. this._defines.METALLICWORKFLOW = true;
  56855. }
  56856. // Attribs
  56857. if (mesh) {
  56858. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  56859. this._defines.NORMAL = true;
  56860. }
  56861. if (needUVs) {
  56862. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56863. this._defines.UV1 = true;
  56864. }
  56865. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56866. this._defines.UV2 = true;
  56867. }
  56868. }
  56869. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  56870. this._defines.VERTEXCOLOR = true;
  56871. if (mesh.hasVertexAlpha) {
  56872. this._defines.VERTEXALPHA = true;
  56873. }
  56874. }
  56875. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56876. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  56877. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  56878. }
  56879. // Instances
  56880. if (useInstances) {
  56881. this._defines.INSTANCES = true;
  56882. }
  56883. }
  56884. // Get correct effect
  56885. if (!this._defines.isEqual(this._cachedDefines)) {
  56886. this._defines.cloneTo(this._cachedDefines);
  56887. scene.resetCachedMaterial();
  56888. // Fallbacks
  56889. var fallbacks = new BABYLON.EffectFallbacks();
  56890. if (this._defines.REFLECTION) {
  56891. fallbacks.addFallback(0, "REFLECTION");
  56892. }
  56893. if (this._defines.REFRACTION) {
  56894. fallbacks.addFallback(0, "REFRACTION");
  56895. }
  56896. if (this._defines.REFLECTIVITY) {
  56897. fallbacks.addFallback(0, "REFLECTIVITY");
  56898. }
  56899. if (this._defines.BUMP) {
  56900. fallbacks.addFallback(0, "BUMP");
  56901. }
  56902. if (this._defines.PARALLAX) {
  56903. fallbacks.addFallback(1, "PARALLAX");
  56904. }
  56905. if (this._defines.PARALLAXOCCLUSION) {
  56906. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  56907. }
  56908. if (this._defines.SPECULAROVERALPHA) {
  56909. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  56910. }
  56911. if (this._defines.FOG) {
  56912. fallbacks.addFallback(1, "FOG");
  56913. }
  56914. if (this._defines.POINTSIZE) {
  56915. fallbacks.addFallback(0, "POINTSIZE");
  56916. }
  56917. if (this._defines.LOGARITHMICDEPTH) {
  56918. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  56919. }
  56920. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  56921. if (this._defines.SPECULARTERM) {
  56922. fallbacks.addFallback(0, "SPECULARTERM");
  56923. }
  56924. if (this._defines.OPACITYFRESNEL) {
  56925. fallbacks.addFallback(1, "OPACITYFRESNEL");
  56926. }
  56927. if (this._defines.EMISSIVEFRESNEL) {
  56928. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  56929. }
  56930. if (this._defines.FRESNEL) {
  56931. fallbacks.addFallback(3, "FRESNEL");
  56932. }
  56933. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  56934. fallbacks.addCPUSkinningFallback(0, mesh);
  56935. }
  56936. //Attributes
  56937. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56938. if (this._defines.NORMAL) {
  56939. attribs.push(BABYLON.VertexBuffer.NormalKind);
  56940. }
  56941. if (this._defines.UV1) {
  56942. attribs.push(BABYLON.VertexBuffer.UVKind);
  56943. }
  56944. if (this._defines.UV2) {
  56945. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56946. }
  56947. if (this._defines.VERTEXCOLOR) {
  56948. attribs.push(BABYLON.VertexBuffer.ColorKind);
  56949. }
  56950. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  56951. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  56952. // Legacy browser patch
  56953. var join = this._defines.toString();
  56954. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  56955. "vFogInfos", "vFogColor", "pointSize",
  56956. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  56957. "mBones",
  56958. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  56959. "depthValues",
  56960. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  56961. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  56962. "logarithmicDepthConstant",
  56963. "vSphericalX", "vSphericalY", "vSphericalZ",
  56964. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  56965. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  56966. "vMicrosurfaceTextureLods",
  56967. "vCameraInfos"
  56968. ];
  56969. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  56970. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  56971. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  56972. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  56973. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  56974. }
  56975. if (!this._effect.isReady()) {
  56976. return false;
  56977. }
  56978. this._renderId = scene.getRenderId();
  56979. this._wasPreviouslyReady = true;
  56980. if (mesh) {
  56981. if (!mesh._materialDefines) {
  56982. mesh._materialDefines = new PBRMaterialDefines();
  56983. }
  56984. this._defines.cloneTo(mesh._materialDefines);
  56985. }
  56986. return true;
  56987. };
  56988. PBRMaterial.prototype.unbind = function () {
  56989. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  56990. this._effect.setTexture("reflection2DSampler", null);
  56991. }
  56992. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  56993. this._effect.setTexture("refraction2DSampler", null);
  56994. }
  56995. _super.prototype.unbind.call(this);
  56996. };
  56997. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  56998. this._effect.setMatrix("world", world);
  56999. };
  57000. PBRMaterial.prototype.bind = function (world, mesh) {
  57001. this._myScene = this.getScene();
  57002. // Matrices
  57003. this.bindOnlyWorldMatrix(world);
  57004. // Bones
  57005. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  57006. if (this._myScene.getCachedMaterial() !== this) {
  57007. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  57008. if (BABYLON.StandardMaterial.FresnelEnabled) {
  57009. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  57010. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  57011. }
  57012. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  57013. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  57014. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  57015. }
  57016. }
  57017. // Textures
  57018. if (this._myScene.texturesEnabled) {
  57019. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  57020. this._effect.setTexture("albedoSampler", this.albedoTexture);
  57021. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  57022. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  57023. }
  57024. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  57025. this._effect.setTexture("ambientSampler", this.ambientTexture);
  57026. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  57027. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  57028. }
  57029. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  57030. this._effect.setTexture("opacitySampler", this.opacityTexture);
  57031. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  57032. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  57033. }
  57034. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  57035. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  57036. if (this.reflectionTexture.isCube) {
  57037. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  57038. }
  57039. else {
  57040. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  57041. }
  57042. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  57043. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  57044. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  57045. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  57046. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  57047. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  57048. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  57049. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  57050. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  57051. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  57052. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  57053. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  57054. }
  57055. }
  57056. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  57057. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  57058. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  57059. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  57060. }
  57061. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  57062. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  57063. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  57064. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  57065. }
  57066. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  57067. if (this.metallicTexture) {
  57068. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  57069. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  57070. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  57071. }
  57072. else if (this.reflectivityTexture) {
  57073. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  57074. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  57075. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  57076. }
  57077. }
  57078. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  57079. this._effect.setTexture("bumpSampler", this.bumpTexture);
  57080. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  57081. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  57082. }
  57083. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  57084. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  57085. var depth = 1.0;
  57086. if (this.refractionTexture.isCube) {
  57087. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  57088. }
  57089. else {
  57090. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  57091. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  57092. if (this.refractionTexture.depth) {
  57093. depth = this.refractionTexture.depth;
  57094. }
  57095. }
  57096. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  57097. }
  57098. if ((this.reflectionTexture || this.refractionTexture)) {
  57099. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  57100. }
  57101. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  57102. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  57103. }
  57104. }
  57105. // Clip plane
  57106. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  57107. // Point size
  57108. if (this.pointsCloud) {
  57109. this._effect.setFloat("pointSize", this.pointSize);
  57110. }
  57111. // Colors
  57112. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  57113. if (this._defines.METALLICWORKFLOW) {
  57114. PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
  57115. PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
  57116. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  57117. }
  57118. else {
  57119. // GAMMA CORRECTION.
  57120. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  57121. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  57122. }
  57123. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  57124. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  57125. // GAMMA CORRECTION.
  57126. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  57127. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  57128. // GAMMA CORRECTION.
  57129. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  57130. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  57131. }
  57132. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  57133. // GAMMA CORRECTION.
  57134. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  57135. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  57136. // Lights
  57137. if (this._myScene.lightsEnabled && !this.disableLighting) {
  57138. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  57139. }
  57140. // View
  57141. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  57142. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  57143. }
  57144. // Fog
  57145. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  57146. this._lightingInfos.x = this.directIntensity;
  57147. this._lightingInfos.y = this.emissiveIntensity;
  57148. this._lightingInfos.z = this.environmentIntensity;
  57149. this._lightingInfos.w = this.specularIntensity;
  57150. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  57151. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  57152. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  57153. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  57154. this._cameraInfos.x = this.cameraExposure;
  57155. this._cameraInfos.y = this.cameraContrast;
  57156. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  57157. if (this.cameraColorCurves) {
  57158. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  57159. }
  57160. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  57161. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  57162. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  57163. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  57164. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  57165. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  57166. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  57167. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  57168. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  57169. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  57170. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  57171. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  57172. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  57173. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  57174. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  57175. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  57176. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  57177. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  57178. // Log. depth
  57179. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  57180. }
  57181. _super.prototype.bind.call(this, world, mesh);
  57182. this._myScene = null;
  57183. };
  57184. PBRMaterial.prototype.getAnimatables = function () {
  57185. var results = [];
  57186. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  57187. results.push(this.albedoTexture);
  57188. }
  57189. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  57190. results.push(this.ambientTexture);
  57191. }
  57192. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  57193. results.push(this.opacityTexture);
  57194. }
  57195. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  57196. results.push(this.reflectionTexture);
  57197. }
  57198. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  57199. results.push(this.emissiveTexture);
  57200. }
  57201. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  57202. results.push(this.metallicTexture);
  57203. }
  57204. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  57205. results.push(this.reflectivityTexture);
  57206. }
  57207. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  57208. results.push(this.bumpTexture);
  57209. }
  57210. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  57211. results.push(this.lightmapTexture);
  57212. }
  57213. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  57214. results.push(this.refractionTexture);
  57215. }
  57216. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  57217. results.push(this.cameraColorGradingTexture);
  57218. }
  57219. return results;
  57220. };
  57221. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  57222. if (forceDisposeTextures) {
  57223. if (this.albedoTexture) {
  57224. this.albedoTexture.dispose();
  57225. }
  57226. if (this.ambientTexture) {
  57227. this.ambientTexture.dispose();
  57228. }
  57229. if (this.opacityTexture) {
  57230. this.opacityTexture.dispose();
  57231. }
  57232. if (this.reflectionTexture) {
  57233. this.reflectionTexture.dispose();
  57234. }
  57235. if (this.emissiveTexture) {
  57236. this.emissiveTexture.dispose();
  57237. }
  57238. if (this.metallicTexture) {
  57239. this.metallicTexture.dispose();
  57240. }
  57241. if (this.reflectivityTexture) {
  57242. this.reflectivityTexture.dispose();
  57243. }
  57244. if (this.bumpTexture) {
  57245. this.bumpTexture.dispose();
  57246. }
  57247. if (this.lightmapTexture) {
  57248. this.lightmapTexture.dispose();
  57249. }
  57250. if (this.refractionTexture) {
  57251. this.refractionTexture.dispose();
  57252. }
  57253. if (this.cameraColorGradingTexture) {
  57254. this.cameraColorGradingTexture.dispose();
  57255. }
  57256. }
  57257. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  57258. };
  57259. PBRMaterial.prototype.clone = function (name) {
  57260. var _this = this;
  57261. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  57262. };
  57263. PBRMaterial.prototype.serialize = function () {
  57264. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  57265. serializationObject.customType = "BABYLON.PBRMaterial";
  57266. return serializationObject;
  57267. };
  57268. // Statics
  57269. PBRMaterial.Parse = function (source, scene, rootUrl) {
  57270. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  57271. };
  57272. return PBRMaterial;
  57273. }(BABYLON.Material));
  57274. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  57275. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  57276. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  57277. PBRMaterial._scaledReflection = new BABYLON.Color3();
  57278. __decorate([
  57279. BABYLON.serialize()
  57280. ], PBRMaterial.prototype, "directIntensity", void 0);
  57281. __decorate([
  57282. BABYLON.serialize()
  57283. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  57284. __decorate([
  57285. BABYLON.serialize()
  57286. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  57287. __decorate([
  57288. BABYLON.serialize()
  57289. ], PBRMaterial.prototype, "specularIntensity", void 0);
  57290. __decorate([
  57291. BABYLON.serialize()
  57292. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  57293. __decorate([
  57294. BABYLON.serialize()
  57295. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  57296. __decorate([
  57297. BABYLON.serialize()
  57298. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  57299. __decorate([
  57300. BABYLON.serialize()
  57301. ], PBRMaterial.prototype, "cameraExposure", void 0);
  57302. __decorate([
  57303. BABYLON.serialize()
  57304. ], PBRMaterial.prototype, "cameraContrast", void 0);
  57305. __decorate([
  57306. BABYLON.serializeAsTexture()
  57307. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  57308. __decorate([
  57309. BABYLON.serializeAsColorCurves()
  57310. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  57311. __decorate([
  57312. BABYLON.serializeAsColor3()
  57313. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  57314. __decorate([
  57315. BABYLON.serialize()
  57316. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  57317. __decorate([
  57318. BABYLON.serializeAsColor3()
  57319. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  57320. __decorate([
  57321. BABYLON.serialize()
  57322. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  57323. __decorate([
  57324. BABYLON.serializeAsColor3()
  57325. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  57326. __decorate([
  57327. BABYLON.serialize()
  57328. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  57329. __decorate([
  57330. BABYLON.serializeAsColor3()
  57331. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  57332. __decorate([
  57333. BABYLON.serialize()
  57334. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  57335. __decorate([
  57336. BABYLON.serializeAsColor3()
  57337. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  57338. __decorate([
  57339. BABYLON.serialize()
  57340. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  57341. __decorate([
  57342. BABYLON.serialize()
  57343. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  57344. __decorate([
  57345. BABYLON.serialize()
  57346. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  57347. __decorate([
  57348. BABYLON.serializeAsTexture()
  57349. ], PBRMaterial.prototype, "albedoTexture", void 0);
  57350. __decorate([
  57351. BABYLON.serializeAsTexture()
  57352. ], PBRMaterial.prototype, "ambientTexture", void 0);
  57353. __decorate([
  57354. BABYLON.serialize()
  57355. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  57356. __decorate([
  57357. BABYLON.serializeAsTexture()
  57358. ], PBRMaterial.prototype, "opacityTexture", void 0);
  57359. __decorate([
  57360. BABYLON.serializeAsTexture()
  57361. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  57362. __decorate([
  57363. BABYLON.serializeAsTexture()
  57364. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  57365. __decorate([
  57366. BABYLON.serializeAsTexture()
  57367. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  57368. __decorate([
  57369. BABYLON.serializeAsTexture()
  57370. ], PBRMaterial.prototype, "metallicTexture", void 0);
  57371. __decorate([
  57372. BABYLON.serialize()
  57373. ], PBRMaterial.prototype, "metallic", void 0);
  57374. __decorate([
  57375. BABYLON.serialize()
  57376. ], PBRMaterial.prototype, "roughness", void 0);
  57377. __decorate([
  57378. BABYLON.serializeAsTexture()
  57379. ], PBRMaterial.prototype, "bumpTexture", void 0);
  57380. __decorate([
  57381. BABYLON.serializeAsTexture()
  57382. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  57383. __decorate([
  57384. BABYLON.serializeAsTexture()
  57385. ], PBRMaterial.prototype, "refractionTexture", void 0);
  57386. __decorate([
  57387. BABYLON.serializeAsColor3("ambient")
  57388. ], PBRMaterial.prototype, "ambientColor", void 0);
  57389. __decorate([
  57390. BABYLON.serializeAsColor3("albedo")
  57391. ], PBRMaterial.prototype, "albedoColor", void 0);
  57392. __decorate([
  57393. BABYLON.serializeAsColor3("reflectivity")
  57394. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  57395. __decorate([
  57396. BABYLON.serializeAsColor3("reflection")
  57397. ], PBRMaterial.prototype, "reflectionColor", void 0);
  57398. __decorate([
  57399. BABYLON.serializeAsColor3("emissive")
  57400. ], PBRMaterial.prototype, "emissiveColor", void 0);
  57401. __decorate([
  57402. BABYLON.serialize()
  57403. ], PBRMaterial.prototype, "microSurface", void 0);
  57404. __decorate([
  57405. BABYLON.serialize()
  57406. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  57407. __decorate([
  57408. BABYLON.serialize()
  57409. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  57410. __decorate([
  57411. BABYLON.serializeAsFresnelParameters()
  57412. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  57413. __decorate([
  57414. BABYLON.serializeAsFresnelParameters()
  57415. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  57416. __decorate([
  57417. BABYLON.serialize()
  57418. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  57419. __decorate([
  57420. BABYLON.serialize()
  57421. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  57422. __decorate([
  57423. BABYLON.serialize()
  57424. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  57425. __decorate([
  57426. BABYLON.serialize()
  57427. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  57428. __decorate([
  57429. BABYLON.serialize()
  57430. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  57431. __decorate([
  57432. BABYLON.serialize()
  57433. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  57434. __decorate([
  57435. BABYLON.serialize()
  57436. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  57437. __decorate([
  57438. BABYLON.serialize()
  57439. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  57440. __decorate([
  57441. BABYLON.serialize()
  57442. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  57443. __decorate([
  57444. BABYLON.serialize()
  57445. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  57446. __decorate([
  57447. BABYLON.serialize()
  57448. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  57449. __decorate([
  57450. BABYLON.serialize()
  57451. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  57452. __decorate([
  57453. BABYLON.serialize()
  57454. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  57455. __decorate([
  57456. BABYLON.serialize()
  57457. ], PBRMaterial.prototype, "useParallax", void 0);
  57458. __decorate([
  57459. BABYLON.serialize()
  57460. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  57461. __decorate([
  57462. BABYLON.serialize()
  57463. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  57464. __decorate([
  57465. BABYLON.serialize()
  57466. ], PBRMaterial.prototype, "disableLighting", void 0);
  57467. __decorate([
  57468. BABYLON.serialize()
  57469. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  57470. __decorate([
  57471. BABYLON.serialize()
  57472. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  57473. __decorate([
  57474. BABYLON.serialize()
  57475. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  57476. __decorate([
  57477. BABYLON.serialize()
  57478. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  57479. BABYLON.PBRMaterial = PBRMaterial;
  57480. })(BABYLON || (BABYLON = {}));
  57481. //# sourceMappingURL=babylon.pbrMaterial.js.map
  57482. var BABYLON;
  57483. (function (BABYLON) {
  57484. var DebugLayer = (function () {
  57485. function DebugLayer(scene) {
  57486. this._scene = scene;
  57487. }
  57488. /** Creates the inspector window. */
  57489. DebugLayer.prototype._createInspector = function (popup) {
  57490. if (!this._inspector) {
  57491. this._inspector = new INSPECTOR.Inspector(this._scene, popup);
  57492. } // else nothing to do,; instance is already existing
  57493. };
  57494. DebugLayer.prototype.isVisible = function () {
  57495. return false;
  57496. };
  57497. DebugLayer.prototype.hide = function () {
  57498. if (this._inspector) {
  57499. this._inspector.dispose();
  57500. this._inspector = null;
  57501. }
  57502. };
  57503. DebugLayer.prototype.show = function (popup) {
  57504. if (typeof INSPECTOR == 'undefined') {
  57505. // Load inspector and add it to the DOM
  57506. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, popup));
  57507. }
  57508. else {
  57509. // Otherwise creates the inspector
  57510. this._createInspector(popup);
  57511. }
  57512. };
  57513. return DebugLayer;
  57514. }());
  57515. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  57516. BABYLON.DebugLayer = DebugLayer;
  57517. })(BABYLON || (BABYLON = {}));
  57518. //# sourceMappingURL=babylon.debugLayer.js.map
  57519. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  57520. var BABYLON;
  57521. (function (BABYLON) {
  57522. var StandardRenderingPipeline = (function (_super) {
  57523. __extends(StandardRenderingPipeline, _super);
  57524. /**
  57525. * @constructor
  57526. * @param {string} name - The rendering pipeline name
  57527. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57528. * @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)
  57529. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  57530. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57531. */
  57532. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  57533. if (originalPostProcess === void 0) { originalPostProcess = null; }
  57534. var _this = _super.call(this, scene.getEngine(), name) || this;
  57535. _this.downSampleX4PostProcess = null;
  57536. _this.brightPassPostProcess = null;
  57537. _this.gaussianBlurHPostProcesses = [];
  57538. _this.gaussianBlurVPostProcesses = [];
  57539. _this.textureAdderPostProcess = null;
  57540. _this.textureAdderFinalPostProcess = null;
  57541. _this.lensFlarePostProcess = null;
  57542. _this.lensFlareComposePostProcess = null;
  57543. _this.depthOfFieldPostProcess = null;
  57544. // Values
  57545. _this.brightThreshold = 1.0;
  57546. _this.blurWidth = 2.0;
  57547. _this.gaussianCoefficient = 0.25;
  57548. _this.gaussianMean = 1.0;
  57549. _this.gaussianStandardDeviation = 1.0;
  57550. _this.exposure = 1.0;
  57551. _this.lensTexture = null;
  57552. _this.lensColorTexture = null;
  57553. _this.lensFlareStrength = 20.0;
  57554. _this.lensFlareGhostDispersal = 1.4;
  57555. _this.lensFlareHaloWidth = 0.7;
  57556. _this.lensFlareDistortionStrength = 16.0;
  57557. _this.lensStarTexture = null;
  57558. _this.lensFlareDirtTexture = null;
  57559. _this.depthOfFieldDistance = 10.0;
  57560. // IAnimatable
  57561. _this.animations = [];
  57562. _this._depthRenderer = null;
  57563. // Getters and setters
  57564. _this._depthOfFieldEnabled = true;
  57565. _this._lensFlareEnabled = true;
  57566. // Initialize
  57567. _this._scene = scene;
  57568. // Create pass post-processe
  57569. if (!originalPostProcess) {
  57570. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  57571. }
  57572. else {
  57573. _this.originalPostProcess = originalPostProcess;
  57574. }
  57575. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  57576. // Create down sample X4 post-process
  57577. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  57578. // Create bright pass post-process
  57579. _this._createBrightPassPostProcess(scene, ratio / 2);
  57580. // Create gaussian blur post-processes (down sampling blurs)
  57581. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  57582. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  57583. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  57584. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  57585. // Create texture adder post-process
  57586. _this._createTextureAdderPostProcess(scene, ratio);
  57587. // Create depth-of-field source post-process
  57588. _this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57589. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  57590. // Create lens flare post-process
  57591. _this._createLensFlarePostProcess(scene, ratio);
  57592. // Create gaussian blur used by depth-of-field
  57593. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  57594. // Create depth-of-field post-process
  57595. _this._createDepthOfFieldPostProcess(scene, ratio);
  57596. // Finish
  57597. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57598. if (cameras !== null) {
  57599. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57600. }
  57601. // Deactivate
  57602. _this.LensFlareEnabled = false;
  57603. _this.DepthOfFieldEnabled = false;
  57604. return _this;
  57605. }
  57606. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  57607. get: function () {
  57608. return this._depthOfFieldEnabled;
  57609. },
  57610. set: function (enabled) {
  57611. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  57612. if (enabled && !this._depthOfFieldEnabled) {
  57613. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  57614. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  57615. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  57616. this._depthRenderer = this._scene.enableDepthRenderer();
  57617. }
  57618. else if (!enabled && this._depthOfFieldEnabled) {
  57619. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  57620. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  57621. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  57622. }
  57623. this._depthOfFieldEnabled = enabled;
  57624. },
  57625. enumerable: true,
  57626. configurable: true
  57627. });
  57628. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  57629. get: function () {
  57630. return this._lensFlareEnabled;
  57631. },
  57632. set: function (enabled) {
  57633. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  57634. if (enabled && !this._lensFlareEnabled) {
  57635. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  57636. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  57637. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  57638. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  57639. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  57640. }
  57641. else if (!enabled && this._lensFlareEnabled) {
  57642. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  57643. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  57644. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  57645. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  57646. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  57647. }
  57648. this._lensFlareEnabled = enabled;
  57649. },
  57650. enumerable: true,
  57651. configurable: true
  57652. });
  57653. // Down Sample X4 Post-Processs
  57654. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  57655. var _this = this;
  57656. var downSampleX4Offsets = new Array(32);
  57657. 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);
  57658. this.downSampleX4PostProcess.onApply = function (effect) {
  57659. var id = 0;
  57660. for (var i = -2; i < 2; i++) {
  57661. for (var j = -2; j < 2; j++) {
  57662. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  57663. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  57664. id += 2;
  57665. }
  57666. }
  57667. effect.setArray2("dsOffsets", downSampleX4Offsets);
  57668. };
  57669. // Add to pipeline
  57670. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  57671. };
  57672. // Brightpass Post-Process
  57673. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  57674. var _this = this;
  57675. var brightOffsets = new Array(8);
  57676. 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);
  57677. this.brightPassPostProcess.onApply = function (effect) {
  57678. var sU = (1.0 / _this.brightPassPostProcess.width);
  57679. var sV = (1.0 / _this.brightPassPostProcess.height);
  57680. brightOffsets[0] = -0.5 * sU;
  57681. brightOffsets[1] = 0.5 * sV;
  57682. brightOffsets[2] = 0.5 * sU;
  57683. brightOffsets[3] = 0.5 * sV;
  57684. brightOffsets[4] = -0.5 * sU;
  57685. brightOffsets[5] = -0.5 * sV;
  57686. brightOffsets[6] = 0.5 * sU;
  57687. brightOffsets[7] = -0.5 * sV;
  57688. effect.setArray2("dsOffsets", brightOffsets);
  57689. effect.setFloat("brightThreshold", _this.brightThreshold);
  57690. };
  57691. // Add to pipeline
  57692. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  57693. };
  57694. // Create gaussian blur H&V post-processes
  57695. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  57696. var _this = this;
  57697. var blurOffsets = new Array(9);
  57698. var blurWeights = new Array(9);
  57699. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  57700. var callback = function (height) {
  57701. return function (effect) {
  57702. // Weights
  57703. var x = 0.0;
  57704. for (var i = 0; i < 9; i++) {
  57705. x = (i - 4.0) / 4.0;
  57706. blurWeights[i] =
  57707. _this.gaussianCoefficient
  57708. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  57709. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  57710. }
  57711. var lastOutputDimensions = {
  57712. width: scene.getEngine().getRenderWidth(),
  57713. height: scene.getEngine().getRenderHeight()
  57714. };
  57715. for (var i = 0; i < 9; i++) {
  57716. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  57717. blurOffsets[i] = value;
  57718. }
  57719. effect.setArray("blurOffsets", blurOffsets);
  57720. effect.setArray("blurWeights", blurWeights);
  57721. effect.setFloat("blurWidth", _this.blurWidth);
  57722. };
  57723. };
  57724. // Create horizontal gaussian blur post-processes
  57725. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57726. gaussianBlurHPostProcess.onApply = callback(false);
  57727. // Create vertical gaussian blur post-process
  57728. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57729. gaussianBlurVPostProcess.onApply = callback(true);
  57730. // Add to pipeline
  57731. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  57732. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  57733. // Finish
  57734. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  57735. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  57736. };
  57737. // Create texture adder post-process
  57738. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  57739. var _this = this;
  57740. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  57741. 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);
  57742. this.textureAdderPostProcess.onApply = function (effect) {
  57743. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  57744. effect.setTexture("lensSampler", _this.lensTexture);
  57745. effect.setFloat("exposure", _this.exposure);
  57746. };
  57747. // Add to pipeline
  57748. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  57749. };
  57750. // Create lens flare post-process
  57751. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  57752. var _this = this;
  57753. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57754. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  57755. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  57756. 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);
  57757. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  57758. var resolution = new BABYLON.Vector2(0, 0);
  57759. // Lens flare
  57760. this.lensFlarePostProcess.onApply = function (effect) {
  57761. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  57762. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  57763. effect.setFloat("strength", _this.lensFlareStrength);
  57764. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  57765. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  57766. // Shift
  57767. resolution.x = _this.lensFlarePostProcess.width;
  57768. resolution.y = _this.lensFlarePostProcess.height;
  57769. effect.setVector2("resolution", resolution);
  57770. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  57771. };
  57772. // Compose
  57773. 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);
  57774. 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);
  57775. this.lensFlareComposePostProcess.onApply = function (effect) {
  57776. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  57777. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  57778. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  57779. // Lens start rotation matrix
  57780. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  57781. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  57782. 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));
  57783. camRot *= 4.0;
  57784. 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);
  57785. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  57786. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  57787. };
  57788. };
  57789. // Create depth-of-field post-process
  57790. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  57791. var _this = this;
  57792. 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);
  57793. this.depthOfFieldPostProcess.onApply = function (effect) {
  57794. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  57795. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  57796. effect.setFloat("distance", _this.depthOfFieldDistance);
  57797. };
  57798. // Add to pipeline
  57799. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  57800. };
  57801. // Dispose
  57802. StandardRenderingPipeline.prototype.dispose = function () {
  57803. for (var i = 0; i < this._scene.cameras.length; i++) {
  57804. var camera = this._scene.cameras[i];
  57805. this.originalPostProcess.dispose(camera);
  57806. this.downSampleX4PostProcess.dispose(camera);
  57807. this.brightPassPostProcess.dispose(camera);
  57808. this.textureAdderPostProcess.dispose(camera);
  57809. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  57810. this.gaussianBlurHPostProcesses[j].dispose(camera);
  57811. }
  57812. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  57813. this.gaussianBlurVPostProcesses[j].dispose(camera);
  57814. }
  57815. this.textureAdderFinalPostProcess.dispose(camera);
  57816. this.lensFlarePostProcess.dispose(camera);
  57817. this.lensFlareComposePostProcess.dispose(camera);
  57818. this.depthOfFieldPostProcess.dispose(camera);
  57819. }
  57820. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57821. _super.prototype.dispose.call(this);
  57822. };
  57823. return StandardRenderingPipeline;
  57824. }(BABYLON.PostProcessRenderPipeline));
  57825. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  57826. })(BABYLON || (BABYLON = {}));
  57827. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  57828. 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#ifdef REFLECTIONMAP_EQUIRECTANGULAR_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 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#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\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 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<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_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#ifdef REFLECTIONMAP_EQUIRECTANGULAR_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<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":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","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#ifdef REFLECTIONMAP_EQUIRECTANGULAR_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<pbrShadowFunctions>\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\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#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\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 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<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_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#ifdef REFLECTIONMAP_EQUIRECTANGULAR_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<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\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\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\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\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\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}"};
  57829. 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)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,vBumpUV);\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(viewDirectionW,TBN,vBumpUV+uvOffset);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\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(vec3 viewDir,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","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 SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\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 SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\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","pbrShadowFunctions":"\n#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,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\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 bias,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\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) 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 computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\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))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\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 bias,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\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) 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}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,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 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\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#ifdef REFLECTIONMAP_EQUIRECTANGULAR_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;\nreturn vec3(s,t,0);\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,float bias)\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))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,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\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\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))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,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\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,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 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\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"};
  57830. 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),!(n<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=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,D>=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,D>=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){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;c<a;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?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);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.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);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,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.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){var o=t.r+(i.r-t.r)*n,e=t.g+(i.g-t.g)*n,s=t.b+(i.b-t.b)*n;return new r(o,e,s)},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.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.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,a=.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),u=.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);return new r(a,u)},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,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y;return new r(c,p)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n;return new r(o,e)},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){var n=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new r(n,o)},r.Maximize=function(t,i){var n=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new r(n,o)},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.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},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,a=.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),u=.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),m=.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);return new r(a,u,m)},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,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},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){F.Vector3[0].x=t.y*i.z-t.z*i.y,F.Vector3[0].y=t.z*i.x-t.x*i.z,F.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(F.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=F.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.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}();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.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){var r=new t(this.width+i.width,this.height+i.height);return r},t.prototype.subtract=function(i){var r=new t(this.width-i.width,this.height-i.height);return r},t.Lerp=function(i,r,n){var o=i.width+(r.width-i.width)*n,e=i.height+(r.height-i.height)*n;return new t(o,e)},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.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(){var t=new i(-this.x,-this.y,-this.z,this.w);return t},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,y=.4999999;return m<-y?(t.y=2*Math.atan2(o,e),t.x=Math.PI/2,t.z=0):m>y?(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.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=F.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),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),F=1/(i*T+r*_+n*M+o*A),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,V=s*y-h*m,q=e*c-a*u,D=e*y-h*u,N=e*m-s*u;return t.m[0]=T*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=A*F,t.m[1]=-(r*z-n*w+o*v)*F,t.m[5]=(i*z-n*d+o*g)*F,t.m[9]=-(i*w-r*d+o*R)*F,t.m[13]=(i*v-r*g+n*R)*F,t.m[2]=(r*b-n*L+o*C)*F,t.m[6]=-(i*b-n*P+o*Z)*F,t.m[10]=(i*L-r*P+o*S)*F,t.m[14]=-(i*C-r*Z+n*S)*F,t.m[3]=-(r*I-n*H+o*V)*F,t.m[7]=(i*I-n*q+o*D)*F,t.m[11]=-(i*H-r*q+o*N)*F,t.m[15]=(i*V-r*D+n*N)*F,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){\nvoid 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],M=t.m[6],A=t.m[7],F=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*F+s*P,i[r+1]=n*d+o*_+e*b+s*Z,i[r+2]=n*g+o*M+e*L+s*S,i[r+3]=n*R+o*A+e*C+s*I,i[r+4]=h*v+a*T+u*F+m*P,i[r+5]=h*d+a*_+u*b+m*Z,i[r+6]=h*g+a*M+u*L+m*S,i[r+7]=h*R+a*A+u*C+m*I,i[r+8]=y*v+c*T+p*F+f*P,i[r+9]=y*d+c*_+p*b+f*Z,i[r+10]=y*g+c*M+p*L+f*S,i[r+11]=y*R+c*A+p*C+f*I,i[r+12]=x*v+l*T+z*F+w*P,i[r+13]=x*d+l*_+z*b+w*Z,i[r+14]=x*g+l*M+z*L+w*S,i[r+15]=x*R+l*A+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,F.Matrix[0]),a.FromRotationMatrixToRef(F.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,F.Matrix[1]),i.toRotationMatrix(F.Matrix[0]),F.Matrix[1].multiplyToRef(F.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=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);n.m[0]=u,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=m,n.m[6]=n.m[7]=0,n.m[8]=(h-a)*u*.5,n.m[9]=-((e-s)*m*.5),n.m[10]=-(i+r)/(r-i),n.m[11]=1,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,h=n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],a=n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],m=n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],y=n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15];return new t(h,a,m,y)},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){var r=e.Dot(this.normal,t);return r<=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;var p;!function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(p=t.Space||(t.Space={}));var f=function(){function t(){}return t}();f.X=new e(1,0,0),f.Y=new e(0,1,0),f.Z=new e(0,0,1),t.Axis=f;var x=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,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,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=x;var l;!function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(l=t.Orientation||(t.Orientation={}));var z=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),o=Math.atan2(n.y,n.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=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=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.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?l.CW:l.CCW,this.angle=z.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=w;var v=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 w(s,h,a),m=u.angle.radians()/e;u.orientation===l.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],r=this._points[0];t+=r.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=v;var d=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=d;var g=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){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},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){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o;return e},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));var s=new t(n);return s},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=g;var R=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=R;var T=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=T;var _=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=_;var M=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=M;var A=function(){function t(){}return t}();A.Color3=[r.Black(),r.Black(),r.Black()],A.Vector2=[o.Zero(),o.Zero(),o.Zero()],A.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],A.Vector4=[s.Zero(),s.Zero(),s.Zero()],A.Quaternion=[a.Zero(),a.Zero()],A.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=A;var F=function(){function t(){}return t}();F.Vector3=[e.Zero()],F.Matrix=[u.Zero(),u.Zero()],F.Quaternion=[a.Zero()]}(BABYLON||(BABYLON={}));";
  57831. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  57832. module.exports = BABYLON;
  57833. };