babylon.max.js 2.8 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261
  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. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. }());
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. return Color3;
  211. }());
  212. BABYLON.Color3 = Color3;
  213. var Color4 = (function () {
  214. function Color4(r, g, b, a) {
  215. this.r = r;
  216. this.g = g;
  217. this.b = b;
  218. this.a = a;
  219. }
  220. // Operators
  221. Color4.prototype.addInPlace = function (right) {
  222. this.r += right.r;
  223. this.g += right.g;
  224. this.b += right.b;
  225. this.a += right.a;
  226. return this;
  227. };
  228. Color4.prototype.asArray = function () {
  229. var result = [];
  230. this.toArray(result, 0);
  231. return result;
  232. };
  233. Color4.prototype.toArray = function (array, index) {
  234. if (index === undefined) {
  235. index = 0;
  236. }
  237. array[index] = this.r;
  238. array[index + 1] = this.g;
  239. array[index + 2] = this.b;
  240. array[index + 3] = this.a;
  241. return this;
  242. };
  243. Color4.prototype.add = function (right) {
  244. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  245. };
  246. Color4.prototype.subtract = function (right) {
  247. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  248. };
  249. Color4.prototype.subtractToRef = function (right, result) {
  250. result.r = this.r - right.r;
  251. result.g = this.g - right.g;
  252. result.b = this.b - right.b;
  253. result.a = this.a - right.a;
  254. return this;
  255. };
  256. Color4.prototype.scale = function (scale) {
  257. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  258. };
  259. Color4.prototype.scaleToRef = function (scale, result) {
  260. result.r = this.r * scale;
  261. result.g = this.g * scale;
  262. result.b = this.b * scale;
  263. result.a = this.a * scale;
  264. return this;
  265. };
  266. /**
  267. * Multipy an RGBA Color4 value by another and return a new Color4 object
  268. * @param color The Color4 (RGBA) value to multiply by
  269. * @returns A new Color4.
  270. */
  271. Color4.prototype.multiply = function (color) {
  272. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  273. };
  274. /**
  275. * Multipy an RGBA Color4 value by another and push the result in a reference value
  276. * @param color The Color4 (RGBA) value to multiply by
  277. * @param result The Color4 (RGBA) to fill the result in
  278. * @returns the result Color4.
  279. */
  280. Color4.prototype.multiplyToRef = function (color, result) {
  281. result.r = this.r * color.r;
  282. result.g = this.g * color.g;
  283. result.b = this.b * color.b;
  284. result.a = this.a * color.a;
  285. return result;
  286. };
  287. Color4.prototype.toString = function () {
  288. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  289. };
  290. Color4.prototype.getClassName = function () {
  291. return "Color4";
  292. };
  293. Color4.prototype.getHashCode = function () {
  294. var hash = this.r || 0;
  295. hash = (hash * 397) ^ (this.g || 0);
  296. hash = (hash * 397) ^ (this.b || 0);
  297. hash = (hash * 397) ^ (this.a || 0);
  298. return hash;
  299. };
  300. Color4.prototype.clone = function () {
  301. return new Color4(this.r, this.g, this.b, this.a);
  302. };
  303. Color4.prototype.copyFrom = function (source) {
  304. this.r = source.r;
  305. this.g = source.g;
  306. this.b = source.b;
  307. this.a = source.a;
  308. return this;
  309. };
  310. Color4.prototype.toHexString = function () {
  311. var intR = (this.r * 255) | 0;
  312. var intG = (this.g * 255) | 0;
  313. var intB = (this.b * 255) | 0;
  314. var intA = (this.a * 255) | 0;
  315. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  316. };
  317. // Statics
  318. Color4.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  320. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  321. return new Color4(0, 0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. var a = parseInt(hex.substring(7, 9), 16);
  327. return Color4.FromInts(r, g, b, a);
  328. };
  329. Color4.Lerp = function (left, right, amount) {
  330. var result = new Color4(0, 0, 0, 0);
  331. Color4.LerpToRef(left, right, amount, result);
  332. return result;
  333. };
  334. Color4.LerpToRef = function (left, right, amount, result) {
  335. result.r = left.r + (right.r - left.r) * amount;
  336. result.g = left.g + (right.g - left.g) * amount;
  337. result.b = left.b + (right.b - left.b) * amount;
  338. result.a = left.a + (right.a - left.a) * amount;
  339. };
  340. Color4.FromArray = function (array, offset) {
  341. if (offset === void 0) { offset = 0; }
  342. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  343. };
  344. Color4.FromInts = function (r, g, b, a) {
  345. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  346. };
  347. Color4.CheckColors4 = function (colors, count) {
  348. // Check if color3 was used
  349. if (colors.length === count * 3) {
  350. var colors4 = [];
  351. for (var index = 0; index < colors.length; index += 3) {
  352. var newIndex = (index / 3) * 4;
  353. colors4[newIndex] = colors[index];
  354. colors4[newIndex + 1] = colors[index + 1];
  355. colors4[newIndex + 2] = colors[index + 2];
  356. colors4[newIndex + 3] = 1.0;
  357. }
  358. return colors4;
  359. }
  360. return colors;
  361. };
  362. return Color4;
  363. }());
  364. BABYLON.Color4 = Color4;
  365. var Vector2 = (function () {
  366. function Vector2(x, y) {
  367. this.x = x;
  368. this.y = y;
  369. }
  370. Vector2.prototype.toString = function () {
  371. return "{X: " + this.x + " Y:" + this.y + "}";
  372. };
  373. Vector2.prototype.getClassName = function () {
  374. return "Vector2";
  375. };
  376. Vector2.prototype.getHashCode = function () {
  377. var hash = this.x || 0;
  378. hash = (hash * 397) ^ (this.y || 0);
  379. return hash;
  380. };
  381. // Operators
  382. Vector2.prototype.toArray = function (array, index) {
  383. if (index === void 0) { index = 0; }
  384. array[index] = this.x;
  385. array[index + 1] = this.y;
  386. return this;
  387. };
  388. Vector2.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. Vector2.prototype.copyFrom = function (source) {
  394. this.x = source.x;
  395. this.y = source.y;
  396. return this;
  397. };
  398. Vector2.prototype.copyFromFloats = function (x, y) {
  399. this.x = x;
  400. this.y = y;
  401. return this;
  402. };
  403. Vector2.prototype.add = function (otherVector) {
  404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  405. };
  406. Vector2.prototype.addToRef = function (otherVector, result) {
  407. result.x = this.x + otherVector.x;
  408. result.y = this.y + otherVector.y;
  409. return this;
  410. };
  411. Vector2.prototype.addInPlace = function (otherVector) {
  412. this.x += otherVector.x;
  413. this.y += otherVector.y;
  414. return this;
  415. };
  416. Vector2.prototype.addVector3 = function (otherVector) {
  417. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  418. };
  419. Vector2.prototype.subtract = function (otherVector) {
  420. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  421. };
  422. Vector2.prototype.subtractToRef = function (otherVector, result) {
  423. result.x = this.x - otherVector.x;
  424. result.y = this.y - otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiplyInPlace = function (otherVector) {
  433. this.x *= otherVector.x;
  434. this.y *= otherVector.y;
  435. return this;
  436. };
  437. Vector2.prototype.multiply = function (otherVector) {
  438. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  439. };
  440. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  441. result.x = this.x * otherVector.x;
  442. result.y = this.y * otherVector.y;
  443. return this;
  444. };
  445. Vector2.prototype.multiplyByFloats = function (x, y) {
  446. return new Vector2(this.x * x, this.y * y);
  447. };
  448. Vector2.prototype.divide = function (otherVector) {
  449. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  450. };
  451. Vector2.prototype.divideToRef = function (otherVector, result) {
  452. result.x = this.x / otherVector.x;
  453. result.y = this.y / otherVector.y;
  454. return this;
  455. };
  456. Vector2.prototype.negate = function () {
  457. return new Vector2(-this.x, -this.y);
  458. };
  459. Vector2.prototype.scaleInPlace = function (scale) {
  460. this.x *= scale;
  461. this.y *= scale;
  462. return this;
  463. };
  464. Vector2.prototype.scale = function (scale) {
  465. return new Vector2(this.x * scale, this.y * scale);
  466. };
  467. Vector2.prototype.equals = function (otherVector) {
  468. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  469. };
  470. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  471. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  472. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  473. };
  474. // Properties
  475. Vector2.prototype.length = function () {
  476. return Math.sqrt(this.x * this.x + this.y * this.y);
  477. };
  478. Vector2.prototype.lengthSquared = function () {
  479. return (this.x * this.x + this.y * this.y);
  480. };
  481. // Methods
  482. Vector2.prototype.normalize = function () {
  483. var len = this.length();
  484. if (len === 0)
  485. return this;
  486. var num = 1.0 / len;
  487. this.x *= num;
  488. this.y *= num;
  489. return this;
  490. };
  491. Vector2.prototype.clone = function () {
  492. return new Vector2(this.x, this.y);
  493. };
  494. // Statics
  495. Vector2.Zero = function () {
  496. return new Vector2(0, 0);
  497. };
  498. Vector2.FromArray = function (array, offset) {
  499. if (offset === void 0) { offset = 0; }
  500. return new Vector2(array[offset], array[offset + 1]);
  501. };
  502. Vector2.FromArrayToRef = function (array, offset, result) {
  503. result.x = array[offset];
  504. result.y = array[offset + 1];
  505. };
  506. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  507. var squared = amount * amount;
  508. var cubed = amount * squared;
  509. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  510. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  511. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  512. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  513. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  514. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  515. return new Vector2(x, y);
  516. };
  517. Vector2.Clamp = function (value, min, max) {
  518. var x = value.x;
  519. x = (x > max.x) ? max.x : x;
  520. x = (x < min.x) ? min.x : x;
  521. var y = value.y;
  522. y = (y > max.y) ? max.y : y;
  523. y = (y < min.y) ? min.y : y;
  524. return new Vector2(x, y);
  525. };
  526. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  527. var squared = amount * amount;
  528. var cubed = amount * squared;
  529. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  530. var part2 = (-2.0 * cubed) + (3.0 * squared);
  531. var part3 = (cubed - (2.0 * squared)) + amount;
  532. var part4 = cubed - squared;
  533. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  534. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Lerp = function (start, end, amount) {
  538. var x = start.x + ((end.x - start.x) * amount);
  539. var y = start.y + ((end.y - start.y) * amount);
  540. return new Vector2(x, y);
  541. };
  542. Vector2.Dot = function (left, right) {
  543. return left.x * right.x + left.y * right.y;
  544. };
  545. Vector2.Normalize = function (vector) {
  546. var newVector = vector.clone();
  547. newVector.normalize();
  548. return newVector;
  549. };
  550. Vector2.Minimize = function (left, right) {
  551. var x = (left.x < right.x) ? left.x : right.x;
  552. var y = (left.y < right.y) ? left.y : right.y;
  553. return new Vector2(x, y);
  554. };
  555. Vector2.Maximize = function (left, right) {
  556. var x = (left.x > right.x) ? left.x : right.x;
  557. var y = (left.y > right.y) ? left.y : right.y;
  558. return new Vector2(x, y);
  559. };
  560. Vector2.Transform = function (vector, transformation) {
  561. var r = Vector2.Zero();
  562. Vector2.TransformToRef(vector, transformation, r);
  563. return r;
  564. };
  565. Vector2.TransformToRef = function (vector, transformation, result) {
  566. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  567. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  568. result.x = x;
  569. result.y = y;
  570. };
  571. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  572. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  573. var sign = a < 0 ? -1 : 1;
  574. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  575. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  576. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  577. };
  578. Vector2.Distance = function (value1, value2) {
  579. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  580. };
  581. Vector2.DistanceSquared = function (value1, value2) {
  582. var x = value1.x - value2.x;
  583. var y = value1.y - value2.y;
  584. return (x * x) + (y * y);
  585. };
  586. Vector2.Center = function (value1, value2) {
  587. var center = value1.add(value2);
  588. center.scaleInPlace(0.5);
  589. return center;
  590. };
  591. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  592. var l2 = Vector2.DistanceSquared(segA, segB);
  593. if (l2 === 0.0) {
  594. return Vector2.Distance(p, segA);
  595. }
  596. var v = segB.subtract(segA);
  597. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  598. var proj = segA.add(v.multiplyByFloats(t, t));
  599. return Vector2.Distance(p, proj);
  600. };
  601. return Vector2;
  602. }());
  603. BABYLON.Vector2 = Vector2;
  604. var Vector3 = (function () {
  605. function Vector3(x, y, z) {
  606. this.x = x;
  607. this.y = y;
  608. this.z = z;
  609. }
  610. Vector3.prototype.toString = function () {
  611. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  612. };
  613. Vector3.prototype.getClassName = function () {
  614. return "Vector3";
  615. };
  616. Vector3.prototype.getHashCode = function () {
  617. var hash = this.x || 0;
  618. hash = (hash * 397) ^ (this.y || 0);
  619. hash = (hash * 397) ^ (this.z || 0);
  620. return hash;
  621. };
  622. // Operators
  623. Vector3.prototype.asArray = function () {
  624. var result = [];
  625. this.toArray(result, 0);
  626. return result;
  627. };
  628. Vector3.prototype.toArray = function (array, index) {
  629. if (index === void 0) { index = 0; }
  630. array[index] = this.x;
  631. array[index + 1] = this.y;
  632. array[index + 2] = this.z;
  633. return this;
  634. };
  635. Vector3.prototype.toQuaternion = function () {
  636. var result = new Quaternion(0, 0, 0, 1);
  637. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  638. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  639. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  640. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  641. var cosy = Math.cos(this.y * 0.5);
  642. var siny = Math.sin(this.y * 0.5);
  643. result.x = coszMinusx * siny;
  644. result.y = -sinzMinusx * siny;
  645. result.z = sinxPlusz * cosy;
  646. result.w = cosxPlusz * cosy;
  647. return result;
  648. };
  649. Vector3.prototype.addInPlace = function (otherVector) {
  650. this.x += otherVector.x;
  651. this.y += otherVector.y;
  652. this.z += otherVector.z;
  653. return this;
  654. };
  655. Vector3.prototype.add = function (otherVector) {
  656. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  657. };
  658. Vector3.prototype.addToRef = function (otherVector, result) {
  659. result.x = this.x + otherVector.x;
  660. result.y = this.y + otherVector.y;
  661. result.z = this.z + otherVector.z;
  662. return this;
  663. };
  664. Vector3.prototype.subtractInPlace = function (otherVector) {
  665. this.x -= otherVector.x;
  666. this.y -= otherVector.y;
  667. this.z -= otherVector.z;
  668. return this;
  669. };
  670. Vector3.prototype.subtract = function (otherVector) {
  671. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  672. };
  673. Vector3.prototype.subtractToRef = function (otherVector, result) {
  674. result.x = this.x - otherVector.x;
  675. result.y = this.y - otherVector.y;
  676. result.z = this.z - otherVector.z;
  677. return this;
  678. };
  679. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  680. return new Vector3(this.x - x, this.y - y, this.z - z);
  681. };
  682. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  683. result.x = this.x - x;
  684. result.y = this.y - y;
  685. result.z = this.z - z;
  686. return this;
  687. };
  688. Vector3.prototype.negate = function () {
  689. return new Vector3(-this.x, -this.y, -this.z);
  690. };
  691. Vector3.prototype.scaleInPlace = function (scale) {
  692. this.x *= scale;
  693. this.y *= scale;
  694. this.z *= scale;
  695. return this;
  696. };
  697. Vector3.prototype.scale = function (scale) {
  698. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  699. };
  700. Vector3.prototype.scaleToRef = function (scale, result) {
  701. result.x = this.x * scale;
  702. result.y = this.y * scale;
  703. result.z = this.z * scale;
  704. };
  705. Vector3.prototype.equals = function (otherVector) {
  706. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  707. };
  708. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  709. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  710. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  711. };
  712. Vector3.prototype.equalsToFloats = function (x, y, z) {
  713. return this.x === x && this.y === y && this.z === z;
  714. };
  715. Vector3.prototype.multiplyInPlace = function (otherVector) {
  716. this.x *= otherVector.x;
  717. this.y *= otherVector.y;
  718. this.z *= otherVector.z;
  719. return this;
  720. };
  721. Vector3.prototype.multiply = function (otherVector) {
  722. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  723. };
  724. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  725. result.x = this.x * otherVector.x;
  726. result.y = this.y * otherVector.y;
  727. result.z = this.z * otherVector.z;
  728. return this;
  729. };
  730. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  731. return new Vector3(this.x * x, this.y * y, this.z * z);
  732. };
  733. Vector3.prototype.divide = function (otherVector) {
  734. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  735. };
  736. Vector3.prototype.divideToRef = function (otherVector, result) {
  737. result.x = this.x / otherVector.x;
  738. result.y = this.y / otherVector.y;
  739. result.z = this.z / otherVector.z;
  740. return this;
  741. };
  742. Vector3.prototype.MinimizeInPlace = function (other) {
  743. if (other.x < this.x)
  744. this.x = other.x;
  745. if (other.y < this.y)
  746. this.y = other.y;
  747. if (other.z < this.z)
  748. this.z = other.z;
  749. return this;
  750. };
  751. Vector3.prototype.MaximizeInPlace = function (other) {
  752. if (other.x > this.x)
  753. this.x = other.x;
  754. if (other.y > this.y)
  755. this.y = other.y;
  756. if (other.z > this.z)
  757. this.z = other.z;
  758. return this;
  759. };
  760. // Properties
  761. Vector3.prototype.length = function () {
  762. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  763. };
  764. Vector3.prototype.lengthSquared = function () {
  765. return (this.x * this.x + this.y * this.y + this.z * this.z);
  766. };
  767. // Methods
  768. Vector3.prototype.normalize = function () {
  769. var len = this.length();
  770. if (len === 0 || len === 1.0)
  771. return this;
  772. var num = 1.0 / len;
  773. this.x *= num;
  774. this.y *= num;
  775. this.z *= num;
  776. return this;
  777. };
  778. Vector3.prototype.clone = function () {
  779. return new Vector3(this.x, this.y, this.z);
  780. };
  781. Vector3.prototype.copyFrom = function (source) {
  782. this.x = source.x;
  783. this.y = source.y;
  784. this.z = source.z;
  785. return this;
  786. };
  787. Vector3.prototype.copyFromFloats = function (x, y, z) {
  788. this.x = x;
  789. this.y = y;
  790. this.z = z;
  791. return this;
  792. };
  793. // Statics
  794. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  795. var d0 = Vector3.Dot(vector0, axis) - size;
  796. var d1 = Vector3.Dot(vector1, axis) - size;
  797. var s = d0 / (d0 - d1);
  798. return s;
  799. };
  800. Vector3.FromArray = function (array, offset) {
  801. if (!offset) {
  802. offset = 0;
  803. }
  804. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  805. };
  806. Vector3.FromFloatArray = function (array, offset) {
  807. if (!offset) {
  808. offset = 0;
  809. }
  810. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  811. };
  812. Vector3.FromArrayToRef = function (array, offset, result) {
  813. result.x = array[offset];
  814. result.y = array[offset + 1];
  815. result.z = array[offset + 2];
  816. };
  817. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  818. result.x = array[offset];
  819. result.y = array[offset + 1];
  820. result.z = array[offset + 2];
  821. };
  822. Vector3.FromFloatsToRef = function (x, y, z, result) {
  823. result.x = x;
  824. result.y = y;
  825. result.z = z;
  826. };
  827. Vector3.Zero = function () {
  828. return new Vector3(0, 0, 0);
  829. };
  830. Vector3.Up = function () {
  831. return new Vector3(0, 1.0, 0);
  832. };
  833. Vector3.Forward = function () {
  834. return new Vector3(0, 0, 1.0);
  835. };
  836. Vector3.Right = function () {
  837. return new Vector3(1.0, 0, 0);
  838. };
  839. Vector3.Left = function () {
  840. return new Vector3(-1.0, 0, 0);
  841. };
  842. Vector3.TransformCoordinates = function (vector, transformation) {
  843. var result = Vector3.Zero();
  844. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  845. return result;
  846. };
  847. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  848. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  849. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  850. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  851. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  852. result.x = x / w;
  853. result.y = y / w;
  854. result.z = z / w;
  855. };
  856. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  857. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  858. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  859. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  860. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  861. result.x = rx / rw;
  862. result.y = ry / rw;
  863. result.z = rz / rw;
  864. };
  865. Vector3.TransformNormal = function (vector, transformation) {
  866. var result = Vector3.Zero();
  867. Vector3.TransformNormalToRef(vector, transformation, result);
  868. return result;
  869. };
  870. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  871. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  872. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  873. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  874. result.x = x;
  875. result.y = y;
  876. result.z = z;
  877. };
  878. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  879. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  880. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  881. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  882. };
  883. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  884. var squared = amount * amount;
  885. var cubed = amount * squared;
  886. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  887. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  888. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  889. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  890. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  891. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  892. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  893. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  894. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  895. return new Vector3(x, y, z);
  896. };
  897. Vector3.Clamp = function (value, min, max) {
  898. var x = value.x;
  899. x = (x > max.x) ? max.x : x;
  900. x = (x < min.x) ? min.x : x;
  901. var y = value.y;
  902. y = (y > max.y) ? max.y : y;
  903. y = (y < min.y) ? min.y : y;
  904. var z = value.z;
  905. z = (z > max.z) ? max.z : z;
  906. z = (z < min.z) ? min.z : z;
  907. return new Vector3(x, y, z);
  908. };
  909. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  910. var squared = amount * amount;
  911. var cubed = amount * squared;
  912. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  913. var part2 = (-2.0 * cubed) + (3.0 * squared);
  914. var part3 = (cubed - (2.0 * squared)) + amount;
  915. var part4 = cubed - squared;
  916. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  917. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  918. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  919. return new Vector3(x, y, z);
  920. };
  921. Vector3.Lerp = function (start, end, amount) {
  922. var x = start.x + ((end.x - start.x) * amount);
  923. var y = start.y + ((end.y - start.y) * amount);
  924. var z = start.z + ((end.z - start.z) * amount);
  925. return new Vector3(x, y, z);
  926. };
  927. Vector3.Dot = function (left, right) {
  928. return (left.x * right.x + left.y * right.y + left.z * right.z);
  929. };
  930. Vector3.Cross = function (left, right) {
  931. var result = Vector3.Zero();
  932. Vector3.CrossToRef(left, right, result);
  933. return result;
  934. };
  935. Vector3.CrossToRef = function (left, right, result) {
  936. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  937. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  938. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  939. result.copyFrom(Tmp.Vector3[0]);
  940. };
  941. Vector3.Normalize = function (vector) {
  942. var result = Vector3.Zero();
  943. Vector3.NormalizeToRef(vector, result);
  944. return result;
  945. };
  946. Vector3.NormalizeToRef = function (vector, result) {
  947. result.copyFrom(vector);
  948. result.normalize();
  949. };
  950. Vector3.Project = function (vector, world, transform, viewport) {
  951. var cw = viewport.width;
  952. var ch = viewport.height;
  953. var cx = viewport.x;
  954. var cy = viewport.y;
  955. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  956. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1, viewportMatrix);
  957. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  958. world.multiplyToRef(transform, matrix);
  959. matrix.multiplyToRef(viewportMatrix, matrix);
  960. return Vector3.TransformCoordinates(vector, matrix);
  961. };
  962. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  963. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  964. world.multiplyToRef(transform, matrix);
  965. matrix.invert();
  966. source.x = source.x / viewportWidth * 2 - 1;
  967. source.y = -(source.y / viewportHeight * 2 - 1);
  968. var vector = Vector3.TransformCoordinates(source, matrix);
  969. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  970. if (MathTools.WithinEpsilon(num, 1.0)) {
  971. vector = vector.scale(1.0 / num);
  972. }
  973. return vector;
  974. };
  975. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  976. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  977. world.multiplyToRef(view, matrix);
  978. matrix.multiplyToRef(projection, matrix);
  979. matrix.invert();
  980. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  981. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  982. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  983. if (MathTools.WithinEpsilon(num, 1.0)) {
  984. vector = vector.scale(1.0 / num);
  985. }
  986. return vector;
  987. };
  988. Vector3.Minimize = function (left, right) {
  989. var min = left.clone();
  990. min.MinimizeInPlace(right);
  991. return min;
  992. };
  993. Vector3.Maximize = function (left, right) {
  994. var max = left.clone();
  995. max.MaximizeInPlace(right);
  996. return max;
  997. };
  998. Vector3.Distance = function (value1, value2) {
  999. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1000. };
  1001. Vector3.DistanceSquared = function (value1, value2) {
  1002. var x = value1.x - value2.x;
  1003. var y = value1.y - value2.y;
  1004. var z = value1.z - value2.z;
  1005. return (x * x) + (y * y) + (z * z);
  1006. };
  1007. Vector3.Center = function (value1, value2) {
  1008. var center = value1.add(value2);
  1009. center.scaleInPlace(0.5);
  1010. return center;
  1011. };
  1012. /**
  1013. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1014. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1015. * to something in order to rotate it from its local system to the given target system.
  1016. */
  1017. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1018. var rotation = Vector3.Zero();
  1019. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1020. return rotation;
  1021. };
  1022. /**
  1023. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1024. */
  1025. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1026. var u = axis1.normalize();
  1027. var w = axis3.normalize();
  1028. // world axis
  1029. var X = Axis.X;
  1030. var Y = Axis.Y;
  1031. // equation unknowns and vars
  1032. var yaw = 0.0;
  1033. var pitch = 0.0;
  1034. var roll = 0.0;
  1035. var x = 0.0;
  1036. var y = 0.0;
  1037. var z = 0.0;
  1038. var t = 0.0;
  1039. var sign = -1.0;
  1040. var nbRevert = 0;
  1041. var cross = Tmp.Vector3[0];
  1042. var dot = 0.0;
  1043. // step 1 : rotation around w
  1044. // Rv3(u) = u1, and u1 belongs to plane xOz
  1045. // Rv3(w) = w1 = w invariant
  1046. var u1 = Tmp.Vector3[1];
  1047. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1048. z = 1.0;
  1049. }
  1050. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1051. x = 1.0;
  1052. }
  1053. else {
  1054. t = w.z / w.x;
  1055. x = -t * Math.sqrt(1 / (1 + t * t));
  1056. z = Math.sqrt(1 / (1 + t * t));
  1057. }
  1058. u1.x = x;
  1059. u1.y = y;
  1060. u1.z = z;
  1061. u1.normalize();
  1062. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1063. cross.normalize();
  1064. if (Vector3.Dot(w, cross) < 0) {
  1065. sign = 1.0;
  1066. }
  1067. dot = Vector3.Dot(u, u1);
  1068. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1069. roll = Math.acos(dot) * sign;
  1070. if (Vector3.Dot(u1, X) < 0) {
  1071. roll = Math.PI + roll;
  1072. u1 = u1.scaleInPlace(-1);
  1073. nbRevert++;
  1074. }
  1075. // step 2 : rotate around u1
  1076. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1077. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1078. var w2 = Tmp.Vector3[2];
  1079. var v2 = Tmp.Vector3[3];
  1080. x = 0.0;
  1081. y = 0.0;
  1082. z = 0.0;
  1083. sign = -1.0;
  1084. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1085. x = 1.0;
  1086. }
  1087. else {
  1088. t = u1.z / u1.x;
  1089. x = -t * Math.sqrt(1 / (1 + t * t));
  1090. z = Math.sqrt(1 / (1 + t * t));
  1091. }
  1092. w2.x = x;
  1093. w2.y = y;
  1094. w2.z = z;
  1095. w2.normalize();
  1096. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1097. v2.normalize();
  1098. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1099. cross.normalize();
  1100. if (Vector3.Dot(u1, cross) < 0) {
  1101. sign = 1.0;
  1102. }
  1103. dot = Vector3.Dot(w, w2);
  1104. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1105. pitch = Math.acos(dot) * sign;
  1106. if (Vector3.Dot(v2, Y) < 0) {
  1107. pitch = Math.PI + pitch;
  1108. nbRevert++;
  1109. }
  1110. // step 3 : rotate around v2
  1111. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1112. sign = -1.0;
  1113. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1114. cross.normalize();
  1115. if (Vector3.Dot(cross, Y) < 0) {
  1116. sign = 1.0;
  1117. }
  1118. dot = Vector3.Dot(u1, X);
  1119. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1120. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1121. if (dot < 0 && nbRevert < 2) {
  1122. yaw = Math.PI + yaw;
  1123. }
  1124. ref.x = pitch;
  1125. ref.y = yaw;
  1126. ref.z = roll;
  1127. };
  1128. return Vector3;
  1129. }());
  1130. BABYLON.Vector3 = Vector3;
  1131. //Vector4 class created for EulerAngle class conversion to Quaternion
  1132. var Vector4 = (function () {
  1133. function Vector4(x, y, z, w) {
  1134. this.x = x;
  1135. this.y = y;
  1136. this.z = z;
  1137. this.w = w;
  1138. }
  1139. Vector4.prototype.toString = function () {
  1140. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1141. };
  1142. Vector4.prototype.getClassName = function () {
  1143. return "Vector4";
  1144. };
  1145. Vector4.prototype.getHashCode = function () {
  1146. var hash = this.x || 0;
  1147. hash = (hash * 397) ^ (this.y || 0);
  1148. hash = (hash * 397) ^ (this.z || 0);
  1149. hash = (hash * 397) ^ (this.w || 0);
  1150. return hash;
  1151. };
  1152. // Operators
  1153. Vector4.prototype.asArray = function () {
  1154. var result = [];
  1155. this.toArray(result, 0);
  1156. return result;
  1157. };
  1158. Vector4.prototype.toArray = function (array, index) {
  1159. if (index === undefined) {
  1160. index = 0;
  1161. }
  1162. array[index] = this.x;
  1163. array[index + 1] = this.y;
  1164. array[index + 2] = this.z;
  1165. array[index + 3] = this.w;
  1166. return this;
  1167. };
  1168. Vector4.prototype.addInPlace = function (otherVector) {
  1169. this.x += otherVector.x;
  1170. this.y += otherVector.y;
  1171. this.z += otherVector.z;
  1172. this.w += otherVector.w;
  1173. return this;
  1174. };
  1175. Vector4.prototype.add = function (otherVector) {
  1176. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1177. };
  1178. Vector4.prototype.addToRef = function (otherVector, result) {
  1179. result.x = this.x + otherVector.x;
  1180. result.y = this.y + otherVector.y;
  1181. result.z = this.z + otherVector.z;
  1182. result.w = this.w + otherVector.w;
  1183. return this;
  1184. };
  1185. Vector4.prototype.subtractInPlace = function (otherVector) {
  1186. this.x -= otherVector.x;
  1187. this.y -= otherVector.y;
  1188. this.z -= otherVector.z;
  1189. this.w -= otherVector.w;
  1190. return this;
  1191. };
  1192. Vector4.prototype.subtract = function (otherVector) {
  1193. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1194. };
  1195. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1196. result.x = this.x - otherVector.x;
  1197. result.y = this.y - otherVector.y;
  1198. result.z = this.z - otherVector.z;
  1199. result.w = this.w - otherVector.w;
  1200. return this;
  1201. };
  1202. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1203. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1204. };
  1205. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1206. result.x = this.x - x;
  1207. result.y = this.y - y;
  1208. result.z = this.z - z;
  1209. result.w = this.w - w;
  1210. return this;
  1211. };
  1212. Vector4.prototype.negate = function () {
  1213. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1214. };
  1215. Vector4.prototype.scaleInPlace = function (scale) {
  1216. this.x *= scale;
  1217. this.y *= scale;
  1218. this.z *= scale;
  1219. this.w *= scale;
  1220. return this;
  1221. };
  1222. Vector4.prototype.scale = function (scale) {
  1223. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1224. };
  1225. Vector4.prototype.scaleToRef = function (scale, result) {
  1226. result.x = this.x * scale;
  1227. result.y = this.y * scale;
  1228. result.z = this.z * scale;
  1229. result.w = this.w * scale;
  1230. };
  1231. Vector4.prototype.equals = function (otherVector) {
  1232. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1233. };
  1234. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1235. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1236. return otherVector
  1237. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1238. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1239. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1240. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1241. };
  1242. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1243. return this.x === x && this.y === y && this.z === z && this.w === w;
  1244. };
  1245. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1246. this.x *= otherVector.x;
  1247. this.y *= otherVector.y;
  1248. this.z *= otherVector.z;
  1249. this.w *= otherVector.w;
  1250. return this;
  1251. };
  1252. Vector4.prototype.multiply = function (otherVector) {
  1253. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1254. };
  1255. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1256. result.x = this.x * otherVector.x;
  1257. result.y = this.y * otherVector.y;
  1258. result.z = this.z * otherVector.z;
  1259. result.w = this.w * otherVector.w;
  1260. return this;
  1261. };
  1262. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1263. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1264. };
  1265. Vector4.prototype.divide = function (otherVector) {
  1266. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1267. };
  1268. Vector4.prototype.divideToRef = function (otherVector, result) {
  1269. result.x = this.x / otherVector.x;
  1270. result.y = this.y / otherVector.y;
  1271. result.z = this.z / otherVector.z;
  1272. result.w = this.w / otherVector.w;
  1273. return this;
  1274. };
  1275. Vector4.prototype.MinimizeInPlace = function (other) {
  1276. if (other.x < this.x)
  1277. this.x = other.x;
  1278. if (other.y < this.y)
  1279. this.y = other.y;
  1280. if (other.z < this.z)
  1281. this.z = other.z;
  1282. if (other.w < this.w)
  1283. this.w = other.w;
  1284. return this;
  1285. };
  1286. Vector4.prototype.MaximizeInPlace = function (other) {
  1287. if (other.x > this.x)
  1288. this.x = other.x;
  1289. if (other.y > this.y)
  1290. this.y = other.y;
  1291. if (other.z > this.z)
  1292. this.z = other.z;
  1293. if (other.w > this.w)
  1294. this.w = other.w;
  1295. return this;
  1296. };
  1297. // Properties
  1298. Vector4.prototype.length = function () {
  1299. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1300. };
  1301. Vector4.prototype.lengthSquared = function () {
  1302. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1303. };
  1304. // Methods
  1305. Vector4.prototype.normalize = function () {
  1306. var len = this.length();
  1307. if (len === 0)
  1308. return this;
  1309. var num = 1.0 / len;
  1310. this.x *= num;
  1311. this.y *= num;
  1312. this.z *= num;
  1313. this.w *= num;
  1314. return this;
  1315. };
  1316. Vector4.prototype.toVector3 = function () {
  1317. return new Vector3(this.x, this.y, this.z);
  1318. };
  1319. Vector4.prototype.clone = function () {
  1320. return new Vector4(this.x, this.y, this.z, this.w);
  1321. };
  1322. Vector4.prototype.copyFrom = function (source) {
  1323. this.x = source.x;
  1324. this.y = source.y;
  1325. this.z = source.z;
  1326. this.w = source.w;
  1327. return this;
  1328. };
  1329. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1330. this.x = x;
  1331. this.y = y;
  1332. this.z = z;
  1333. this.w = w;
  1334. return this;
  1335. };
  1336. // Statics
  1337. Vector4.FromArray = function (array, offset) {
  1338. if (!offset) {
  1339. offset = 0;
  1340. }
  1341. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1342. };
  1343. Vector4.FromArrayToRef = function (array, offset, result) {
  1344. result.x = array[offset];
  1345. result.y = array[offset + 1];
  1346. result.z = array[offset + 2];
  1347. result.w = array[offset + 3];
  1348. };
  1349. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1350. result.x = array[offset];
  1351. result.y = array[offset + 1];
  1352. result.z = array[offset + 2];
  1353. result.w = array[offset + 3];
  1354. };
  1355. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1356. result.x = x;
  1357. result.y = y;
  1358. result.z = z;
  1359. result.w = w;
  1360. };
  1361. Vector4.Zero = function () {
  1362. return new Vector4(0, 0, 0, 0);
  1363. };
  1364. Vector4.Normalize = function (vector) {
  1365. var result = Vector4.Zero();
  1366. Vector4.NormalizeToRef(vector, result);
  1367. return result;
  1368. };
  1369. Vector4.NormalizeToRef = function (vector, result) {
  1370. result.copyFrom(vector);
  1371. result.normalize();
  1372. };
  1373. Vector4.Minimize = function (left, right) {
  1374. var min = left.clone();
  1375. min.MinimizeInPlace(right);
  1376. return min;
  1377. };
  1378. Vector4.Maximize = function (left, right) {
  1379. var max = left.clone();
  1380. max.MaximizeInPlace(right);
  1381. return max;
  1382. };
  1383. Vector4.Distance = function (value1, value2) {
  1384. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1385. };
  1386. Vector4.DistanceSquared = function (value1, value2) {
  1387. var x = value1.x - value2.x;
  1388. var y = value1.y - value2.y;
  1389. var z = value1.z - value2.z;
  1390. var w = value1.w - value2.w;
  1391. return (x * x) + (y * y) + (z * z) + (w * w);
  1392. };
  1393. Vector4.Center = function (value1, value2) {
  1394. var center = value1.add(value2);
  1395. center.scaleInPlace(0.5);
  1396. return center;
  1397. };
  1398. return Vector4;
  1399. }());
  1400. BABYLON.Vector4 = Vector4;
  1401. var Size = (function () {
  1402. function Size(width, height) {
  1403. this.width = width;
  1404. this.height = height;
  1405. }
  1406. Size.prototype.toString = function () {
  1407. return "{W: " + this.width + ", H: " + this.height + "}";
  1408. };
  1409. Size.prototype.getClassName = function () {
  1410. return "Size";
  1411. };
  1412. Size.prototype.getHashCode = function () {
  1413. var hash = this.width || 0;
  1414. hash = (hash * 397) ^ (this.height || 0);
  1415. return hash;
  1416. };
  1417. Size.prototype.copyFrom = function (src) {
  1418. this.width = src.width;
  1419. this.height = src.height;
  1420. };
  1421. Size.prototype.copyFromFloats = function (width, height) {
  1422. this.width = width;
  1423. this.height = height;
  1424. };
  1425. Size.prototype.multiplyByFloats = function (w, h) {
  1426. return new Size(this.width * w, this.height * h);
  1427. };
  1428. Size.prototype.clone = function () {
  1429. return new Size(this.width, this.height);
  1430. };
  1431. Size.prototype.equals = function (other) {
  1432. if (!other) {
  1433. return false;
  1434. }
  1435. return (this.width === other.width) && (this.height === other.height);
  1436. };
  1437. Object.defineProperty(Size.prototype, "surface", {
  1438. get: function () {
  1439. return this.width * this.height;
  1440. },
  1441. enumerable: true,
  1442. configurable: true
  1443. });
  1444. Size.Zero = function () {
  1445. return new Size(0, 0);
  1446. };
  1447. Size.prototype.add = function (otherSize) {
  1448. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1449. return r;
  1450. };
  1451. Size.prototype.substract = function (otherSize) {
  1452. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1453. return r;
  1454. };
  1455. Size.Lerp = function (start, end, amount) {
  1456. var w = start.width + ((end.width - start.width) * amount);
  1457. var h = start.height + ((end.height - start.height) * amount);
  1458. return new Size(w, h);
  1459. };
  1460. return Size;
  1461. }());
  1462. BABYLON.Size = Size;
  1463. var Quaternion = (function () {
  1464. function Quaternion(x, y, z, w) {
  1465. if (x === void 0) { x = 0; }
  1466. if (y === void 0) { y = 0; }
  1467. if (z === void 0) { z = 0; }
  1468. if (w === void 0) { w = 1; }
  1469. this.x = x;
  1470. this.y = y;
  1471. this.z = z;
  1472. this.w = w;
  1473. }
  1474. Quaternion.prototype.toString = function () {
  1475. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1476. };
  1477. Quaternion.prototype.getClassName = function () {
  1478. return "Quaternion";
  1479. };
  1480. Quaternion.prototype.getHashCode = function () {
  1481. var hash = this.x || 0;
  1482. hash = (hash * 397) ^ (this.y || 0);
  1483. hash = (hash * 397) ^ (this.z || 0);
  1484. hash = (hash * 397) ^ (this.w || 0);
  1485. return hash;
  1486. };
  1487. Quaternion.prototype.asArray = function () {
  1488. return [this.x, this.y, this.z, this.w];
  1489. };
  1490. Quaternion.prototype.equals = function (otherQuaternion) {
  1491. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1492. };
  1493. Quaternion.prototype.clone = function () {
  1494. return new Quaternion(this.x, this.y, this.z, this.w);
  1495. };
  1496. Quaternion.prototype.copyFrom = function (other) {
  1497. this.x = other.x;
  1498. this.y = other.y;
  1499. this.z = other.z;
  1500. this.w = other.w;
  1501. return this;
  1502. };
  1503. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1504. this.x = x;
  1505. this.y = y;
  1506. this.z = z;
  1507. this.w = w;
  1508. return this;
  1509. };
  1510. Quaternion.prototype.add = function (other) {
  1511. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1512. };
  1513. Quaternion.prototype.subtract = function (other) {
  1514. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1515. };
  1516. Quaternion.prototype.scale = function (value) {
  1517. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1518. };
  1519. Quaternion.prototype.multiply = function (q1) {
  1520. var result = new Quaternion(0, 0, 0, 1.0);
  1521. this.multiplyToRef(q1, result);
  1522. return result;
  1523. };
  1524. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1525. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1526. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1527. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1528. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1529. result.copyFromFloats(x, y, z, w);
  1530. return this;
  1531. };
  1532. Quaternion.prototype.multiplyInPlace = function (q1) {
  1533. this.multiplyToRef(q1, this);
  1534. return this;
  1535. };
  1536. Quaternion.prototype.conjugateToRef = function (ref) {
  1537. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1538. return this;
  1539. };
  1540. Quaternion.prototype.conjugateInPlace = function () {
  1541. this.x *= -1;
  1542. this.y *= -1;
  1543. this.z *= -1;
  1544. return this;
  1545. };
  1546. Quaternion.prototype.conjugate = function () {
  1547. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1548. return result;
  1549. };
  1550. Quaternion.prototype.length = function () {
  1551. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1552. };
  1553. Quaternion.prototype.normalize = function () {
  1554. var length = 1.0 / this.length();
  1555. this.x *= length;
  1556. this.y *= length;
  1557. this.z *= length;
  1558. this.w *= length;
  1559. return this;
  1560. };
  1561. Quaternion.prototype.toEulerAngles = function (order) {
  1562. if (order === void 0) { order = "YZX"; }
  1563. var result = Vector3.Zero();
  1564. this.toEulerAnglesToRef(result, order);
  1565. return result;
  1566. };
  1567. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1568. if (order === void 0) { order = "YZX"; }
  1569. var qz = this.z;
  1570. var qx = this.x;
  1571. var qy = this.y;
  1572. var qw = this.w;
  1573. var sqw = qw * qw;
  1574. var sqz = qz * qz;
  1575. var sqx = qx * qx;
  1576. var sqy = qy * qy;
  1577. var zAxisY = qy * qz - qx * qw;
  1578. var limit = .4999999;
  1579. if (zAxisY < -limit) {
  1580. result.y = 2 * Math.atan2(qy, qw);
  1581. result.x = Math.PI / 2;
  1582. result.z = 0;
  1583. }
  1584. else if (zAxisY > limit) {
  1585. result.y = 2 * Math.atan2(qy, qw);
  1586. result.x = -Math.PI / 2;
  1587. result.z = 0;
  1588. }
  1589. else {
  1590. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  1591. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  1592. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  1593. }
  1594. return this;
  1595. };
  1596. Quaternion.prototype.toRotationMatrix = function (result) {
  1597. var xx = this.x * this.x;
  1598. var yy = this.y * this.y;
  1599. var zz = this.z * this.z;
  1600. var xy = this.x * this.y;
  1601. var zw = this.z * this.w;
  1602. var zx = this.z * this.x;
  1603. var yw = this.y * this.w;
  1604. var yz = this.y * this.z;
  1605. var xw = this.x * this.w;
  1606. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1607. result.m[1] = 2.0 * (xy + zw);
  1608. result.m[2] = 2.0 * (zx - yw);
  1609. result.m[3] = 0;
  1610. result.m[4] = 2.0 * (xy - zw);
  1611. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1612. result.m[6] = 2.0 * (yz + xw);
  1613. result.m[7] = 0;
  1614. result.m[8] = 2.0 * (zx + yw);
  1615. result.m[9] = 2.0 * (yz - xw);
  1616. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1617. result.m[11] = 0;
  1618. result.m[12] = 0;
  1619. result.m[13] = 0;
  1620. result.m[14] = 0;
  1621. result.m[15] = 1.0;
  1622. return this;
  1623. };
  1624. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1625. Quaternion.FromRotationMatrixToRef(matrix, this);
  1626. return this;
  1627. };
  1628. // Statics
  1629. Quaternion.FromRotationMatrix = function (matrix) {
  1630. var result = new Quaternion();
  1631. Quaternion.FromRotationMatrixToRef(matrix, result);
  1632. return result;
  1633. };
  1634. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1635. var data = matrix.m;
  1636. var m11 = data[0], m12 = data[4], m13 = data[8];
  1637. var m21 = data[1], m22 = data[5], m23 = data[9];
  1638. var m31 = data[2], m32 = data[6], m33 = data[10];
  1639. var trace = m11 + m22 + m33;
  1640. var s;
  1641. if (trace > 0) {
  1642. s = 0.5 / Math.sqrt(trace + 1.0);
  1643. result.w = 0.25 / s;
  1644. result.x = (m32 - m23) * s;
  1645. result.y = (m13 - m31) * s;
  1646. result.z = (m21 - m12) * s;
  1647. }
  1648. else if (m11 > m22 && m11 > m33) {
  1649. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1650. result.w = (m32 - m23) / s;
  1651. result.x = 0.25 * s;
  1652. result.y = (m12 + m21) / s;
  1653. result.z = (m13 + m31) / s;
  1654. }
  1655. else if (m22 > m33) {
  1656. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1657. result.w = (m13 - m31) / s;
  1658. result.x = (m12 + m21) / s;
  1659. result.y = 0.25 * s;
  1660. result.z = (m23 + m32) / s;
  1661. }
  1662. else {
  1663. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1664. result.w = (m21 - m12) / s;
  1665. result.x = (m13 + m31) / s;
  1666. result.y = (m23 + m32) / s;
  1667. result.z = 0.25 * s;
  1668. }
  1669. };
  1670. Quaternion.Inverse = function (q) {
  1671. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1672. };
  1673. Quaternion.Identity = function () {
  1674. return new Quaternion(0, 0, 0, 1);
  1675. };
  1676. Quaternion.RotationAxis = function (axis, angle) {
  1677. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1678. };
  1679. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1680. var sin = Math.sin(angle / 2);
  1681. axis.normalize();
  1682. result.w = Math.cos(angle / 2);
  1683. result.x = axis.x * sin;
  1684. result.y = axis.y * sin;
  1685. result.z = axis.z * sin;
  1686. return result;
  1687. };
  1688. Quaternion.FromArray = function (array, offset) {
  1689. if (!offset) {
  1690. offset = 0;
  1691. }
  1692. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1693. };
  1694. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1695. var q = new Quaternion();
  1696. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1697. return q;
  1698. };
  1699. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1700. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1701. var halfRoll = roll * 0.5;
  1702. var halfPitch = pitch * 0.5;
  1703. var halfYaw = yaw * 0.5;
  1704. var sinRoll = Math.sin(halfRoll);
  1705. var cosRoll = Math.cos(halfRoll);
  1706. var sinPitch = Math.sin(halfPitch);
  1707. var cosPitch = Math.cos(halfPitch);
  1708. var sinYaw = Math.sin(halfYaw);
  1709. var cosYaw = Math.cos(halfYaw);
  1710. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1711. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1712. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1713. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1714. };
  1715. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1716. var result = new Quaternion();
  1717. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1718. return result;
  1719. };
  1720. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1721. // Produces a quaternion from Euler angles in the z-x-z orientation
  1722. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1723. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1724. var halfBeta = beta * 0.5;
  1725. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1726. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1727. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1728. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1729. };
  1730. Quaternion.Slerp = function (left, right, amount) {
  1731. var num2;
  1732. var num3;
  1733. var num = amount;
  1734. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1735. var flag = false;
  1736. if (num4 < 0) {
  1737. flag = true;
  1738. num4 = -num4;
  1739. }
  1740. if (num4 > 0.999999) {
  1741. num3 = 1 - num;
  1742. num2 = flag ? -num : num;
  1743. }
  1744. else {
  1745. var num5 = Math.acos(num4);
  1746. var num6 = (1.0 / Math.sin(num5));
  1747. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1748. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1749. }
  1750. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1751. };
  1752. return Quaternion;
  1753. }());
  1754. BABYLON.Quaternion = Quaternion;
  1755. var Matrix = (function () {
  1756. function Matrix() {
  1757. this.m = new Float32Array(16);
  1758. }
  1759. // Properties
  1760. Matrix.prototype.isIdentity = function () {
  1761. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1762. return false;
  1763. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1764. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1765. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1766. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1767. return false;
  1768. return true;
  1769. };
  1770. Matrix.prototype.determinant = function () {
  1771. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1772. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1773. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1774. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1775. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1776. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1777. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1778. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1779. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1780. };
  1781. // Methods
  1782. Matrix.prototype.toArray = function () {
  1783. return this.m;
  1784. };
  1785. Matrix.prototype.asArray = function () {
  1786. return this.toArray();
  1787. };
  1788. Matrix.prototype.invert = function () {
  1789. this.invertToRef(this);
  1790. return this;
  1791. };
  1792. Matrix.prototype.reset = function () {
  1793. for (var index = 0; index < 16; index++) {
  1794. this.m[index] = 0;
  1795. }
  1796. return this;
  1797. };
  1798. Matrix.prototype.add = function (other) {
  1799. var result = new Matrix();
  1800. this.addToRef(other, result);
  1801. return result;
  1802. };
  1803. Matrix.prototype.addToRef = function (other, result) {
  1804. for (var index = 0; index < 16; index++) {
  1805. result.m[index] = this.m[index] + other.m[index];
  1806. }
  1807. return this;
  1808. };
  1809. Matrix.prototype.addToSelf = function (other) {
  1810. for (var index = 0; index < 16; index++) {
  1811. this.m[index] += other.m[index];
  1812. }
  1813. return this;
  1814. };
  1815. Matrix.prototype.invertToRef = function (other) {
  1816. var l1 = this.m[0];
  1817. var l2 = this.m[1];
  1818. var l3 = this.m[2];
  1819. var l4 = this.m[3];
  1820. var l5 = this.m[4];
  1821. var l6 = this.m[5];
  1822. var l7 = this.m[6];
  1823. var l8 = this.m[7];
  1824. var l9 = this.m[8];
  1825. var l10 = this.m[9];
  1826. var l11 = this.m[10];
  1827. var l12 = this.m[11];
  1828. var l13 = this.m[12];
  1829. var l14 = this.m[13];
  1830. var l15 = this.m[14];
  1831. var l16 = this.m[15];
  1832. var l17 = (l11 * l16) - (l12 * l15);
  1833. var l18 = (l10 * l16) - (l12 * l14);
  1834. var l19 = (l10 * l15) - (l11 * l14);
  1835. var l20 = (l9 * l16) - (l12 * l13);
  1836. var l21 = (l9 * l15) - (l11 * l13);
  1837. var l22 = (l9 * l14) - (l10 * l13);
  1838. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1839. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1840. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1841. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1842. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1843. var l28 = (l7 * l16) - (l8 * l15);
  1844. var l29 = (l6 * l16) - (l8 * l14);
  1845. var l30 = (l6 * l15) - (l7 * l14);
  1846. var l31 = (l5 * l16) - (l8 * l13);
  1847. var l32 = (l5 * l15) - (l7 * l13);
  1848. var l33 = (l5 * l14) - (l6 * l13);
  1849. var l34 = (l7 * l12) - (l8 * l11);
  1850. var l35 = (l6 * l12) - (l8 * l10);
  1851. var l36 = (l6 * l11) - (l7 * l10);
  1852. var l37 = (l5 * l12) - (l8 * l9);
  1853. var l38 = (l5 * l11) - (l7 * l9);
  1854. var l39 = (l5 * l10) - (l6 * l9);
  1855. other.m[0] = l23 * l27;
  1856. other.m[4] = l24 * l27;
  1857. other.m[8] = l25 * l27;
  1858. other.m[12] = l26 * l27;
  1859. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1860. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1861. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1862. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1863. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1864. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1865. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1866. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1867. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1868. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1869. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1870. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1871. return this;
  1872. };
  1873. Matrix.prototype.setTranslation = function (vector3) {
  1874. this.m[12] = vector3.x;
  1875. this.m[13] = vector3.y;
  1876. this.m[14] = vector3.z;
  1877. return this;
  1878. };
  1879. Matrix.prototype.getTranslation = function () {
  1880. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1881. };
  1882. Matrix.prototype.multiply = function (other) {
  1883. var result = new Matrix();
  1884. this.multiplyToRef(other, result);
  1885. return result;
  1886. };
  1887. Matrix.prototype.copyFrom = function (other) {
  1888. for (var index = 0; index < 16; index++) {
  1889. this.m[index] = other.m[index];
  1890. }
  1891. return this;
  1892. };
  1893. Matrix.prototype.copyToArray = function (array, offset) {
  1894. if (offset === void 0) { offset = 0; }
  1895. for (var index = 0; index < 16; index++) {
  1896. array[offset + index] = this.m[index];
  1897. }
  1898. return this;
  1899. };
  1900. Matrix.prototype.multiplyToRef = function (other, result) {
  1901. this.multiplyToArray(other, result.m, 0);
  1902. return this;
  1903. };
  1904. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1905. var tm0 = this.m[0];
  1906. var tm1 = this.m[1];
  1907. var tm2 = this.m[2];
  1908. var tm3 = this.m[3];
  1909. var tm4 = this.m[4];
  1910. var tm5 = this.m[5];
  1911. var tm6 = this.m[6];
  1912. var tm7 = this.m[7];
  1913. var tm8 = this.m[8];
  1914. var tm9 = this.m[9];
  1915. var tm10 = this.m[10];
  1916. var tm11 = this.m[11];
  1917. var tm12 = this.m[12];
  1918. var tm13 = this.m[13];
  1919. var tm14 = this.m[14];
  1920. var tm15 = this.m[15];
  1921. var om0 = other.m[0];
  1922. var om1 = other.m[1];
  1923. var om2 = other.m[2];
  1924. var om3 = other.m[3];
  1925. var om4 = other.m[4];
  1926. var om5 = other.m[5];
  1927. var om6 = other.m[6];
  1928. var om7 = other.m[7];
  1929. var om8 = other.m[8];
  1930. var om9 = other.m[9];
  1931. var om10 = other.m[10];
  1932. var om11 = other.m[11];
  1933. var om12 = other.m[12];
  1934. var om13 = other.m[13];
  1935. var om14 = other.m[14];
  1936. var om15 = other.m[15];
  1937. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1938. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1939. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1940. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1941. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1942. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1943. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1944. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1945. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1946. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1947. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1948. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1949. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1950. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1951. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1952. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1953. return this;
  1954. };
  1955. Matrix.prototype.equals = function (value) {
  1956. return value &&
  1957. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1958. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1959. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1960. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1961. };
  1962. Matrix.prototype.clone = function () {
  1963. 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]);
  1964. };
  1965. Matrix.prototype.getClassName = function () {
  1966. return "Matrix";
  1967. };
  1968. Matrix.prototype.getHashCode = function () {
  1969. var hash = this.m[0] || 0;
  1970. for (var i = 1; i < 16; i++) {
  1971. hash = (hash * 397) ^ (this.m[i] || 0);
  1972. }
  1973. return hash;
  1974. };
  1975. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1976. translation.x = this.m[12];
  1977. translation.y = this.m[13];
  1978. translation.z = this.m[14];
  1979. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1980. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1981. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1982. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1983. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1984. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1985. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1986. rotation.x = 0;
  1987. rotation.y = 0;
  1988. rotation.z = 0;
  1989. rotation.w = 1;
  1990. return false;
  1991. }
  1992. 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, Tmp.Matrix[0]);
  1993. Quaternion.FromRotationMatrixToRef(Tmp.Matrix[0], rotation);
  1994. return true;
  1995. };
  1996. // Statics
  1997. Matrix.FromArray = function (array, offset) {
  1998. var result = new Matrix();
  1999. if (!offset) {
  2000. offset = 0;
  2001. }
  2002. Matrix.FromArrayToRef(array, offset, result);
  2003. return result;
  2004. };
  2005. Matrix.FromArrayToRef = function (array, offset, result) {
  2006. for (var index = 0; index < 16; index++) {
  2007. result.m[index] = array[index + offset];
  2008. }
  2009. };
  2010. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2011. for (var index = 0; index < 16; index++) {
  2012. result.m[index] = array[index + offset] * scale;
  2013. }
  2014. };
  2015. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2016. result.m[0] = initialM11;
  2017. result.m[1] = initialM12;
  2018. result.m[2] = initialM13;
  2019. result.m[3] = initialM14;
  2020. result.m[4] = initialM21;
  2021. result.m[5] = initialM22;
  2022. result.m[6] = initialM23;
  2023. result.m[7] = initialM24;
  2024. result.m[8] = initialM31;
  2025. result.m[9] = initialM32;
  2026. result.m[10] = initialM33;
  2027. result.m[11] = initialM34;
  2028. result.m[12] = initialM41;
  2029. result.m[13] = initialM42;
  2030. result.m[14] = initialM43;
  2031. result.m[15] = initialM44;
  2032. };
  2033. Matrix.prototype.getRow = function (index) {
  2034. if (index < 0 || index > 3) {
  2035. return null;
  2036. }
  2037. var i = index * 4;
  2038. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2039. };
  2040. Matrix.prototype.setRow = function (index, row) {
  2041. if (index < 0 || index > 3) {
  2042. return this;
  2043. }
  2044. var i = index * 4;
  2045. this.m[i + 0] = row.x;
  2046. this.m[i + 1] = row.y;
  2047. this.m[i + 2] = row.z;
  2048. this.m[i + 3] = row.w;
  2049. return this;
  2050. };
  2051. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2052. var result = new Matrix();
  2053. result.m[0] = initialM11;
  2054. result.m[1] = initialM12;
  2055. result.m[2] = initialM13;
  2056. result.m[3] = initialM14;
  2057. result.m[4] = initialM21;
  2058. result.m[5] = initialM22;
  2059. result.m[6] = initialM23;
  2060. result.m[7] = initialM24;
  2061. result.m[8] = initialM31;
  2062. result.m[9] = initialM32;
  2063. result.m[10] = initialM33;
  2064. result.m[11] = initialM34;
  2065. result.m[12] = initialM41;
  2066. result.m[13] = initialM42;
  2067. result.m[14] = initialM43;
  2068. result.m[15] = initialM44;
  2069. return result;
  2070. };
  2071. Matrix.Compose = function (scale, rotation, translation) {
  2072. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2073. var rotationMatrix = Matrix.Identity();
  2074. rotation.toRotationMatrix(rotationMatrix);
  2075. result = result.multiply(rotationMatrix);
  2076. result.setTranslation(translation);
  2077. return result;
  2078. };
  2079. Matrix.Identity = function () {
  2080. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2081. };
  2082. Matrix.IdentityToRef = function (result) {
  2083. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2084. };
  2085. Matrix.Zero = function () {
  2086. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2087. };
  2088. Matrix.RotationX = function (angle) {
  2089. var result = new Matrix();
  2090. Matrix.RotationXToRef(angle, result);
  2091. return result;
  2092. };
  2093. Matrix.Invert = function (source) {
  2094. var result = new Matrix();
  2095. source.invertToRef(result);
  2096. return result;
  2097. };
  2098. Matrix.RotationXToRef = function (angle, result) {
  2099. var s = Math.sin(angle);
  2100. var c = Math.cos(angle);
  2101. result.m[0] = 1.0;
  2102. result.m[15] = 1.0;
  2103. result.m[5] = c;
  2104. result.m[10] = c;
  2105. result.m[9] = -s;
  2106. result.m[6] = s;
  2107. result.m[1] = 0;
  2108. result.m[2] = 0;
  2109. result.m[3] = 0;
  2110. result.m[4] = 0;
  2111. result.m[7] = 0;
  2112. result.m[8] = 0;
  2113. result.m[11] = 0;
  2114. result.m[12] = 0;
  2115. result.m[13] = 0;
  2116. result.m[14] = 0;
  2117. };
  2118. Matrix.RotationY = function (angle) {
  2119. var result = new Matrix();
  2120. Matrix.RotationYToRef(angle, result);
  2121. return result;
  2122. };
  2123. Matrix.RotationYToRef = function (angle, result) {
  2124. var s = Math.sin(angle);
  2125. var c = Math.cos(angle);
  2126. result.m[5] = 1.0;
  2127. result.m[15] = 1.0;
  2128. result.m[0] = c;
  2129. result.m[2] = -s;
  2130. result.m[8] = s;
  2131. result.m[10] = c;
  2132. result.m[1] = 0;
  2133. result.m[3] = 0;
  2134. result.m[4] = 0;
  2135. result.m[6] = 0;
  2136. result.m[7] = 0;
  2137. result.m[9] = 0;
  2138. result.m[11] = 0;
  2139. result.m[12] = 0;
  2140. result.m[13] = 0;
  2141. result.m[14] = 0;
  2142. };
  2143. Matrix.RotationZ = function (angle) {
  2144. var result = new Matrix();
  2145. Matrix.RotationZToRef(angle, result);
  2146. return result;
  2147. };
  2148. Matrix.RotationZToRef = function (angle, result) {
  2149. var s = Math.sin(angle);
  2150. var c = Math.cos(angle);
  2151. result.m[10] = 1.0;
  2152. result.m[15] = 1.0;
  2153. result.m[0] = c;
  2154. result.m[1] = s;
  2155. result.m[4] = -s;
  2156. result.m[5] = c;
  2157. result.m[2] = 0;
  2158. result.m[3] = 0;
  2159. result.m[6] = 0;
  2160. result.m[7] = 0;
  2161. result.m[8] = 0;
  2162. result.m[9] = 0;
  2163. result.m[11] = 0;
  2164. result.m[12] = 0;
  2165. result.m[13] = 0;
  2166. result.m[14] = 0;
  2167. };
  2168. Matrix.RotationAxis = function (axis, angle) {
  2169. var result = Matrix.Zero();
  2170. Matrix.RotationAxisToRef(axis, angle, result);
  2171. return result;
  2172. };
  2173. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2174. var s = Math.sin(-angle);
  2175. var c = Math.cos(-angle);
  2176. var c1 = 1 - c;
  2177. axis.normalize();
  2178. result.m[0] = (axis.x * axis.x) * c1 + c;
  2179. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2180. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2181. result.m[3] = 0.0;
  2182. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2183. result.m[5] = (axis.y * axis.y) * c1 + c;
  2184. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2185. result.m[7] = 0.0;
  2186. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2187. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2188. result.m[10] = (axis.z * axis.z) * c1 + c;
  2189. result.m[11] = 0.0;
  2190. result.m[15] = 1.0;
  2191. };
  2192. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2193. var result = new Matrix();
  2194. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2195. return result;
  2196. };
  2197. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2198. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2199. this._tempQuaternion.toRotationMatrix(result);
  2200. };
  2201. Matrix.Scaling = function (x, y, z) {
  2202. var result = Matrix.Zero();
  2203. Matrix.ScalingToRef(x, y, z, result);
  2204. return result;
  2205. };
  2206. Matrix.ScalingToRef = function (x, y, z, result) {
  2207. result.m[0] = x;
  2208. result.m[1] = 0;
  2209. result.m[2] = 0;
  2210. result.m[3] = 0;
  2211. result.m[4] = 0;
  2212. result.m[5] = y;
  2213. result.m[6] = 0;
  2214. result.m[7] = 0;
  2215. result.m[8] = 0;
  2216. result.m[9] = 0;
  2217. result.m[10] = z;
  2218. result.m[11] = 0;
  2219. result.m[12] = 0;
  2220. result.m[13] = 0;
  2221. result.m[14] = 0;
  2222. result.m[15] = 1.0;
  2223. };
  2224. Matrix.Translation = function (x, y, z) {
  2225. var result = Matrix.Identity();
  2226. Matrix.TranslationToRef(x, y, z, result);
  2227. return result;
  2228. };
  2229. Matrix.TranslationToRef = function (x, y, z, result) {
  2230. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2231. };
  2232. Matrix.Lerp = function (startValue, endValue, gradient) {
  2233. var result = Matrix.Zero();
  2234. for (var index = 0; index < 16; index++) {
  2235. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2236. }
  2237. return result;
  2238. };
  2239. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2240. var startScale = new Vector3(0, 0, 0);
  2241. var startRotation = new Quaternion();
  2242. var startTranslation = new Vector3(0, 0, 0);
  2243. startValue.decompose(startScale, startRotation, startTranslation);
  2244. var endScale = new Vector3(0, 0, 0);
  2245. var endRotation = new Quaternion();
  2246. var endTranslation = new Vector3(0, 0, 0);
  2247. endValue.decompose(endScale, endRotation, endTranslation);
  2248. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2249. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2250. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2251. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2252. };
  2253. Matrix.LookAtLH = function (eye, target, up) {
  2254. var result = Matrix.Zero();
  2255. Matrix.LookAtLHToRef(eye, target, up, result);
  2256. return result;
  2257. };
  2258. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2259. // Z axis
  2260. target.subtractToRef(eye, this._zAxis);
  2261. this._zAxis.normalize();
  2262. // X axis
  2263. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2264. if (this._xAxis.lengthSquared() === 0) {
  2265. this._xAxis.x = 1.0;
  2266. }
  2267. else {
  2268. this._xAxis.normalize();
  2269. }
  2270. // Y axis
  2271. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2272. this._yAxis.normalize();
  2273. // Eye angles
  2274. var ex = -Vector3.Dot(this._xAxis, eye);
  2275. var ey = -Vector3.Dot(this._yAxis, eye);
  2276. var ez = -Vector3.Dot(this._zAxis, eye);
  2277. 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);
  2278. };
  2279. Matrix.LookAtRH = function (eye, target, up) {
  2280. var result = Matrix.Zero();
  2281. Matrix.LookAtRHToRef(eye, target, up, result);
  2282. return result;
  2283. };
  2284. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2285. // Z axis
  2286. eye.subtractToRef(target, this._zAxis);
  2287. this._zAxis.normalize();
  2288. // X axis
  2289. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2290. if (this._xAxis.lengthSquared() === 0) {
  2291. this._xAxis.x = 1.0;
  2292. }
  2293. else {
  2294. this._xAxis.normalize();
  2295. }
  2296. // Y axis
  2297. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2298. this._yAxis.normalize();
  2299. // Eye angles
  2300. var ex = -Vector3.Dot(this._xAxis, eye);
  2301. var ey = -Vector3.Dot(this._yAxis, eye);
  2302. var ez = -Vector3.Dot(this._zAxis, eye);
  2303. 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);
  2304. };
  2305. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2306. var matrix = Matrix.Zero();
  2307. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2308. return matrix;
  2309. };
  2310. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2311. var hw = 2.0 / width;
  2312. var hh = 2.0 / height;
  2313. var id = 1.0 / (zfar - znear);
  2314. var nid = znear / (znear - zfar);
  2315. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2316. };
  2317. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2318. var matrix = Matrix.Zero();
  2319. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2320. return matrix;
  2321. };
  2322. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2323. result.m[0] = 2.0 / (right - left);
  2324. result.m[1] = result.m[2] = result.m[3] = 0;
  2325. result.m[5] = 2.0 / (top - bottom);
  2326. result.m[4] = result.m[6] = result.m[7] = 0;
  2327. result.m[10] = 1.0 / (zfar - znear);
  2328. result.m[8] = result.m[9] = result.m[11] = 0;
  2329. result.m[12] = (left + right) / (left - right);
  2330. result.m[13] = (top + bottom) / (bottom - top);
  2331. result.m[14] = -znear / (zfar - znear);
  2332. result.m[15] = 1.0;
  2333. };
  2334. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2335. var matrix = Matrix.Zero();
  2336. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2337. return matrix;
  2338. };
  2339. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2340. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2341. result.m[10] *= -1.0;
  2342. };
  2343. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2344. var matrix = Matrix.Zero();
  2345. matrix.m[0] = (2.0 * znear) / width;
  2346. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2347. matrix.m[5] = (2.0 * znear) / height;
  2348. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2349. matrix.m[10] = -zfar / (znear - zfar);
  2350. matrix.m[8] = matrix.m[9] = 0.0;
  2351. matrix.m[11] = 1.0;
  2352. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2353. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2354. return matrix;
  2355. };
  2356. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2357. var matrix = Matrix.Zero();
  2358. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2359. return matrix;
  2360. };
  2361. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2362. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2363. var tan = 1.0 / (Math.tan(fov * 0.5));
  2364. if (isVerticalFovFixed) {
  2365. result.m[0] = tan / aspect;
  2366. }
  2367. else {
  2368. result.m[0] = tan;
  2369. }
  2370. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2371. if (isVerticalFovFixed) {
  2372. result.m[5] = tan;
  2373. }
  2374. else {
  2375. result.m[5] = tan * aspect;
  2376. }
  2377. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2378. result.m[8] = result.m[9] = 0.0;
  2379. result.m[10] = zfar / (zfar - znear);
  2380. result.m[11] = 1.0;
  2381. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2382. result.m[14] = -(znear * zfar) / (zfar - znear);
  2383. };
  2384. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2385. var matrix = Matrix.Zero();
  2386. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2387. return matrix;
  2388. };
  2389. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2390. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2391. var tan = 1.0 / (Math.tan(fov * 0.5));
  2392. if (isVerticalFovFixed) {
  2393. result.m[0] = tan / aspect;
  2394. }
  2395. else {
  2396. result.m[0] = tan;
  2397. }
  2398. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2399. if (isVerticalFovFixed) {
  2400. result.m[5] = tan;
  2401. }
  2402. else {
  2403. result.m[5] = tan * aspect;
  2404. }
  2405. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2406. result.m[8] = result.m[9] = 0.0;
  2407. result.m[10] = zfar / (znear - zfar);
  2408. result.m[11] = -1.0;
  2409. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2410. result.m[14] = (znear * zfar) / (znear - zfar);
  2411. };
  2412. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2413. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2414. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2415. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2416. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2417. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2418. var xScale = 2.0 / (leftTan + rightTan);
  2419. var yScale = 2.0 / (upTan + downTan);
  2420. result.m[0] = xScale;
  2421. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2422. result.m[5] = yScale;
  2423. result.m[6] = result.m[7] = 0.0;
  2424. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2425. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2426. //result.m[10] = -(znear + zfar) / (zfar - znear);
  2427. result.m[10] = -zfar / (znear - zfar);
  2428. result.m[11] = 1.0;
  2429. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2430. //result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2431. result.m[14] = (znear * zfar) / (znear - zfar);
  2432. };
  2433. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2434. var cw = viewport.width;
  2435. var ch = viewport.height;
  2436. var cx = viewport.x;
  2437. var cy = viewport.y;
  2438. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2439. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2440. };
  2441. Matrix.GetAsMatrix2x2 = function (matrix) {
  2442. return new Float32Array([
  2443. matrix.m[0], matrix.m[1],
  2444. matrix.m[4], matrix.m[5]
  2445. ]);
  2446. };
  2447. Matrix.GetAsMatrix3x3 = function (matrix) {
  2448. return new Float32Array([
  2449. matrix.m[0], matrix.m[1], matrix.m[2],
  2450. matrix.m[4], matrix.m[5], matrix.m[6],
  2451. matrix.m[8], matrix.m[9], matrix.m[10]
  2452. ]);
  2453. };
  2454. Matrix.Transpose = function (matrix) {
  2455. var result = new Matrix();
  2456. result.m[0] = matrix.m[0];
  2457. result.m[1] = matrix.m[4];
  2458. result.m[2] = matrix.m[8];
  2459. result.m[3] = matrix.m[12];
  2460. result.m[4] = matrix.m[1];
  2461. result.m[5] = matrix.m[5];
  2462. result.m[6] = matrix.m[9];
  2463. result.m[7] = matrix.m[13];
  2464. result.m[8] = matrix.m[2];
  2465. result.m[9] = matrix.m[6];
  2466. result.m[10] = matrix.m[10];
  2467. result.m[11] = matrix.m[14];
  2468. result.m[12] = matrix.m[3];
  2469. result.m[13] = matrix.m[7];
  2470. result.m[14] = matrix.m[11];
  2471. result.m[15] = matrix.m[15];
  2472. return result;
  2473. };
  2474. Matrix.Reflection = function (plane) {
  2475. var matrix = new Matrix();
  2476. Matrix.ReflectionToRef(plane, matrix);
  2477. return matrix;
  2478. };
  2479. Matrix.ReflectionToRef = function (plane, result) {
  2480. plane.normalize();
  2481. var x = plane.normal.x;
  2482. var y = plane.normal.y;
  2483. var z = plane.normal.z;
  2484. var temp = -2 * x;
  2485. var temp2 = -2 * y;
  2486. var temp3 = -2 * z;
  2487. result.m[0] = (temp * x) + 1;
  2488. result.m[1] = temp2 * x;
  2489. result.m[2] = temp3 * x;
  2490. result.m[3] = 0.0;
  2491. result.m[4] = temp * y;
  2492. result.m[5] = (temp2 * y) + 1;
  2493. result.m[6] = temp3 * y;
  2494. result.m[7] = 0.0;
  2495. result.m[8] = temp * z;
  2496. result.m[9] = temp2 * z;
  2497. result.m[10] = (temp3 * z) + 1;
  2498. result.m[11] = 0.0;
  2499. result.m[12] = temp * plane.d;
  2500. result.m[13] = temp2 * plane.d;
  2501. result.m[14] = temp3 * plane.d;
  2502. result.m[15] = 1.0;
  2503. };
  2504. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  2505. mat.m[0] = xaxis.x;
  2506. mat.m[1] = xaxis.y;
  2507. mat.m[2] = xaxis.z;
  2508. mat.m[3] = 0;
  2509. mat.m[4] = yaxis.x;
  2510. mat.m[5] = yaxis.y;
  2511. mat.m[6] = yaxis.z;
  2512. mat.m[7] = 0;
  2513. mat.m[8] = zaxis.x;
  2514. mat.m[9] = zaxis.y;
  2515. mat.m[10] = zaxis.z;
  2516. mat.m[11] = 0;
  2517. mat.m[12] = 0;
  2518. mat.m[13] = 0;
  2519. mat.m[14] = 0;
  2520. mat.m[15] = 1;
  2521. };
  2522. Matrix.FromQuaternionToRef = function (quat, result) {
  2523. var xx = quat.x * quat.x;
  2524. var yy = quat.y * quat.y;
  2525. var zz = quat.z * quat.z;
  2526. var xy = quat.x * quat.y;
  2527. var zw = quat.z * quat.w;
  2528. var zx = quat.z * quat.x;
  2529. var yw = quat.y * quat.w;
  2530. var yz = quat.y * quat.z;
  2531. var xw = quat.x * quat.w;
  2532. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2533. result.m[1] = 2.0 * (xy + zw);
  2534. result.m[2] = 2.0 * (zx - yw);
  2535. result.m[3] = 0;
  2536. result.m[4] = 2.0 * (xy - zw);
  2537. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2538. result.m[6] = 2.0 * (yz + xw);
  2539. result.m[7] = 0;
  2540. result.m[8] = 2.0 * (zx + yw);
  2541. result.m[9] = 2.0 * (yz - xw);
  2542. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2543. result.m[11] = 0;
  2544. result.m[12] = 0;
  2545. result.m[13] = 0;
  2546. result.m[14] = 0;
  2547. result.m[15] = 1.0;
  2548. };
  2549. Matrix._tempQuaternion = new Quaternion();
  2550. Matrix._xAxis = Vector3.Zero();
  2551. Matrix._yAxis = Vector3.Zero();
  2552. Matrix._zAxis = Vector3.Zero();
  2553. return Matrix;
  2554. }());
  2555. BABYLON.Matrix = Matrix;
  2556. var Plane = (function () {
  2557. function Plane(a, b, c, d) {
  2558. this.normal = new Vector3(a, b, c);
  2559. this.d = d;
  2560. }
  2561. Plane.prototype.asArray = function () {
  2562. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2563. };
  2564. // Methods
  2565. Plane.prototype.clone = function () {
  2566. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2567. };
  2568. Plane.prototype.getClassName = function () {
  2569. return "Plane";
  2570. };
  2571. Plane.prototype.getHashCode = function () {
  2572. var hash = this.normal.getHashCode();
  2573. hash = (hash * 397) ^ (this.d || 0);
  2574. return hash;
  2575. };
  2576. Plane.prototype.normalize = function () {
  2577. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2578. var magnitude = 0;
  2579. if (norm !== 0) {
  2580. magnitude = 1.0 / norm;
  2581. }
  2582. this.normal.x *= magnitude;
  2583. this.normal.y *= magnitude;
  2584. this.normal.z *= magnitude;
  2585. this.d *= magnitude;
  2586. return this;
  2587. };
  2588. Plane.prototype.transform = function (transformation) {
  2589. var transposedMatrix = Matrix.Transpose(transformation);
  2590. var x = this.normal.x;
  2591. var y = this.normal.y;
  2592. var z = this.normal.z;
  2593. var d = this.d;
  2594. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2595. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2596. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2597. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2598. return new Plane(normalX, normalY, normalZ, finalD);
  2599. };
  2600. Plane.prototype.dotCoordinate = function (point) {
  2601. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2602. };
  2603. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2604. var x1 = point2.x - point1.x;
  2605. var y1 = point2.y - point1.y;
  2606. var z1 = point2.z - point1.z;
  2607. var x2 = point3.x - point1.x;
  2608. var y2 = point3.y - point1.y;
  2609. var z2 = point3.z - point1.z;
  2610. var yz = (y1 * z2) - (z1 * y2);
  2611. var xz = (z1 * x2) - (x1 * z2);
  2612. var xy = (x1 * y2) - (y1 * x2);
  2613. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2614. var invPyth;
  2615. if (pyth !== 0) {
  2616. invPyth = 1.0 / pyth;
  2617. }
  2618. else {
  2619. invPyth = 0;
  2620. }
  2621. this.normal.x = yz * invPyth;
  2622. this.normal.y = xz * invPyth;
  2623. this.normal.z = xy * invPyth;
  2624. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2625. return this;
  2626. };
  2627. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2628. var dot = Vector3.Dot(this.normal, direction);
  2629. return (dot <= epsilon);
  2630. };
  2631. Plane.prototype.signedDistanceTo = function (point) {
  2632. return Vector3.Dot(point, this.normal) + this.d;
  2633. };
  2634. // Statics
  2635. Plane.FromArray = function (array) {
  2636. return new Plane(array[0], array[1], array[2], array[3]);
  2637. };
  2638. Plane.FromPoints = function (point1, point2, point3) {
  2639. var result = new Plane(0, 0, 0, 0);
  2640. result.copyFromPoints(point1, point2, point3);
  2641. return result;
  2642. };
  2643. Plane.FromPositionAndNormal = function (origin, normal) {
  2644. var result = new Plane(0, 0, 0, 0);
  2645. normal.normalize();
  2646. result.normal = normal;
  2647. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2648. return result;
  2649. };
  2650. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2651. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2652. return Vector3.Dot(point, normal) + d;
  2653. };
  2654. return Plane;
  2655. }());
  2656. BABYLON.Plane = Plane;
  2657. var Viewport = (function () {
  2658. function Viewport(x, y, width, height) {
  2659. this.x = x;
  2660. this.y = y;
  2661. this.width = width;
  2662. this.height = height;
  2663. }
  2664. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2665. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2666. };
  2667. return Viewport;
  2668. }());
  2669. BABYLON.Viewport = Viewport;
  2670. var Frustum = (function () {
  2671. function Frustum() {
  2672. }
  2673. Frustum.GetPlanes = function (transform) {
  2674. var frustumPlanes = [];
  2675. for (var index = 0; index < 6; index++) {
  2676. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2677. }
  2678. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2679. return frustumPlanes;
  2680. };
  2681. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2682. // Near
  2683. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2684. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2685. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2686. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2687. frustumPlanes[0].normalize();
  2688. // Far
  2689. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2690. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2691. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2692. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2693. frustumPlanes[1].normalize();
  2694. // Left
  2695. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2696. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2697. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2698. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2699. frustumPlanes[2].normalize();
  2700. // Right
  2701. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2702. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2703. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2704. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2705. frustumPlanes[3].normalize();
  2706. // Top
  2707. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2708. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2709. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2710. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2711. frustumPlanes[4].normalize();
  2712. // Bottom
  2713. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2714. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2715. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2716. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2717. frustumPlanes[5].normalize();
  2718. };
  2719. return Frustum;
  2720. }());
  2721. BABYLON.Frustum = Frustum;
  2722. (function (Space) {
  2723. Space[Space["LOCAL"] = 0] = "LOCAL";
  2724. Space[Space["WORLD"] = 1] = "WORLD";
  2725. })(BABYLON.Space || (BABYLON.Space = {}));
  2726. var Space = BABYLON.Space;
  2727. var Axis = (function () {
  2728. function Axis() {
  2729. }
  2730. Axis.X = new Vector3(1, 0, 0);
  2731. Axis.Y = new Vector3(0, 1, 0);
  2732. Axis.Z = new Vector3(0, 0, 1);
  2733. return Axis;
  2734. }());
  2735. BABYLON.Axis = Axis;
  2736. ;
  2737. var BezierCurve = (function () {
  2738. function BezierCurve() {
  2739. }
  2740. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2741. // Extract X (which is equal to time here)
  2742. var f0 = 1 - 3 * x2 + 3 * x1;
  2743. var f1 = 3 * x2 - 6 * x1;
  2744. var f2 = 3 * x1;
  2745. var refinedT = t;
  2746. for (var i = 0; i < 5; i++) {
  2747. var refinedT2 = refinedT * refinedT;
  2748. var refinedT3 = refinedT2 * refinedT;
  2749. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2750. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2751. refinedT -= (x - t) * slope;
  2752. refinedT = Math.min(1, Math.max(0, refinedT));
  2753. }
  2754. // Resolve cubic bezier for the given x
  2755. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2756. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2757. Math.pow(refinedT, 3);
  2758. };
  2759. return BezierCurve;
  2760. }());
  2761. BABYLON.BezierCurve = BezierCurve;
  2762. (function (Orientation) {
  2763. Orientation[Orientation["CW"] = 0] = "CW";
  2764. Orientation[Orientation["CCW"] = 1] = "CCW";
  2765. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2766. var Orientation = BABYLON.Orientation;
  2767. var Angle = (function () {
  2768. function Angle(radians) {
  2769. var _this = this;
  2770. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2771. this.radians = function () { return _this._radians; };
  2772. this._radians = radians;
  2773. if (this._radians < 0)
  2774. this._radians += (2 * Math.PI);
  2775. }
  2776. Angle.BetweenTwoPoints = function (a, b) {
  2777. var delta = b.subtract(a);
  2778. var theta = Math.atan2(delta.y, delta.x);
  2779. return new Angle(theta);
  2780. };
  2781. Angle.FromRadians = function (radians) {
  2782. return new Angle(radians);
  2783. };
  2784. Angle.FromDegrees = function (degrees) {
  2785. return new Angle(degrees * Math.PI / 180);
  2786. };
  2787. return Angle;
  2788. }());
  2789. BABYLON.Angle = Angle;
  2790. var Arc2 = (function () {
  2791. function Arc2(startPoint, midPoint, endPoint) {
  2792. this.startPoint = startPoint;
  2793. this.midPoint = midPoint;
  2794. this.endPoint = endPoint;
  2795. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2796. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2797. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2798. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2799. 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);
  2800. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2801. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2802. var a1 = this.startAngle.degrees();
  2803. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2804. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2805. // angles correction
  2806. if (a2 - a1 > +180.0)
  2807. a2 -= 360.0;
  2808. if (a2 - a1 < -180.0)
  2809. a2 += 360.0;
  2810. if (a3 - a2 > +180.0)
  2811. a3 -= 360.0;
  2812. if (a3 - a2 < -180.0)
  2813. a3 += 360.0;
  2814. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2815. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2816. }
  2817. return Arc2;
  2818. }());
  2819. BABYLON.Arc2 = Arc2;
  2820. var Path2 = (function () {
  2821. function Path2(x, y) {
  2822. this._points = new Array();
  2823. this._length = 0;
  2824. this.closed = false;
  2825. this._points.push(new Vector2(x, y));
  2826. }
  2827. Path2.prototype.addLineTo = function (x, y) {
  2828. if (closed) {
  2829. //Tools.Error("cannot add lines to closed paths");
  2830. return this;
  2831. }
  2832. var newPoint = new Vector2(x, y);
  2833. var previousPoint = this._points[this._points.length - 1];
  2834. this._points.push(newPoint);
  2835. this._length += newPoint.subtract(previousPoint).length();
  2836. return this;
  2837. };
  2838. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2839. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2840. if (closed) {
  2841. //Tools.Error("cannot add arcs to closed paths");
  2842. return this;
  2843. }
  2844. var startPoint = this._points[this._points.length - 1];
  2845. var midPoint = new Vector2(midX, midY);
  2846. var endPoint = new Vector2(endX, endY);
  2847. var arc = new Arc2(startPoint, midPoint, endPoint);
  2848. var increment = arc.angle.radians() / numberOfSegments;
  2849. if (arc.orientation === Orientation.CW)
  2850. increment *= -1;
  2851. var currentAngle = arc.startAngle.radians() + increment;
  2852. for (var i = 0; i < numberOfSegments; i++) {
  2853. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2854. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2855. this.addLineTo(x, y);
  2856. currentAngle += increment;
  2857. }
  2858. return this;
  2859. };
  2860. Path2.prototype.close = function () {
  2861. this.closed = true;
  2862. return this;
  2863. };
  2864. Path2.prototype.length = function () {
  2865. var result = this._length;
  2866. if (!this.closed) {
  2867. var lastPoint = this._points[this._points.length - 1];
  2868. var firstPoint = this._points[0];
  2869. result += (firstPoint.subtract(lastPoint).length());
  2870. }
  2871. return result;
  2872. };
  2873. Path2.prototype.getPoints = function () {
  2874. return this._points;
  2875. };
  2876. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2877. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2878. //Tools.Error("normalized length position should be between 0 and 1.");
  2879. return Vector2.Zero();
  2880. }
  2881. var lengthPosition = normalizedLengthPosition * this.length();
  2882. var previousOffset = 0;
  2883. for (var i = 0; i < this._points.length; i++) {
  2884. var j = (i + 1) % this._points.length;
  2885. var a = this._points[i];
  2886. var b = this._points[j];
  2887. var bToA = b.subtract(a);
  2888. var nextOffset = (bToA.length() + previousOffset);
  2889. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2890. var dir = bToA.normalize();
  2891. var localOffset = lengthPosition - previousOffset;
  2892. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2893. }
  2894. previousOffset = nextOffset;
  2895. }
  2896. //Tools.Error("internal error");
  2897. return Vector2.Zero();
  2898. };
  2899. Path2.StartingAt = function (x, y) {
  2900. return new Path2(x, y);
  2901. };
  2902. return Path2;
  2903. }());
  2904. BABYLON.Path2 = Path2;
  2905. var Path3D = (function () {
  2906. /**
  2907. * new Path3D(path, normal, raw)
  2908. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2909. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2910. * path : an array of Vector3, the curve axis of the Path3D
  2911. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2912. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2913. */
  2914. function Path3D(path, firstNormal, raw) {
  2915. this.path = path;
  2916. this._curve = new Array();
  2917. this._distances = new Array();
  2918. this._tangents = new Array();
  2919. this._normals = new Array();
  2920. this._binormals = new Array();
  2921. for (var p = 0; p < path.length; p++) {
  2922. this._curve[p] = path[p].clone(); // hard copy
  2923. }
  2924. this._raw = raw || false;
  2925. this._compute(firstNormal);
  2926. }
  2927. /**
  2928. * Returns the Path3D array of successive Vector3 designing its curve.
  2929. */
  2930. Path3D.prototype.getCurve = function () {
  2931. return this._curve;
  2932. };
  2933. /**
  2934. * Returns an array populated with tangent vectors on each Path3D curve point.
  2935. */
  2936. Path3D.prototype.getTangents = function () {
  2937. return this._tangents;
  2938. };
  2939. /**
  2940. * Returns an array populated with normal vectors on each Path3D curve point.
  2941. */
  2942. Path3D.prototype.getNormals = function () {
  2943. return this._normals;
  2944. };
  2945. /**
  2946. * Returns an array populated with binormal vectors on each Path3D curve point.
  2947. */
  2948. Path3D.prototype.getBinormals = function () {
  2949. return this._binormals;
  2950. };
  2951. /**
  2952. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2953. */
  2954. Path3D.prototype.getDistances = function () {
  2955. return this._distances;
  2956. };
  2957. /**
  2958. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2959. * Returns the same object updated.
  2960. */
  2961. Path3D.prototype.update = function (path, firstNormal) {
  2962. for (var p = 0; p < path.length; p++) {
  2963. this._curve[p].x = path[p].x;
  2964. this._curve[p].y = path[p].y;
  2965. this._curve[p].z = path[p].z;
  2966. }
  2967. this._compute(firstNormal);
  2968. return this;
  2969. };
  2970. // private function compute() : computes tangents, normals and binormals
  2971. Path3D.prototype._compute = function (firstNormal) {
  2972. var l = this._curve.length;
  2973. // first and last tangents
  2974. this._tangents[0] = this._getFirstNonNullVector(0);
  2975. if (!this._raw) {
  2976. this._tangents[0].normalize();
  2977. }
  2978. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2979. if (!this._raw) {
  2980. this._tangents[l - 1].normalize();
  2981. }
  2982. // normals and binormals at first point : arbitrary vector with _normalVector()
  2983. var tg0 = this._tangents[0];
  2984. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2985. this._normals[0] = pp0;
  2986. if (!this._raw) {
  2987. this._normals[0].normalize();
  2988. }
  2989. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2990. if (!this._raw) {
  2991. this._binormals[0].normalize();
  2992. }
  2993. this._distances[0] = 0.0;
  2994. // normals and binormals : next points
  2995. var prev; // previous vector (segment)
  2996. var cur; // current vector (segment)
  2997. var curTang; // current tangent
  2998. // previous normal
  2999. var prevBinor; // previous binormal
  3000. for (var i = 1; i < l; i++) {
  3001. // tangents
  3002. prev = this._getLastNonNullVector(i);
  3003. if (i < l - 1) {
  3004. cur = this._getFirstNonNullVector(i);
  3005. this._tangents[i] = prev.add(cur);
  3006. this._tangents[i].normalize();
  3007. }
  3008. this._distances[i] = this._distances[i - 1] + prev.length();
  3009. // normals and binormals
  3010. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  3011. curTang = this._tangents[i];
  3012. prevBinor = this._binormals[i - 1];
  3013. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  3014. if (!this._raw) {
  3015. this._normals[i].normalize();
  3016. }
  3017. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  3018. if (!this._raw) {
  3019. this._binormals[i].normalize();
  3020. }
  3021. }
  3022. };
  3023. // private function getFirstNonNullVector(index)
  3024. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  3025. Path3D.prototype._getFirstNonNullVector = function (index) {
  3026. var i = 1;
  3027. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  3028. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  3029. i++;
  3030. nNVector = this._curve[index + i].subtract(this._curve[index]);
  3031. }
  3032. return nNVector;
  3033. };
  3034. // private function getLastNonNullVector(index)
  3035. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  3036. Path3D.prototype._getLastNonNullVector = function (index) {
  3037. var i = 1;
  3038. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  3039. while (nLVector.length() === 0 && index > i + 1) {
  3040. i++;
  3041. nLVector = this._curve[index].subtract(this._curve[index - i]);
  3042. }
  3043. return nLVector;
  3044. };
  3045. // private function normalVector(v0, vt, va) :
  3046. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  3047. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  3048. Path3D.prototype._normalVector = function (v0, vt, va) {
  3049. var normal0;
  3050. var tgl = vt.length();
  3051. if (tgl === 0.0) {
  3052. tgl = 1.0;
  3053. }
  3054. if (va === undefined || va === null) {
  3055. var point;
  3056. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3057. point = new Vector3(0.0, -1.0, 0.0);
  3058. }
  3059. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3060. point = new Vector3(1.0, 0.0, 0.0);
  3061. }
  3062. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3063. point = new Vector3(0.0, 0.0, 1.0);
  3064. }
  3065. normal0 = Vector3.Cross(vt, point);
  3066. }
  3067. else {
  3068. normal0 = Vector3.Cross(vt, va);
  3069. Vector3.CrossToRef(normal0, vt, normal0);
  3070. }
  3071. normal0.normalize();
  3072. return normal0;
  3073. };
  3074. return Path3D;
  3075. }());
  3076. BABYLON.Path3D = Path3D;
  3077. var Curve3 = (function () {
  3078. /**
  3079. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3080. * A Curve3 is designed from a series of successive Vector3.
  3081. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3082. */
  3083. function Curve3(points) {
  3084. this._length = 0.0;
  3085. this._points = points;
  3086. this._length = this._computeLength(points);
  3087. }
  3088. /**
  3089. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3090. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3091. * @param v1 (Vector3) the control point
  3092. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3093. * @param nbPoints (integer) the wanted number of points in the curve
  3094. */
  3095. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3096. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3097. var bez = new Array();
  3098. var equation = function (t, val0, val1, val2) {
  3099. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3100. return res;
  3101. };
  3102. for (var i = 0; i <= nbPoints; i++) {
  3103. 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)));
  3104. }
  3105. return new Curve3(bez);
  3106. };
  3107. /**
  3108. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3109. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3110. * @param v1 (Vector3) the first control point
  3111. * @param v2 (Vector3) the second control point
  3112. * @param v3 (Vector3) the end point of the Cubic Bezier
  3113. * @param nbPoints (integer) the wanted number of points in the curve
  3114. */
  3115. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3116. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3117. var bez = new Array();
  3118. var equation = function (t, val0, val1, val2, val3) {
  3119. 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;
  3120. return res;
  3121. };
  3122. for (var i = 0; i <= nbPoints; i++) {
  3123. 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)));
  3124. }
  3125. return new Curve3(bez);
  3126. };
  3127. /**
  3128. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3129. * @param p1 (Vector3) the origin point of the Hermite Spline
  3130. * @param t1 (Vector3) the tangent vector at the origin point
  3131. * @param p2 (Vector3) the end point of the Hermite Spline
  3132. * @param t2 (Vector3) the tangent vector at the end point
  3133. * @param nbPoints (integer) the wanted number of points in the curve
  3134. */
  3135. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3136. var hermite = new Array();
  3137. var step = 1.0 / nbPoints;
  3138. for (var i = 0; i <= nbPoints; i++) {
  3139. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3140. }
  3141. return new Curve3(hermite);
  3142. };
  3143. /**
  3144. * Returns the Curve3 stored array of successive Vector3
  3145. */
  3146. Curve3.prototype.getPoints = function () {
  3147. return this._points;
  3148. };
  3149. /**
  3150. * Returns the computed length (float) of the curve.
  3151. */
  3152. Curve3.prototype.length = function () {
  3153. return this._length;
  3154. };
  3155. /**
  3156. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3157. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3158. * curveA and curveB keep unchanged.
  3159. */
  3160. Curve3.prototype.continue = function (curve) {
  3161. var lastPoint = this._points[this._points.length - 1];
  3162. var continuedPoints = this._points.slice();
  3163. var curvePoints = curve.getPoints();
  3164. for (var i = 1; i < curvePoints.length; i++) {
  3165. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3166. }
  3167. var continuedCurve = new Curve3(continuedPoints);
  3168. return continuedCurve;
  3169. };
  3170. Curve3.prototype._computeLength = function (path) {
  3171. var l = 0;
  3172. for (var i = 1; i < path.length; i++) {
  3173. l += (path[i].subtract(path[i - 1])).length();
  3174. }
  3175. return l;
  3176. };
  3177. return Curve3;
  3178. }());
  3179. BABYLON.Curve3 = Curve3;
  3180. // SphericalHarmonics
  3181. var SphericalHarmonics = (function () {
  3182. function SphericalHarmonics() {
  3183. this.L00 = Vector3.Zero();
  3184. this.L1_1 = Vector3.Zero();
  3185. this.L10 = Vector3.Zero();
  3186. this.L11 = Vector3.Zero();
  3187. this.L2_2 = Vector3.Zero();
  3188. this.L2_1 = Vector3.Zero();
  3189. this.L20 = Vector3.Zero();
  3190. this.L21 = Vector3.Zero();
  3191. this.L22 = Vector3.Zero();
  3192. }
  3193. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3194. var colorVector = new Vector3(color.r, color.g, color.b);
  3195. var c = colorVector.scale(deltaSolidAngle);
  3196. this.L00 = this.L00.add(c.scale(0.282095));
  3197. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3198. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3199. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3200. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3201. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3202. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3203. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3204. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3205. };
  3206. SphericalHarmonics.prototype.scale = function (scale) {
  3207. this.L00 = this.L00.scale(scale);
  3208. this.L1_1 = this.L1_1.scale(scale);
  3209. this.L10 = this.L10.scale(scale);
  3210. this.L11 = this.L11.scale(scale);
  3211. this.L2_2 = this.L2_2.scale(scale);
  3212. this.L2_1 = this.L2_1.scale(scale);
  3213. this.L20 = this.L20.scale(scale);
  3214. this.L21 = this.L21.scale(scale);
  3215. this.L22 = this.L22.scale(scale);
  3216. };
  3217. return SphericalHarmonics;
  3218. }());
  3219. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3220. // SphericalPolynomial
  3221. var SphericalPolynomial = (function () {
  3222. function SphericalPolynomial() {
  3223. this.x = Vector3.Zero();
  3224. this.y = Vector3.Zero();
  3225. this.z = Vector3.Zero();
  3226. this.xx = Vector3.Zero();
  3227. this.yy = Vector3.Zero();
  3228. this.zz = Vector3.Zero();
  3229. this.xy = Vector3.Zero();
  3230. this.yz = Vector3.Zero();
  3231. this.zx = Vector3.Zero();
  3232. }
  3233. SphericalPolynomial.prototype.addAmbient = function (color) {
  3234. var colorVector = new Vector3(color.r, color.g, color.b);
  3235. this.xx = this.xx.add(colorVector);
  3236. this.yy = this.yy.add(colorVector);
  3237. this.zz = this.zz.add(colorVector);
  3238. };
  3239. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3240. var result = new SphericalPolynomial();
  3241. result.x = harmonics.L11.scale(1.02333);
  3242. result.y = harmonics.L1_1.scale(1.02333);
  3243. result.z = harmonics.L10.scale(1.02333);
  3244. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3245. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3246. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3247. result.yz = harmonics.L2_1.scale(0.858086);
  3248. result.zx = harmonics.L21.scale(0.858086);
  3249. result.xy = harmonics.L2_2.scale(0.858086);
  3250. return result;
  3251. };
  3252. return SphericalPolynomial;
  3253. }());
  3254. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3255. // Vertex formats
  3256. var PositionNormalVertex = (function () {
  3257. function PositionNormalVertex(position, normal) {
  3258. if (position === void 0) { position = Vector3.Zero(); }
  3259. if (normal === void 0) { normal = Vector3.Up(); }
  3260. this.position = position;
  3261. this.normal = normal;
  3262. }
  3263. PositionNormalVertex.prototype.clone = function () {
  3264. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3265. };
  3266. return PositionNormalVertex;
  3267. }());
  3268. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3269. var PositionNormalTextureVertex = (function () {
  3270. function PositionNormalTextureVertex(position, normal, uv) {
  3271. if (position === void 0) { position = Vector3.Zero(); }
  3272. if (normal === void 0) { normal = Vector3.Up(); }
  3273. if (uv === void 0) { uv = Vector2.Zero(); }
  3274. this.position = position;
  3275. this.normal = normal;
  3276. this.uv = uv;
  3277. }
  3278. PositionNormalTextureVertex.prototype.clone = function () {
  3279. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3280. };
  3281. return PositionNormalTextureVertex;
  3282. }());
  3283. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3284. // Temporary pre-allocated objects for engine internal use
  3285. // usage in any internal function :
  3286. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3287. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3288. var Tmp = (function () {
  3289. function Tmp() {
  3290. }
  3291. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3292. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3293. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3294. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3295. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3296. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3297. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3298. Matrix.Zero(), Matrix.Zero(),
  3299. Matrix.Zero(), Matrix.Zero(),
  3300. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3301. return Tmp;
  3302. }());
  3303. BABYLON.Tmp = Tmp;
  3304. })(BABYLON || (BABYLON = {}));
  3305. //# sourceMappingURL=../Math/babylon.math.js.map
  3306. //# sourceMappingURL=babylon.mixins.js.map
  3307. var BABYLON;
  3308. (function (BABYLON) {
  3309. function generateSerializableMember(type, sourceName) {
  3310. return function (target, propertyKey) {
  3311. if (!target.__serializableMembers) {
  3312. target.__serializableMembers = {};
  3313. }
  3314. if (!target.__serializableMembers[propertyKey]) {
  3315. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3316. }
  3317. };
  3318. }
  3319. function serialize(sourceName) {
  3320. return generateSerializableMember(0, sourceName); // value member
  3321. }
  3322. BABYLON.serialize = serialize;
  3323. function serializeAsTexture(sourceName) {
  3324. return generateSerializableMember(1, sourceName); // texture member
  3325. }
  3326. BABYLON.serializeAsTexture = serializeAsTexture;
  3327. function serializeAsColor3(sourceName) {
  3328. return generateSerializableMember(2, sourceName); // color3 member
  3329. }
  3330. BABYLON.serializeAsColor3 = serializeAsColor3;
  3331. function serializeAsFresnelParameters(sourceName) {
  3332. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3333. }
  3334. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3335. function serializeAsVector2(sourceName) {
  3336. return generateSerializableMember(4, sourceName); // vector2 member
  3337. }
  3338. BABYLON.serializeAsVector2 = serializeAsVector2;
  3339. function serializeAsVector3(sourceName) {
  3340. return generateSerializableMember(5, sourceName); // vector3 member
  3341. }
  3342. BABYLON.serializeAsVector3 = serializeAsVector3;
  3343. function serializeAsMeshReference(sourceName) {
  3344. return generateSerializableMember(6, sourceName); // mesh reference member
  3345. }
  3346. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3347. function serializeAsColorCurves(sourceName) {
  3348. return generateSerializableMember(7, sourceName); // color curves
  3349. }
  3350. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3351. var SerializationHelper = (function () {
  3352. function SerializationHelper() {
  3353. }
  3354. SerializationHelper.Serialize = function (entity, serializationObject) {
  3355. if (!serializationObject) {
  3356. serializationObject = {};
  3357. }
  3358. // Tags
  3359. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3360. // Properties
  3361. for (var property in entity.__serializableMembers) {
  3362. var propertyDescriptor = entity.__serializableMembers[property];
  3363. var targetPropertyName = propertyDescriptor.sourceName || property;
  3364. var propertyType = propertyDescriptor.type;
  3365. var sourceProperty = entity[property];
  3366. if (sourceProperty !== undefined && sourceProperty !== null) {
  3367. switch (propertyType) {
  3368. case 0:
  3369. serializationObject[targetPropertyName] = sourceProperty;
  3370. break;
  3371. case 1:
  3372. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3373. break;
  3374. case 2:
  3375. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3376. break;
  3377. case 3:
  3378. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3379. break;
  3380. case 4:
  3381. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3382. break;
  3383. case 5:
  3384. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3385. break;
  3386. case 6:
  3387. serializationObject[targetPropertyName] = sourceProperty.id;
  3388. break;
  3389. case 7:
  3390. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3391. break;
  3392. }
  3393. }
  3394. }
  3395. return serializationObject;
  3396. };
  3397. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3398. var destination = creationFunction();
  3399. // Tags
  3400. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3401. // Properties
  3402. for (var property in destination.__serializableMembers) {
  3403. var propertyDescriptor = destination.__serializableMembers[property];
  3404. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3405. var propertyType = propertyDescriptor.type;
  3406. if (sourceProperty !== undefined && sourceProperty !== null) {
  3407. switch (propertyType) {
  3408. case 0:
  3409. destination[property] = sourceProperty;
  3410. break;
  3411. case 1:
  3412. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3413. break;
  3414. case 2:
  3415. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3416. break;
  3417. case 3:
  3418. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3419. break;
  3420. case 4:
  3421. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3422. break;
  3423. case 5:
  3424. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3425. break;
  3426. case 6:
  3427. destination[property] = scene.getLastMeshByID(sourceProperty);
  3428. break;
  3429. case 7:
  3430. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3431. break;
  3432. }
  3433. }
  3434. }
  3435. return destination;
  3436. };
  3437. SerializationHelper.Clone = function (creationFunction, source) {
  3438. var destination = creationFunction();
  3439. // Tags
  3440. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3441. // Properties
  3442. for (var property in destination.__serializableMembers) {
  3443. var propertyDescriptor = destination.__serializableMembers[property];
  3444. var sourceProperty = source[property];
  3445. var propertyType = propertyDescriptor.type;
  3446. if (sourceProperty !== undefined && sourceProperty !== null) {
  3447. switch (propertyType) {
  3448. case 0: // Value
  3449. case 6:
  3450. destination[property] = sourceProperty;
  3451. break;
  3452. case 1: // Texture
  3453. case 2: // Color3
  3454. case 3: // FresnelParameters
  3455. case 4: // Vector2
  3456. case 5: // Vector3
  3457. case 7:
  3458. destination[property] = sourceProperty.clone();
  3459. break;
  3460. }
  3461. }
  3462. }
  3463. return destination;
  3464. };
  3465. return SerializationHelper;
  3466. }());
  3467. BABYLON.SerializationHelper = SerializationHelper;
  3468. })(BABYLON || (BABYLON = {}));
  3469. //# sourceMappingURL=../Tools/babylon.decorators.js.map
  3470. var BABYLON;
  3471. (function (BABYLON) {
  3472. /**
  3473. * A class serves as a medium between the observable and its observers
  3474. */
  3475. var EventState = (function () {
  3476. /**
  3477. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3478. */
  3479. function EventState(mask, skipNextObservers) {
  3480. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3481. this.initalize(mask, skipNextObservers);
  3482. }
  3483. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3484. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3485. this.mask = mask;
  3486. this.skipNextObservers = skipNextObservers;
  3487. return this;
  3488. };
  3489. return EventState;
  3490. }());
  3491. BABYLON.EventState = EventState;
  3492. /**
  3493. * Represent an Observer registered to a given Observable object.
  3494. */
  3495. var Observer = (function () {
  3496. function Observer(callback, mask) {
  3497. this.callback = callback;
  3498. this.mask = mask;
  3499. }
  3500. return Observer;
  3501. }());
  3502. BABYLON.Observer = Observer;
  3503. /**
  3504. * The Observable class is a simple implementation of the Observable pattern.
  3505. * 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.
  3506. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3507. * 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).
  3508. * 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.
  3509. */
  3510. var Observable = (function () {
  3511. function Observable() {
  3512. this._observers = new Array();
  3513. this._eventState = new EventState(0);
  3514. }
  3515. /**
  3516. * Create a new Observer with the specified callback
  3517. * @param callback the callback that will be executed for that Observer
  3518. * @param mask the mask used to filter observers
  3519. * @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.
  3520. */
  3521. Observable.prototype.add = function (callback, mask, insertFirst) {
  3522. if (mask === void 0) { mask = -1; }
  3523. if (insertFirst === void 0) { insertFirst = false; }
  3524. if (!callback) {
  3525. return null;
  3526. }
  3527. var observer = new Observer(callback, mask);
  3528. if (insertFirst) {
  3529. this._observers.unshift(observer);
  3530. }
  3531. else {
  3532. this._observers.push(observer);
  3533. }
  3534. return observer;
  3535. };
  3536. /**
  3537. * Remove an Observer from the Observable object
  3538. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3539. */
  3540. Observable.prototype.remove = function (observer) {
  3541. var index = this._observers.indexOf(observer);
  3542. if (index !== -1) {
  3543. this._observers.splice(index, 1);
  3544. return true;
  3545. }
  3546. return false;
  3547. };
  3548. /**
  3549. * Remove a callback from the Observable object
  3550. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3551. */
  3552. Observable.prototype.removeCallback = function (callback) {
  3553. for (var index = 0; index < this._observers.length; index++) {
  3554. if (this._observers[index].callback === callback) {
  3555. this._observers.splice(index, 1);
  3556. return true;
  3557. }
  3558. }
  3559. return false;
  3560. };
  3561. /**
  3562. * Notify all Observers by calling their respective callback with the given data
  3563. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3564. * @param eventData
  3565. * @param mask
  3566. */
  3567. Observable.prototype.notifyObservers = function (eventData, mask) {
  3568. if (mask === void 0) { mask = -1; }
  3569. var state = this._eventState;
  3570. state.mask = mask;
  3571. state.skipNextObservers = false;
  3572. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3573. var obs = _a[_i];
  3574. if (obs.mask & mask) {
  3575. obs.callback(eventData, state);
  3576. }
  3577. if (state.skipNextObservers) {
  3578. return false;
  3579. }
  3580. }
  3581. return true;
  3582. };
  3583. /**
  3584. * return true is the Observable has at least one Observer registered
  3585. */
  3586. Observable.prototype.hasObservers = function () {
  3587. return this._observers.length > 0;
  3588. };
  3589. /**
  3590. * Clear the list of observers
  3591. */
  3592. Observable.prototype.clear = function () {
  3593. this._observers = new Array();
  3594. };
  3595. /**
  3596. * Clone the current observable
  3597. */
  3598. Observable.prototype.clone = function () {
  3599. var result = new Observable();
  3600. result._observers = this._observers.slice(0);
  3601. return result;
  3602. };
  3603. return Observable;
  3604. }());
  3605. BABYLON.Observable = Observable;
  3606. })(BABYLON || (BABYLON = {}));
  3607. //# sourceMappingURL=../Tools/babylon.observable.js.map
  3608. var BABYLON;
  3609. (function (BABYLON) {
  3610. var Database = (function () {
  3611. function Database(urlToScene, callbackManifestChecked) {
  3612. // Handling various flavors of prefixed version of IndexedDB
  3613. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3614. this.callbackManifestChecked = callbackManifestChecked;
  3615. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3616. this.db = null;
  3617. this.enableSceneOffline = false;
  3618. this.enableTexturesOffline = false;
  3619. this.manifestVersionFound = 0;
  3620. this.mustUpdateRessources = false;
  3621. this.hasReachedQuota = false;
  3622. if (!Database.IDBStorageEnabled) {
  3623. this.callbackManifestChecked(true);
  3624. }
  3625. else {
  3626. this.checkManifestFile();
  3627. }
  3628. }
  3629. Database.prototype.checkManifestFile = function () {
  3630. var _this = this;
  3631. function noManifestFile() {
  3632. that.enableSceneOffline = false;
  3633. that.enableTexturesOffline = false;
  3634. that.callbackManifestChecked(false);
  3635. }
  3636. var that = this;
  3637. var timeStampUsed = false;
  3638. var manifestURL = this.currentSceneUrl + ".manifest";
  3639. var xhr = new XMLHttpRequest();
  3640. if (navigator.onLine) {
  3641. // Adding a timestamp to by-pass browsers' cache
  3642. timeStampUsed = true;
  3643. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3644. }
  3645. xhr.open("GET", manifestURL, true);
  3646. xhr.addEventListener("load", function () {
  3647. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3648. try {
  3649. var manifestFile = JSON.parse(xhr.response);
  3650. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3651. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3652. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3653. _this.manifestVersionFound = manifestFile.version;
  3654. }
  3655. if (_this.callbackManifestChecked) {
  3656. _this.callbackManifestChecked(true);
  3657. }
  3658. }
  3659. catch (ex) {
  3660. noManifestFile();
  3661. }
  3662. }
  3663. else {
  3664. noManifestFile();
  3665. }
  3666. }, false);
  3667. xhr.addEventListener("error", function (event) {
  3668. if (timeStampUsed) {
  3669. timeStampUsed = false;
  3670. // Let's retry without the timeStamp
  3671. // It could fail when coupled with HTML5 Offline API
  3672. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3673. xhr.open("GET", retryManifestURL, true);
  3674. xhr.send();
  3675. }
  3676. else {
  3677. noManifestFile();
  3678. }
  3679. }, false);
  3680. try {
  3681. xhr.send();
  3682. }
  3683. catch (ex) {
  3684. BABYLON.Tools.Error("Error on XHR send request.");
  3685. that.callbackManifestChecked(false);
  3686. }
  3687. };
  3688. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3689. var _this = this;
  3690. function handleError() {
  3691. that.isSupported = false;
  3692. if (errorCallback)
  3693. errorCallback();
  3694. }
  3695. var that = this;
  3696. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3697. // Your browser doesn't support IndexedDB
  3698. this.isSupported = false;
  3699. if (errorCallback)
  3700. errorCallback();
  3701. }
  3702. else {
  3703. // If the DB hasn't been opened or created yet
  3704. if (!this.db) {
  3705. this.hasReachedQuota = false;
  3706. this.isSupported = true;
  3707. var request = this.idbFactory.open("babylonjs", 1);
  3708. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3709. request.onerror = function (event) {
  3710. handleError();
  3711. };
  3712. // executes when a version change transaction cannot complete due to other active transactions
  3713. request.onblocked = function (event) {
  3714. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3715. handleError();
  3716. };
  3717. // DB has been opened successfully
  3718. request.onsuccess = function (event) {
  3719. _this.db = request.result;
  3720. successCallback();
  3721. };
  3722. // Initialization of the DB. Creating Scenes & Textures stores
  3723. request.onupgradeneeded = function (event) {
  3724. _this.db = (event.target).result;
  3725. try {
  3726. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3727. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3728. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3729. }
  3730. catch (ex) {
  3731. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3732. handleError();
  3733. }
  3734. };
  3735. }
  3736. else {
  3737. if (successCallback)
  3738. successCallback();
  3739. }
  3740. }
  3741. };
  3742. Database.prototype.loadImageFromDB = function (url, image) {
  3743. var _this = this;
  3744. var completeURL = Database.ReturnFullUrlLocation(url);
  3745. var saveAndLoadImage = function () {
  3746. if (!_this.hasReachedQuota && _this.db !== null) {
  3747. // the texture is not yet in the DB, let's try to save it
  3748. _this._saveImageIntoDBAsync(completeURL, image);
  3749. }
  3750. else {
  3751. image.src = url;
  3752. }
  3753. };
  3754. if (!this.mustUpdateRessources) {
  3755. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3756. }
  3757. else {
  3758. saveAndLoadImage();
  3759. }
  3760. };
  3761. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3762. if (this.isSupported && this.db !== null) {
  3763. var texture;
  3764. var transaction = this.db.transaction(["textures"]);
  3765. transaction.onabort = function (event) {
  3766. image.src = url;
  3767. };
  3768. transaction.oncomplete = function (event) {
  3769. var blobTextureURL;
  3770. if (texture) {
  3771. var URL = window.URL || window.webkitURL;
  3772. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3773. image.onerror = function () {
  3774. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3775. image.src = url;
  3776. };
  3777. image.src = blobTextureURL;
  3778. }
  3779. else {
  3780. notInDBCallback();
  3781. }
  3782. };
  3783. var getRequest = transaction.objectStore("textures").get(url);
  3784. getRequest.onsuccess = function (event) {
  3785. texture = (event.target).result;
  3786. };
  3787. getRequest.onerror = function (event) {
  3788. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3789. image.src = url;
  3790. };
  3791. }
  3792. else {
  3793. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3794. image.src = url;
  3795. }
  3796. };
  3797. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3798. var _this = this;
  3799. if (this.isSupported) {
  3800. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3801. var generateBlobUrl = function () {
  3802. var blobTextureURL;
  3803. if (blob) {
  3804. var URL = window.URL || window.webkitURL;
  3805. try {
  3806. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3807. }
  3808. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3809. catch (ex) {
  3810. blobTextureURL = URL.createObjectURL(blob);
  3811. }
  3812. }
  3813. image.src = blobTextureURL;
  3814. };
  3815. if (Database.IsUASupportingBlobStorage) {
  3816. var xhr = new XMLHttpRequest(), blob;
  3817. xhr.open("GET", url, true);
  3818. xhr.responseType = "blob";
  3819. xhr.addEventListener("load", function () {
  3820. if (xhr.status === 200) {
  3821. // Blob as response (XHR2)
  3822. blob = xhr.response;
  3823. var transaction = _this.db.transaction(["textures"], "readwrite");
  3824. // the transaction could abort because of a QuotaExceededError error
  3825. transaction.onabort = function (event) {
  3826. try {
  3827. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3828. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3829. _this.hasReachedQuota = true;
  3830. }
  3831. }
  3832. catch (ex) { }
  3833. generateBlobUrl();
  3834. };
  3835. transaction.oncomplete = function (event) {
  3836. generateBlobUrl();
  3837. };
  3838. var newTexture = { textureUrl: url, data: blob };
  3839. try {
  3840. // Put the blob into the dabase
  3841. var addRequest = transaction.objectStore("textures").put(newTexture);
  3842. addRequest.onsuccess = function (event) {
  3843. };
  3844. addRequest.onerror = function (event) {
  3845. generateBlobUrl();
  3846. };
  3847. }
  3848. catch (ex) {
  3849. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3850. if (ex.code === 25) {
  3851. Database.IsUASupportingBlobStorage = false;
  3852. }
  3853. image.src = url;
  3854. }
  3855. }
  3856. else {
  3857. image.src = url;
  3858. }
  3859. }, false);
  3860. xhr.addEventListener("error", function (event) {
  3861. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3862. image.src = url;
  3863. }, false);
  3864. xhr.send();
  3865. }
  3866. else {
  3867. image.src = url;
  3868. }
  3869. }
  3870. else {
  3871. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3872. image.src = url;
  3873. }
  3874. };
  3875. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3876. var _this = this;
  3877. var updateVersion = function (event) {
  3878. // the version is not yet in the DB or we need to update it
  3879. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3880. };
  3881. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3882. };
  3883. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3884. var _this = this;
  3885. if (this.isSupported) {
  3886. var version;
  3887. try {
  3888. var transaction = this.db.transaction(["versions"]);
  3889. transaction.oncomplete = function (event) {
  3890. if (version) {
  3891. // If the version in the JSON file is > than the version in DB
  3892. if (_this.manifestVersionFound > version.data) {
  3893. _this.mustUpdateRessources = true;
  3894. updateInDBCallback();
  3895. }
  3896. else {
  3897. callback(version.data);
  3898. }
  3899. }
  3900. else {
  3901. _this.mustUpdateRessources = true;
  3902. updateInDBCallback();
  3903. }
  3904. };
  3905. transaction.onabort = function (event) {
  3906. callback(-1);
  3907. };
  3908. var getRequest = transaction.objectStore("versions").get(url);
  3909. getRequest.onsuccess = function (event) {
  3910. version = (event.target).result;
  3911. };
  3912. getRequest.onerror = function (event) {
  3913. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3914. callback(-1);
  3915. };
  3916. }
  3917. catch (ex) {
  3918. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3919. callback(-1);
  3920. }
  3921. }
  3922. else {
  3923. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3924. callback(-1);
  3925. }
  3926. };
  3927. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3928. var _this = this;
  3929. if (this.isSupported && !this.hasReachedQuota) {
  3930. try {
  3931. // Open a transaction to the database
  3932. var transaction = this.db.transaction(["versions"], "readwrite");
  3933. // the transaction could abort because of a QuotaExceededError error
  3934. transaction.onabort = function (event) {
  3935. try {
  3936. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3937. _this.hasReachedQuota = true;
  3938. }
  3939. }
  3940. catch (ex) { }
  3941. callback(-1);
  3942. };
  3943. transaction.oncomplete = function (event) {
  3944. callback(_this.manifestVersionFound);
  3945. };
  3946. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3947. // Put the scene into the database
  3948. var addRequest = transaction.objectStore("versions").put(newVersion);
  3949. addRequest.onsuccess = function (event) {
  3950. };
  3951. addRequest.onerror = function (event) {
  3952. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3953. };
  3954. }
  3955. catch (ex) {
  3956. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3957. callback(-1);
  3958. }
  3959. }
  3960. else {
  3961. callback(-1);
  3962. }
  3963. };
  3964. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3965. var _this = this;
  3966. var completeUrl = Database.ReturnFullUrlLocation(url);
  3967. var saveAndLoadFile = function (event) {
  3968. // the scene is not yet in the DB, let's try to save it
  3969. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3970. };
  3971. this._checkVersionFromDB(completeUrl, function (version) {
  3972. if (version !== -1) {
  3973. if (!_this.mustUpdateRessources) {
  3974. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3975. }
  3976. else {
  3977. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3978. }
  3979. }
  3980. else {
  3981. errorCallback();
  3982. }
  3983. });
  3984. };
  3985. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3986. if (this.isSupported) {
  3987. var targetStore;
  3988. if (url.indexOf(".babylon") !== -1) {
  3989. targetStore = "scenes";
  3990. }
  3991. else {
  3992. targetStore = "textures";
  3993. }
  3994. var file;
  3995. var transaction = this.db.transaction([targetStore]);
  3996. transaction.oncomplete = function (event) {
  3997. if (file) {
  3998. callback(file.data);
  3999. }
  4000. else {
  4001. notInDBCallback();
  4002. }
  4003. };
  4004. transaction.onabort = function (event) {
  4005. notInDBCallback();
  4006. };
  4007. var getRequest = transaction.objectStore(targetStore).get(url);
  4008. getRequest.onsuccess = function (event) {
  4009. file = (event.target).result;
  4010. };
  4011. getRequest.onerror = function (event) {
  4012. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  4013. notInDBCallback();
  4014. };
  4015. }
  4016. else {
  4017. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4018. callback();
  4019. }
  4020. };
  4021. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  4022. var _this = this;
  4023. if (this.isSupported) {
  4024. var targetStore;
  4025. if (url.indexOf(".babylon") !== -1) {
  4026. targetStore = "scenes";
  4027. }
  4028. else {
  4029. targetStore = "textures";
  4030. }
  4031. // Create XHR
  4032. var xhr = new XMLHttpRequest(), fileData;
  4033. xhr.open("GET", url, true);
  4034. if (useArrayBuffer) {
  4035. xhr.responseType = "arraybuffer";
  4036. }
  4037. xhr.onprogress = progressCallback;
  4038. xhr.addEventListener("load", function () {
  4039. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  4040. // Blob as response (XHR2)
  4041. //fileData = xhr.responseText;
  4042. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  4043. if (!_this.hasReachedQuota) {
  4044. // Open a transaction to the database
  4045. var transaction = _this.db.transaction([targetStore], "readwrite");
  4046. // the transaction could abort because of a QuotaExceededError error
  4047. transaction.onabort = function (event) {
  4048. try {
  4049. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  4050. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  4051. _this.hasReachedQuota = true;
  4052. }
  4053. }
  4054. catch (ex) { }
  4055. callback(fileData);
  4056. };
  4057. transaction.oncomplete = function (event) {
  4058. callback(fileData);
  4059. };
  4060. var newFile;
  4061. if (targetStore === "scenes") {
  4062. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4063. }
  4064. else {
  4065. newFile = { textureUrl: url, data: fileData };
  4066. }
  4067. try {
  4068. // Put the scene into the database
  4069. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4070. addRequest.onsuccess = function (event) {
  4071. };
  4072. addRequest.onerror = function (event) {
  4073. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4074. };
  4075. }
  4076. catch (ex) {
  4077. callback(fileData);
  4078. }
  4079. }
  4080. else {
  4081. callback(fileData);
  4082. }
  4083. }
  4084. else {
  4085. callback();
  4086. }
  4087. }, false);
  4088. xhr.addEventListener("error", function (event) {
  4089. BABYLON.Tools.Error("error on XHR request.");
  4090. callback();
  4091. }, false);
  4092. xhr.send();
  4093. }
  4094. else {
  4095. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4096. callback();
  4097. }
  4098. };
  4099. Database.IsUASupportingBlobStorage = true;
  4100. Database.IDBStorageEnabled = true;
  4101. Database.parseURL = function (url) {
  4102. var a = document.createElement('a');
  4103. a.href = url;
  4104. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4105. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4106. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4107. return absLocation;
  4108. };
  4109. Database.ReturnFullUrlLocation = function (url) {
  4110. if (url.indexOf("http:/") === -1) {
  4111. return (Database.parseURL(window.location.href) + url);
  4112. }
  4113. else {
  4114. return url;
  4115. }
  4116. };
  4117. return Database;
  4118. }());
  4119. BABYLON.Database = Database;
  4120. })(BABYLON || (BABYLON = {}));
  4121. //# sourceMappingURL=../Tools/babylon.database.js.map
  4122. var BABYLON;
  4123. (function (BABYLON) {
  4124. var Internals;
  4125. (function (Internals) {
  4126. /*
  4127. * Based on jsTGALoader - Javascript loader for TGA file
  4128. * By Vincent Thibault
  4129. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4130. */
  4131. var TGATools = (function () {
  4132. function TGATools() {
  4133. }
  4134. TGATools.GetTGAHeader = function (data) {
  4135. var offset = 0;
  4136. var header = {
  4137. id_length: data[offset++],
  4138. colormap_type: data[offset++],
  4139. image_type: data[offset++],
  4140. colormap_index: data[offset++] | data[offset++] << 8,
  4141. colormap_length: data[offset++] | data[offset++] << 8,
  4142. colormap_size: data[offset++],
  4143. origin: [
  4144. data[offset++] | data[offset++] << 8,
  4145. data[offset++] | data[offset++] << 8
  4146. ],
  4147. width: data[offset++] | data[offset++] << 8,
  4148. height: data[offset++] | data[offset++] << 8,
  4149. pixel_size: data[offset++],
  4150. flags: data[offset++]
  4151. };
  4152. return header;
  4153. };
  4154. TGATools.UploadContent = function (gl, data) {
  4155. // Not enough data to contain header ?
  4156. if (data.length < 19) {
  4157. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4158. return;
  4159. }
  4160. // Read Header
  4161. var offset = 18;
  4162. var header = TGATools.GetTGAHeader(data);
  4163. // Assume it's a valid Targa file.
  4164. if (header.id_length + offset > data.length) {
  4165. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4166. return;
  4167. }
  4168. // Skip not needed data
  4169. offset += header.id_length;
  4170. var use_rle = false;
  4171. var use_pal = false;
  4172. var use_rgb = false;
  4173. var use_grey = false;
  4174. // Get some informations.
  4175. switch (header.image_type) {
  4176. case TGATools._TYPE_RLE_INDEXED:
  4177. use_rle = true;
  4178. case TGATools._TYPE_INDEXED:
  4179. use_pal = true;
  4180. break;
  4181. case TGATools._TYPE_RLE_RGB:
  4182. use_rle = true;
  4183. case TGATools._TYPE_RGB:
  4184. use_rgb = true;
  4185. break;
  4186. case TGATools._TYPE_RLE_GREY:
  4187. use_rle = true;
  4188. case TGATools._TYPE_GREY:
  4189. use_grey = true;
  4190. break;
  4191. }
  4192. var pixel_data;
  4193. var numAlphaBits = header.flags & 0xf;
  4194. var pixel_size = header.pixel_size >> 3;
  4195. var pixel_total = header.width * header.height * pixel_size;
  4196. // Read palettes
  4197. var palettes;
  4198. if (use_pal) {
  4199. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4200. }
  4201. // Read LRE
  4202. if (use_rle) {
  4203. pixel_data = new Uint8Array(pixel_total);
  4204. var c, count, i;
  4205. var localOffset = 0;
  4206. var pixels = new Uint8Array(pixel_size);
  4207. while (offset < pixel_total && localOffset < pixel_total) {
  4208. c = data[offset++];
  4209. count = (c & 0x7f) + 1;
  4210. // RLE pixels
  4211. if (c & 0x80) {
  4212. // Bind pixel tmp array
  4213. for (i = 0; i < pixel_size; ++i) {
  4214. pixels[i] = data[offset++];
  4215. }
  4216. // Copy pixel array
  4217. for (i = 0; i < count; ++i) {
  4218. pixel_data.set(pixels, localOffset + i * pixel_size);
  4219. }
  4220. localOffset += pixel_size * count;
  4221. }
  4222. else {
  4223. count *= pixel_size;
  4224. for (i = 0; i < count; ++i) {
  4225. pixel_data[localOffset + i] = data[offset++];
  4226. }
  4227. localOffset += count;
  4228. }
  4229. }
  4230. }
  4231. else {
  4232. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4233. }
  4234. // Load to texture
  4235. var x_start, y_start, x_step, y_step, y_end, x_end;
  4236. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4237. default:
  4238. case TGATools._ORIGIN_UL:
  4239. x_start = 0;
  4240. x_step = 1;
  4241. x_end = header.width;
  4242. y_start = 0;
  4243. y_step = 1;
  4244. y_end = header.height;
  4245. break;
  4246. case TGATools._ORIGIN_BL:
  4247. x_start = 0;
  4248. x_step = 1;
  4249. x_end = header.width;
  4250. y_start = header.height - 1;
  4251. y_step = -1;
  4252. y_end = -1;
  4253. break;
  4254. case TGATools._ORIGIN_UR:
  4255. x_start = header.width - 1;
  4256. x_step = -1;
  4257. x_end = -1;
  4258. y_start = 0;
  4259. y_step = 1;
  4260. y_end = header.height;
  4261. break;
  4262. case TGATools._ORIGIN_BR:
  4263. x_start = header.width - 1;
  4264. x_step = -1;
  4265. x_end = -1;
  4266. y_start = header.height - 1;
  4267. y_step = -1;
  4268. y_end = -1;
  4269. break;
  4270. }
  4271. // Load the specify method
  4272. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4273. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4274. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4275. };
  4276. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4277. var image = pixel_data, colormap = palettes;
  4278. var width = header.width, height = header.height;
  4279. var color, i = 0, x, y;
  4280. var imageData = new Uint8Array(width * height * 4);
  4281. for (y = y_start; y !== y_end; y += y_step) {
  4282. for (x = x_start; x !== x_end; x += x_step, i++) {
  4283. color = image[i];
  4284. imageData[(x + width * y) * 4 + 3] = 255;
  4285. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4286. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4287. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4288. }
  4289. }
  4290. return imageData;
  4291. };
  4292. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4293. var image = pixel_data;
  4294. var width = header.width, height = header.height;
  4295. var color, i = 0, x, y;
  4296. var imageData = new Uint8Array(width * height * 4);
  4297. for (y = y_start; y !== y_end; y += y_step) {
  4298. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4299. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4300. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4301. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4302. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4303. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4304. }
  4305. }
  4306. return imageData;
  4307. };
  4308. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4309. var image = pixel_data;
  4310. var width = header.width, height = header.height;
  4311. var i = 0, x, y;
  4312. var imageData = new Uint8Array(width * height * 4);
  4313. for (y = y_start; y !== y_end; y += y_step) {
  4314. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4315. imageData[(x + width * y) * 4 + 3] = 255;
  4316. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4317. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4318. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4319. }
  4320. }
  4321. return imageData;
  4322. };
  4323. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4324. var image = pixel_data;
  4325. var width = header.width, height = header.height;
  4326. var i = 0, x, y;
  4327. var imageData = new Uint8Array(width * height * 4);
  4328. for (y = y_start; y !== y_end; y += y_step) {
  4329. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4330. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4331. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4332. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4333. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4334. }
  4335. }
  4336. return imageData;
  4337. };
  4338. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4339. var image = pixel_data;
  4340. var width = header.width, height = header.height;
  4341. var color, i = 0, x, y;
  4342. var imageData = new Uint8Array(width * height * 4);
  4343. for (y = y_start; y !== y_end; y += y_step) {
  4344. for (x = x_start; x !== x_end; x += x_step, i++) {
  4345. color = image[i];
  4346. imageData[(x + width * y) * 4 + 0] = color;
  4347. imageData[(x + width * y) * 4 + 1] = color;
  4348. imageData[(x + width * y) * 4 + 2] = color;
  4349. imageData[(x + width * y) * 4 + 3] = 255;
  4350. }
  4351. }
  4352. return imageData;
  4353. };
  4354. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4355. var image = pixel_data;
  4356. var width = header.width, height = header.height;
  4357. var i = 0, x, y;
  4358. var imageData = new Uint8Array(width * height * 4);
  4359. for (y = y_start; y !== y_end; y += y_step) {
  4360. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4361. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4362. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4363. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4364. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4365. }
  4366. }
  4367. return imageData;
  4368. };
  4369. TGATools._TYPE_NO_DATA = 0;
  4370. TGATools._TYPE_INDEXED = 1;
  4371. TGATools._TYPE_RGB = 2;
  4372. TGATools._TYPE_GREY = 3;
  4373. TGATools._TYPE_RLE_INDEXED = 9;
  4374. TGATools._TYPE_RLE_RGB = 10;
  4375. TGATools._TYPE_RLE_GREY = 11;
  4376. TGATools._ORIGIN_MASK = 0x30;
  4377. TGATools._ORIGIN_SHIFT = 0x04;
  4378. TGATools._ORIGIN_BL = 0x00;
  4379. TGATools._ORIGIN_BR = 0x01;
  4380. TGATools._ORIGIN_UL = 0x02;
  4381. TGATools._ORIGIN_UR = 0x03;
  4382. return TGATools;
  4383. }());
  4384. Internals.TGATools = TGATools;
  4385. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4386. })(BABYLON || (BABYLON = {}));
  4387. //# sourceMappingURL=../Tools/babylon.tools.tga.js.map
  4388. var BABYLON;
  4389. (function (BABYLON) {
  4390. var SmartArray = (function () {
  4391. function SmartArray(capacity) {
  4392. this.length = 0;
  4393. this._duplicateId = 0;
  4394. this.data = new Array(capacity);
  4395. this._id = SmartArray._GlobalId++;
  4396. }
  4397. SmartArray.prototype.push = function (value) {
  4398. this.data[this.length++] = value;
  4399. if (this.length > this.data.length) {
  4400. this.data.length *= 2;
  4401. }
  4402. if (!value.__smartArrayFlags) {
  4403. value.__smartArrayFlags = {};
  4404. }
  4405. value.__smartArrayFlags[this._id] = this._duplicateId;
  4406. };
  4407. SmartArray.prototype.pushNoDuplicate = function (value) {
  4408. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4409. return false;
  4410. }
  4411. this.push(value);
  4412. return true;
  4413. };
  4414. SmartArray.prototype.sort = function (compareFn) {
  4415. this.data.sort(compareFn);
  4416. };
  4417. SmartArray.prototype.reset = function () {
  4418. this.length = 0;
  4419. this._duplicateId++;
  4420. };
  4421. SmartArray.prototype.concat = function (array) {
  4422. if (array.length === 0) {
  4423. return;
  4424. }
  4425. if (this.length + array.length > this.data.length) {
  4426. this.data.length = (this.length + array.length) * 2;
  4427. }
  4428. for (var index = 0; index < array.length; index++) {
  4429. this.data[this.length++] = (array.data || array)[index];
  4430. }
  4431. };
  4432. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4433. if (array.length === 0) {
  4434. return;
  4435. }
  4436. if (this.length + array.length > this.data.length) {
  4437. this.data.length = (this.length + array.length) * 2;
  4438. }
  4439. for (var index = 0; index < array.length; index++) {
  4440. var item = (array.data || array)[index];
  4441. this.pushNoDuplicate(item);
  4442. }
  4443. };
  4444. SmartArray.prototype.indexOf = function (value) {
  4445. var position = this.data.indexOf(value);
  4446. if (position >= this.length) {
  4447. return -1;
  4448. }
  4449. return position;
  4450. };
  4451. // Statics
  4452. SmartArray._GlobalId = 0;
  4453. return SmartArray;
  4454. }());
  4455. BABYLON.SmartArray = SmartArray;
  4456. })(BABYLON || (BABYLON = {}));
  4457. //# sourceMappingURL=../Tools/babylon.smartArray.js.map
  4458. var BABYLON;
  4459. (function (BABYLON) {
  4460. /**
  4461. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4462. * The underlying implementation relies on an associative array to ensure the best performances.
  4463. * The value can be anything including 'null' but except 'undefined'
  4464. */
  4465. var StringDictionary = (function () {
  4466. function StringDictionary() {
  4467. this._count = 0;
  4468. this._data = {};
  4469. }
  4470. /**
  4471. * This will clear this dictionary and copy the content from the 'source' one.
  4472. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  4473. * @param source the dictionary to take the content from and copy to this dictionary
  4474. */
  4475. StringDictionary.prototype.copyFrom = function (source) {
  4476. var _this = this;
  4477. this.clear();
  4478. source.forEach(function (t, v) { return _this.add(t, v); });
  4479. };
  4480. /**
  4481. * Get a value based from its key
  4482. * @param key the given key to get the matching value from
  4483. * @return the value if found, otherwise undefined is returned
  4484. */
  4485. StringDictionary.prototype.get = function (key) {
  4486. var val = this._data[key];
  4487. if (val !== undefined) {
  4488. return val;
  4489. }
  4490. return undefined;
  4491. };
  4492. /**
  4493. * Get a value from its key or add it if it doesn't exist.
  4494. * This method will ensure you that a given key/data will be present in the dictionary.
  4495. * @param key the given key to get the matching value from
  4496. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4497. * The factory will only be invoked if there's no data for the given key.
  4498. * @return the value corresponding to the key.
  4499. */
  4500. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4501. var val = this.get(key);
  4502. if (val !== undefined) {
  4503. return val;
  4504. }
  4505. val = factory(key);
  4506. if (val) {
  4507. this.add(key, val);
  4508. }
  4509. return val;
  4510. };
  4511. /**
  4512. * Get a value from its key if present in the dictionary otherwise add it
  4513. * @param key the key to get the value from
  4514. * @param val if there's no such key/value pair in the dictionary add it with this value
  4515. * @return the value corresponding to the key
  4516. */
  4517. StringDictionary.prototype.getOrAdd = function (key, val) {
  4518. var curVal = this.get(key);
  4519. if (curVal !== undefined) {
  4520. return curVal;
  4521. }
  4522. this.add(key, val);
  4523. return val;
  4524. };
  4525. /**
  4526. * Check if there's a given key in the dictionary
  4527. * @param key the key to check for
  4528. * @return true if the key is present, false otherwise
  4529. */
  4530. StringDictionary.prototype.contains = function (key) {
  4531. return this._data[key] !== undefined;
  4532. };
  4533. /**
  4534. * Add a new key and its corresponding value
  4535. * @param key the key to add
  4536. * @param value the value corresponding to the key
  4537. * @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
  4538. */
  4539. StringDictionary.prototype.add = function (key, value) {
  4540. if (this._data[key] !== undefined) {
  4541. return false;
  4542. }
  4543. this._data[key] = value;
  4544. ++this._count;
  4545. return true;
  4546. };
  4547. StringDictionary.prototype.set = function (key, value) {
  4548. if (this._data[key] === undefined) {
  4549. return false;
  4550. }
  4551. this._data[key] = value;
  4552. return true;
  4553. };
  4554. /**
  4555. * Get the element of the given key and remove it from the dictionary
  4556. * @param key
  4557. */
  4558. StringDictionary.prototype.getAndRemove = function (key) {
  4559. var val = this.get(key);
  4560. if (val !== undefined) {
  4561. delete this._data[key];
  4562. --this._count;
  4563. return val;
  4564. }
  4565. return null;
  4566. };
  4567. /**
  4568. * Remove a key/value from the dictionary.
  4569. * @param key the key to remove
  4570. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4571. */
  4572. StringDictionary.prototype.remove = function (key) {
  4573. if (this.contains(key)) {
  4574. delete this._data[key];
  4575. --this._count;
  4576. return true;
  4577. }
  4578. return false;
  4579. };
  4580. /**
  4581. * Clear the whole content of the dictionary
  4582. */
  4583. StringDictionary.prototype.clear = function () {
  4584. this._data = {};
  4585. this._count = 0;
  4586. };
  4587. Object.defineProperty(StringDictionary.prototype, "count", {
  4588. get: function () {
  4589. return this._count;
  4590. },
  4591. enumerable: true,
  4592. configurable: true
  4593. });
  4594. /**
  4595. * Execute a callback on each key/val of the dictionary.
  4596. * Note that you can remove any element in this dictionary in the callback implementation
  4597. * @param callback the callback to execute on a given key/value pair
  4598. */
  4599. StringDictionary.prototype.forEach = function (callback) {
  4600. for (var cur in this._data) {
  4601. var val = this._data[cur];
  4602. callback(cur, val);
  4603. }
  4604. };
  4605. /**
  4606. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4607. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4608. * Note that you can remove any element in this dictionary in the callback implementation
  4609. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4610. */
  4611. StringDictionary.prototype.first = function (callback) {
  4612. for (var cur in this._data) {
  4613. var val = this._data[cur];
  4614. var res = callback(cur, val);
  4615. if (res) {
  4616. return res;
  4617. }
  4618. }
  4619. return null;
  4620. };
  4621. return StringDictionary;
  4622. }());
  4623. BABYLON.StringDictionary = StringDictionary;
  4624. })(BABYLON || (BABYLON = {}));
  4625. //# sourceMappingURL=../Tools/babylon.stringDictionary.js.map
  4626. var BABYLON;
  4627. (function (BABYLON) {
  4628. // Screenshots
  4629. var screenshotCanvas;
  4630. var cloneValue = function (source, destinationObject) {
  4631. if (!source)
  4632. return null;
  4633. if (source instanceof BABYLON.Mesh) {
  4634. return null;
  4635. }
  4636. if (source instanceof BABYLON.SubMesh) {
  4637. return source.clone(destinationObject);
  4638. }
  4639. else if (source.clone) {
  4640. return source.clone();
  4641. }
  4642. return null;
  4643. };
  4644. var Tools = (function () {
  4645. function Tools() {
  4646. }
  4647. Tools.Instantiate = function (className) {
  4648. var arr = className.split(".");
  4649. var fn = (window || this);
  4650. for (var i = 0, len = arr.length; i < len; i++) {
  4651. fn = fn[arr[i]];
  4652. }
  4653. if (typeof fn !== "function") {
  4654. return null;
  4655. }
  4656. return fn;
  4657. };
  4658. Tools.SetImmediate = function (action) {
  4659. if (window.setImmediate) {
  4660. window.setImmediate(action);
  4661. }
  4662. else {
  4663. setTimeout(action, 1);
  4664. }
  4665. };
  4666. Tools.IsExponentOfTwo = function (value) {
  4667. var count = 1;
  4668. do {
  4669. count *= 2;
  4670. } while (count < value);
  4671. return count === value;
  4672. };
  4673. Tools.GetExponentOfTwo = function (value, max) {
  4674. var count = 1;
  4675. do {
  4676. count *= 2;
  4677. } while (count < value);
  4678. if (count > max)
  4679. count = max;
  4680. return count;
  4681. };
  4682. Tools.GetFilename = function (path) {
  4683. var index = path.lastIndexOf("/");
  4684. if (index < 0)
  4685. return path;
  4686. return path.substring(index + 1);
  4687. };
  4688. Tools.GetDOMTextContent = function (element) {
  4689. var result = "";
  4690. var child = element.firstChild;
  4691. while (child) {
  4692. if (child.nodeType === 3) {
  4693. result += child.textContent;
  4694. }
  4695. child = child.nextSibling;
  4696. }
  4697. return result;
  4698. };
  4699. Tools.ToDegrees = function (angle) {
  4700. return angle * 180 / Math.PI;
  4701. };
  4702. Tools.ToRadians = function (angle) {
  4703. return angle * Math.PI / 180;
  4704. };
  4705. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4706. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4707. var output = "";
  4708. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4709. var i = 0;
  4710. var bytes = new Uint8Array(buffer);
  4711. while (i < bytes.length) {
  4712. chr1 = bytes[i++];
  4713. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4714. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4715. enc1 = chr1 >> 2;
  4716. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4717. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4718. enc4 = chr3 & 63;
  4719. if (isNaN(chr2)) {
  4720. enc3 = enc4 = 64;
  4721. }
  4722. else if (isNaN(chr3)) {
  4723. enc4 = 64;
  4724. }
  4725. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4726. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4727. }
  4728. return "data:image/png;base64," + output;
  4729. };
  4730. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4731. if (bias === void 0) { bias = null; }
  4732. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4733. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4734. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4735. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4736. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4737. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4738. }
  4739. if (bias) {
  4740. minimum.x -= minimum.x * bias.x + bias.y;
  4741. minimum.y -= minimum.y * bias.x + bias.y;
  4742. minimum.z -= minimum.z * bias.x + bias.y;
  4743. maximum.x += maximum.x * bias.x + bias.y;
  4744. maximum.y += maximum.y * bias.x + bias.y;
  4745. maximum.z += maximum.z * bias.x + bias.y;
  4746. }
  4747. return {
  4748. minimum: minimum,
  4749. maximum: maximum
  4750. };
  4751. };
  4752. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4753. if (bias === void 0) { bias = null; }
  4754. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4755. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4756. if (!stride) {
  4757. stride = 3;
  4758. }
  4759. for (var index = start; index < start + count; index++) {
  4760. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4761. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4762. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4763. }
  4764. if (bias) {
  4765. minimum.x -= minimum.x * bias.x + bias.y;
  4766. minimum.y -= minimum.y * bias.x + bias.y;
  4767. minimum.z -= minimum.z * bias.x + bias.y;
  4768. maximum.x += maximum.x * bias.x + bias.y;
  4769. maximum.y += maximum.y * bias.x + bias.y;
  4770. maximum.z += maximum.z * bias.x + bias.y;
  4771. }
  4772. return {
  4773. minimum: minimum,
  4774. maximum: maximum
  4775. };
  4776. };
  4777. Tools.Vector2ArrayFeeder = function (array) {
  4778. return function (index) {
  4779. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4780. var length = isFloatArray ? array.length / 2 : array.length;
  4781. if (index >= length) {
  4782. return null;
  4783. }
  4784. if (isFloatArray) {
  4785. var fa = array;
  4786. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4787. }
  4788. var a = array;
  4789. return a[index];
  4790. };
  4791. };
  4792. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4793. if (bias === void 0) { bias = null; }
  4794. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4795. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4796. var i = 0;
  4797. var cur = feeder(i++);
  4798. while (cur) {
  4799. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4800. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4801. cur = feeder(i++);
  4802. }
  4803. if (bias) {
  4804. minimum.x -= minimum.x * bias.x + bias.y;
  4805. minimum.y -= minimum.y * bias.x + bias.y;
  4806. maximum.x += maximum.x * bias.x + bias.y;
  4807. maximum.y += maximum.y * bias.x + bias.y;
  4808. }
  4809. return {
  4810. minimum: minimum,
  4811. maximum: maximum
  4812. };
  4813. };
  4814. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4815. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4816. return undefined;
  4817. return Array.isArray(obj) ? obj : [obj];
  4818. };
  4819. // Misc.
  4820. Tools.GetPointerPrefix = function () {
  4821. var eventPrefix = "pointer";
  4822. // Check if pointer events are supported
  4823. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4824. eventPrefix = "mouse";
  4825. }
  4826. return eventPrefix;
  4827. };
  4828. /**
  4829. * @param func - the function to be called
  4830. * @param requester - the object that will request the next frame. Falls back to window.
  4831. */
  4832. Tools.QueueNewFrame = function (func, requester) {
  4833. if (requester === void 0) { requester = window; }
  4834. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4835. /*if(requester.isPresenting) {
  4836. return;
  4837. } else*/ if (requester.requestAnimationFrame)
  4838. requester.requestAnimationFrame(func);
  4839. else if (requester.msRequestAnimationFrame)
  4840. requester.msRequestAnimationFrame(func);
  4841. else if (requester.webkitRequestAnimationFrame)
  4842. requester.webkitRequestAnimationFrame(func);
  4843. else if (requester.mozRequestAnimationFrame)
  4844. requester.mozRequestAnimationFrame(func);
  4845. else if (requester.oRequestAnimationFrame)
  4846. requester.oRequestAnimationFrame(func);
  4847. else {
  4848. window.setTimeout(func, 16);
  4849. }
  4850. };
  4851. Tools.RequestFullscreen = function (element) {
  4852. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4853. if (!requestFunction)
  4854. return;
  4855. requestFunction.call(element);
  4856. };
  4857. Tools.ExitFullscreen = function () {
  4858. if (document.exitFullscreen) {
  4859. document.exitFullscreen();
  4860. }
  4861. else if (document.mozCancelFullScreen) {
  4862. document.mozCancelFullScreen();
  4863. }
  4864. else if (document.webkitCancelFullScreen) {
  4865. document.webkitCancelFullScreen();
  4866. }
  4867. else if (document.msCancelFullScreen) {
  4868. document.msCancelFullScreen();
  4869. }
  4870. };
  4871. Tools.SetCorsBehavior = function (url, img) {
  4872. if (Tools.CorsBehavior) {
  4873. switch (typeof (Tools.CorsBehavior)) {
  4874. case "function":
  4875. var result = Tools.CorsBehavior(url);
  4876. if (result) {
  4877. return result;
  4878. }
  4879. break;
  4880. case "string":
  4881. default:
  4882. img.crossOrigin = Tools.CorsBehavior;
  4883. break;
  4884. }
  4885. }
  4886. };
  4887. // External files
  4888. Tools.CleanUrl = function (url) {
  4889. url = url.replace(/#/mg, "%23");
  4890. return url;
  4891. };
  4892. Tools.LoadImage = function (url, onload, onerror, database) {
  4893. if (url instanceof ArrayBuffer) {
  4894. url = Tools.EncodeArrayBufferTobase64(url);
  4895. }
  4896. url = Tools.CleanUrl(url);
  4897. var img = new Image();
  4898. if (url.substr(0, 5) !== "data:") {
  4899. Tools.SetCorsBehavior(url, img);
  4900. }
  4901. img.onload = function () {
  4902. onload(img);
  4903. };
  4904. img.onerror = function (err) {
  4905. Tools.Error("Error while trying to load texture: " + url);
  4906. if (Tools.UseFallbackTexture) {
  4907. img.src = "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";
  4908. onload(img);
  4909. }
  4910. else {
  4911. onerror();
  4912. }
  4913. };
  4914. var noIndexedDB = function () {
  4915. img.src = url;
  4916. };
  4917. var loadFromIndexedDB = function () {
  4918. database.loadImageFromDB(url, img);
  4919. };
  4920. //ANY database to do!
  4921. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4922. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4923. }
  4924. else {
  4925. if (url.indexOf("file:") === -1) {
  4926. noIndexedDB();
  4927. }
  4928. else {
  4929. try {
  4930. var textureName = url.substring(5).toLowerCase();
  4931. var blobURL;
  4932. try {
  4933. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4934. }
  4935. catch (ex) {
  4936. // Chrome doesn't support oneTimeOnly parameter
  4937. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4938. }
  4939. img.src = blobURL;
  4940. }
  4941. catch (e) {
  4942. img.src = null;
  4943. }
  4944. }
  4945. }
  4946. return img;
  4947. };
  4948. //ANY
  4949. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4950. url = Tools.CleanUrl(url);
  4951. var noIndexedDB = function () {
  4952. var request = new XMLHttpRequest();
  4953. var loadUrl = Tools.BaseUrl + url;
  4954. request.open('GET', loadUrl, true);
  4955. if (useArrayBuffer) {
  4956. request.responseType = "arraybuffer";
  4957. }
  4958. request.onprogress = progressCallBack;
  4959. request.onreadystatechange = function () {
  4960. if (request.readyState === 4) {
  4961. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4962. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4963. callback(!useArrayBuffer ? request.responseText : request.response);
  4964. }
  4965. else {
  4966. if (onError) {
  4967. onError();
  4968. }
  4969. else {
  4970. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4971. }
  4972. }
  4973. }
  4974. };
  4975. request.send(null);
  4976. };
  4977. var loadFromIndexedDB = function () {
  4978. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4979. };
  4980. if (url.indexOf("file:") !== -1) {
  4981. var fileName = url.substring(5).toLowerCase();
  4982. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4983. }
  4984. else {
  4985. // Caching all files
  4986. if (database && database.enableSceneOffline) {
  4987. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4988. }
  4989. else {
  4990. noIndexedDB();
  4991. }
  4992. }
  4993. };
  4994. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4995. var reader = new FileReader();
  4996. reader.onload = function (e) {
  4997. //target doesn't have result from ts 1.3
  4998. callback(e.target['result']);
  4999. };
  5000. reader.onprogress = progressCallback;
  5001. reader.readAsDataURL(fileToLoad);
  5002. };
  5003. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5004. var reader = new FileReader();
  5005. reader.onerror = function (e) {
  5006. Tools.Log("Error while reading file: " + fileToLoad.name);
  5007. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5008. };
  5009. reader.onload = function (e) {
  5010. //target doesn't have result from ts 1.3
  5011. callback(e.target['result']);
  5012. };
  5013. reader.onprogress = progressCallBack;
  5014. if (!useArrayBuffer) {
  5015. // Asynchronous read
  5016. reader.readAsText(fileToLoad);
  5017. }
  5018. else {
  5019. reader.readAsArrayBuffer(fileToLoad);
  5020. }
  5021. };
  5022. //returns a downloadable url to a file content.
  5023. Tools.FileAsURL = function (content) {
  5024. var fileBlob = new Blob([content]);
  5025. var url = window.URL || window.webkitURL;
  5026. var link = url.createObjectURL(fileBlob);
  5027. return link;
  5028. };
  5029. // Misc.
  5030. Tools.Format = function (value, decimals) {
  5031. if (decimals === void 0) { decimals = 2; }
  5032. return value.toFixed(decimals);
  5033. };
  5034. Tools.CheckExtends = function (v, min, max) {
  5035. if (v.x < min.x)
  5036. min.x = v.x;
  5037. if (v.y < min.y)
  5038. min.y = v.y;
  5039. if (v.z < min.z)
  5040. min.z = v.z;
  5041. if (v.x > max.x)
  5042. max.x = v.x;
  5043. if (v.y > max.y)
  5044. max.y = v.y;
  5045. if (v.z > max.z)
  5046. max.z = v.z;
  5047. };
  5048. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5049. for (var prop in source) {
  5050. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5051. continue;
  5052. }
  5053. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5054. continue;
  5055. }
  5056. var sourceValue = source[prop];
  5057. var typeOfSourceValue = typeof sourceValue;
  5058. if (typeOfSourceValue === "function") {
  5059. continue;
  5060. }
  5061. if (typeOfSourceValue === "object") {
  5062. if (sourceValue instanceof Array) {
  5063. destination[prop] = [];
  5064. if (sourceValue.length > 0) {
  5065. if (typeof sourceValue[0] == "object") {
  5066. for (var index = 0; index < sourceValue.length; index++) {
  5067. var clonedValue = cloneValue(sourceValue[index], destination);
  5068. if (destination[prop].indexOf(clonedValue) === -1) {
  5069. destination[prop].push(clonedValue);
  5070. }
  5071. }
  5072. }
  5073. else {
  5074. destination[prop] = sourceValue.slice(0);
  5075. }
  5076. }
  5077. }
  5078. else {
  5079. destination[prop] = cloneValue(sourceValue, destination);
  5080. }
  5081. }
  5082. else {
  5083. destination[prop] = sourceValue;
  5084. }
  5085. }
  5086. };
  5087. Tools.IsEmpty = function (obj) {
  5088. for (var i in obj) {
  5089. return false;
  5090. }
  5091. return true;
  5092. };
  5093. Tools.RegisterTopRootEvents = function (events) {
  5094. for (var index = 0; index < events.length; index++) {
  5095. var event = events[index];
  5096. window.addEventListener(event.name, event.handler, false);
  5097. try {
  5098. if (window.parent) {
  5099. window.parent.addEventListener(event.name, event.handler, false);
  5100. }
  5101. }
  5102. catch (e) {
  5103. }
  5104. }
  5105. };
  5106. Tools.UnregisterTopRootEvents = function (events) {
  5107. for (var index = 0; index < events.length; index++) {
  5108. var event = events[index];
  5109. window.removeEventListener(event.name, event.handler);
  5110. try {
  5111. if (window.parent) {
  5112. window.parent.removeEventListener(event.name, event.handler);
  5113. }
  5114. }
  5115. catch (e) {
  5116. }
  5117. }
  5118. };
  5119. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5120. if (mimeType === void 0) { mimeType = "image/png"; }
  5121. // Read the contents of the framebuffer
  5122. var numberOfChannelsByLine = width * 4;
  5123. var halfHeight = height / 2;
  5124. //Reading datas from WebGL
  5125. var data = engine.readPixels(0, 0, width, height);
  5126. //To flip image on Y axis.
  5127. for (var i = 0; i < halfHeight; i++) {
  5128. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5129. var currentCell = j + i * numberOfChannelsByLine;
  5130. var targetLine = height - i - 1;
  5131. var targetCell = j + targetLine * numberOfChannelsByLine;
  5132. var temp = data[currentCell];
  5133. data[currentCell] = data[targetCell];
  5134. data[targetCell] = temp;
  5135. }
  5136. }
  5137. // Create a 2D canvas to store the result
  5138. if (!screenshotCanvas) {
  5139. screenshotCanvas = document.createElement('canvas');
  5140. }
  5141. screenshotCanvas.width = width;
  5142. screenshotCanvas.height = height;
  5143. var context = screenshotCanvas.getContext('2d');
  5144. // Copy the pixels to a 2D canvas
  5145. var imageData = context.createImageData(width, height);
  5146. var castData = (imageData.data);
  5147. castData.set(data);
  5148. context.putImageData(imageData, 0, 0);
  5149. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5150. };
  5151. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5152. if (mimeType === void 0) { mimeType = "image/png"; }
  5153. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5154. if (successCallback) {
  5155. successCallback(base64Image);
  5156. }
  5157. else {
  5158. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5159. if (("download" in document.createElement("a"))) {
  5160. var a = window.document.createElement("a");
  5161. a.href = base64Image;
  5162. var date = new Date();
  5163. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5164. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5165. window.document.body.appendChild(a);
  5166. a.addEventListener("click", function () {
  5167. a.parentElement.removeChild(a);
  5168. });
  5169. a.click();
  5170. }
  5171. else {
  5172. var newWindow = window.open("");
  5173. var img = newWindow.document.createElement("img");
  5174. img.src = base64Image;
  5175. newWindow.document.body.appendChild(img);
  5176. }
  5177. }
  5178. };
  5179. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5180. if (mimeType === void 0) { mimeType = "image/png"; }
  5181. var width;
  5182. var height;
  5183. // If a precision value is specified
  5184. if (size.precision) {
  5185. width = Math.round(engine.getRenderWidth() * size.precision);
  5186. height = Math.round(width / engine.getAspectRatio(camera));
  5187. }
  5188. else if (size.width && size.height) {
  5189. width = size.width;
  5190. height = size.height;
  5191. }
  5192. else if (size.width && !size.height) {
  5193. width = size.width;
  5194. height = Math.round(width / engine.getAspectRatio(camera));
  5195. }
  5196. else if (size.height && !size.width) {
  5197. height = size.height;
  5198. width = Math.round(height * engine.getAspectRatio(camera));
  5199. }
  5200. else if (!isNaN(size)) {
  5201. height = size;
  5202. width = size;
  5203. }
  5204. else {
  5205. Tools.Error("Invalid 'size' parameter !");
  5206. return;
  5207. }
  5208. if (!screenshotCanvas) {
  5209. screenshotCanvas = document.createElement('canvas');
  5210. }
  5211. screenshotCanvas.width = width;
  5212. screenshotCanvas.height = height;
  5213. var renderContext = screenshotCanvas.getContext("2d");
  5214. renderContext.drawImage(engine.getRenderingCanvas(), 0, 0, width, height);
  5215. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5216. };
  5217. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5218. if (mimeType === void 0) { mimeType = "image/png"; }
  5219. var width;
  5220. var height;
  5221. //If a precision value is specified
  5222. if (size.precision) {
  5223. width = Math.round(engine.getRenderWidth() * size.precision);
  5224. height = Math.round(width / engine.getAspectRatio(camera));
  5225. size = { width: width, height: height };
  5226. }
  5227. else if (size.width && size.height) {
  5228. width = size.width;
  5229. height = size.height;
  5230. }
  5231. else if (size.width && !size.height) {
  5232. width = size.width;
  5233. height = Math.round(width / engine.getAspectRatio(camera));
  5234. size = { width: width, height: height };
  5235. }
  5236. else if (size.height && !size.width) {
  5237. height = size.height;
  5238. width = Math.round(height * engine.getAspectRatio(camera));
  5239. size = { width: width, height: height };
  5240. }
  5241. else if (!isNaN(size)) {
  5242. height = size;
  5243. width = size;
  5244. }
  5245. else {
  5246. Tools.Error("Invalid 'size' parameter !");
  5247. return;
  5248. }
  5249. var scene = camera.getScene();
  5250. var previousCamera = null;
  5251. if (scene.activeCamera !== camera) {
  5252. previousCamera = scene.activeCamera;
  5253. scene.activeCamera = camera;
  5254. }
  5255. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5256. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5257. texture.renderList = scene.meshes;
  5258. texture.onAfterRenderObservable.add(function () {
  5259. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5260. });
  5261. scene.incrementRenderId();
  5262. scene.resetCachedMaterial();
  5263. texture.render(true);
  5264. texture.dispose();
  5265. if (previousCamera) {
  5266. scene.activeCamera = previousCamera;
  5267. }
  5268. camera.getProjectionMatrix(true); // Force cache refresh;
  5269. };
  5270. // XHR response validator for local file scenario
  5271. Tools.ValidateXHRData = function (xhr, dataType) {
  5272. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5273. if (dataType === void 0) { dataType = 7; }
  5274. try {
  5275. if (dataType & 1) {
  5276. if (xhr.responseText && xhr.responseText.length > 0) {
  5277. return true;
  5278. }
  5279. else if (dataType === 1) {
  5280. return false;
  5281. }
  5282. }
  5283. if (dataType & 2) {
  5284. // Check header width and height since there is no "TGA" magic number
  5285. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5286. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5287. return true;
  5288. }
  5289. else if (dataType === 2) {
  5290. return false;
  5291. }
  5292. }
  5293. if (dataType & 4) {
  5294. // Check for the "DDS" magic number
  5295. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5296. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5297. return true;
  5298. }
  5299. else {
  5300. return false;
  5301. }
  5302. }
  5303. }
  5304. catch (e) {
  5305. }
  5306. return false;
  5307. };
  5308. /**
  5309. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5310. * Be aware Math.random() could cause collisions, but:
  5311. * "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"
  5312. */
  5313. Tools.RandomId = function () {
  5314. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5315. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5316. return v.toString(16);
  5317. });
  5318. };
  5319. Object.defineProperty(Tools, "NoneLogLevel", {
  5320. get: function () {
  5321. return Tools._NoneLogLevel;
  5322. },
  5323. enumerable: true,
  5324. configurable: true
  5325. });
  5326. Object.defineProperty(Tools, "MessageLogLevel", {
  5327. get: function () {
  5328. return Tools._MessageLogLevel;
  5329. },
  5330. enumerable: true,
  5331. configurable: true
  5332. });
  5333. Object.defineProperty(Tools, "WarningLogLevel", {
  5334. get: function () {
  5335. return Tools._WarningLogLevel;
  5336. },
  5337. enumerable: true,
  5338. configurable: true
  5339. });
  5340. Object.defineProperty(Tools, "ErrorLogLevel", {
  5341. get: function () {
  5342. return Tools._ErrorLogLevel;
  5343. },
  5344. enumerable: true,
  5345. configurable: true
  5346. });
  5347. Object.defineProperty(Tools, "AllLogLevel", {
  5348. get: function () {
  5349. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5350. },
  5351. enumerable: true,
  5352. configurable: true
  5353. });
  5354. Tools._AddLogEntry = function (entry) {
  5355. Tools._LogCache = entry + Tools._LogCache;
  5356. if (Tools.OnNewCacheEntry) {
  5357. Tools.OnNewCacheEntry(entry);
  5358. }
  5359. };
  5360. Tools._FormatMessage = function (message) {
  5361. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5362. var date = new Date();
  5363. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5364. };
  5365. Tools._LogDisabled = function (message) {
  5366. // nothing to do
  5367. };
  5368. Tools._LogEnabled = function (message) {
  5369. var formattedMessage = Tools._FormatMessage(message);
  5370. console.log("BJS - " + formattedMessage);
  5371. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5372. Tools._AddLogEntry(entry);
  5373. };
  5374. Tools._WarnDisabled = function (message) {
  5375. // nothing to do
  5376. };
  5377. Tools._WarnEnabled = function (message) {
  5378. var formattedMessage = Tools._FormatMessage(message);
  5379. console.warn("BJS - " + formattedMessage);
  5380. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5381. Tools._AddLogEntry(entry);
  5382. };
  5383. Tools._ErrorDisabled = function (message) {
  5384. // nothing to do
  5385. };
  5386. Tools._ErrorEnabled = function (message) {
  5387. Tools.errorsCount++;
  5388. var formattedMessage = Tools._FormatMessage(message);
  5389. console.error("BJS - " + formattedMessage);
  5390. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5391. Tools._AddLogEntry(entry);
  5392. };
  5393. Object.defineProperty(Tools, "LogCache", {
  5394. get: function () {
  5395. return Tools._LogCache;
  5396. },
  5397. enumerable: true,
  5398. configurable: true
  5399. });
  5400. Tools.ClearLogCache = function () {
  5401. Tools._LogCache = "";
  5402. Tools.errorsCount = 0;
  5403. };
  5404. Object.defineProperty(Tools, "LogLevels", {
  5405. set: function (level) {
  5406. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5407. Tools.Log = Tools._LogEnabled;
  5408. }
  5409. else {
  5410. Tools.Log = Tools._LogDisabled;
  5411. }
  5412. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5413. Tools.Warn = Tools._WarnEnabled;
  5414. }
  5415. else {
  5416. Tools.Warn = Tools._WarnDisabled;
  5417. }
  5418. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5419. Tools.Error = Tools._ErrorEnabled;
  5420. }
  5421. else {
  5422. Tools.Error = Tools._ErrorDisabled;
  5423. }
  5424. },
  5425. enumerable: true,
  5426. configurable: true
  5427. });
  5428. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5429. get: function () {
  5430. return Tools._PerformanceNoneLogLevel;
  5431. },
  5432. enumerable: true,
  5433. configurable: true
  5434. });
  5435. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5436. get: function () {
  5437. return Tools._PerformanceUserMarkLogLevel;
  5438. },
  5439. enumerable: true,
  5440. configurable: true
  5441. });
  5442. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5443. get: function () {
  5444. return Tools._PerformanceConsoleLogLevel;
  5445. },
  5446. enumerable: true,
  5447. configurable: true
  5448. });
  5449. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5450. set: function (level) {
  5451. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5452. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5453. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5454. return;
  5455. }
  5456. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5457. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5458. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5459. return;
  5460. }
  5461. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5462. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5463. },
  5464. enumerable: true,
  5465. configurable: true
  5466. });
  5467. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5468. };
  5469. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5470. };
  5471. Tools._StartUserMark = function (counterName, condition) {
  5472. if (condition === void 0) { condition = true; }
  5473. if (!condition || !Tools._performance.mark) {
  5474. return;
  5475. }
  5476. Tools._performance.mark(counterName + "-Begin");
  5477. };
  5478. Tools._EndUserMark = function (counterName, condition) {
  5479. if (condition === void 0) { condition = true; }
  5480. if (!condition || !Tools._performance.mark) {
  5481. return;
  5482. }
  5483. Tools._performance.mark(counterName + "-End");
  5484. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5485. };
  5486. Tools._StartPerformanceConsole = function (counterName, condition) {
  5487. if (condition === void 0) { condition = true; }
  5488. if (!condition) {
  5489. return;
  5490. }
  5491. Tools._StartUserMark(counterName, condition);
  5492. if (console.time) {
  5493. console.time(counterName);
  5494. }
  5495. };
  5496. Tools._EndPerformanceConsole = function (counterName, condition) {
  5497. if (condition === void 0) { condition = true; }
  5498. if (!condition) {
  5499. return;
  5500. }
  5501. Tools._EndUserMark(counterName, condition);
  5502. if (console.time) {
  5503. console.timeEnd(counterName);
  5504. }
  5505. };
  5506. Object.defineProperty(Tools, "Now", {
  5507. get: function () {
  5508. if (window.performance && window.performance.now) {
  5509. return window.performance.now();
  5510. }
  5511. return new Date().getTime();
  5512. },
  5513. enumerable: true,
  5514. configurable: true
  5515. });
  5516. /**
  5517. * This method will return the name of the class used to create the instance of the given object.
  5518. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5519. * @param object the object to get the class name from
  5520. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5521. */
  5522. Tools.getClassName = function (object, isType) {
  5523. if (isType === void 0) { isType = false; }
  5524. var name = null;
  5525. if (!isType && object.getClassName) {
  5526. name = object.getClassName();
  5527. }
  5528. else {
  5529. if (object instanceof Object) {
  5530. var classObj = isType ? object : Object.getPrototypeOf(object);
  5531. name = classObj.constructor["__bjsclassName__"];
  5532. }
  5533. if (!name) {
  5534. name = typeof object;
  5535. }
  5536. }
  5537. return name;
  5538. };
  5539. Tools.first = function (array, predicate) {
  5540. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5541. var el = array_1[_i];
  5542. if (predicate(el)) {
  5543. return el;
  5544. }
  5545. }
  5546. };
  5547. /**
  5548. * This method will return the name of the full name of the class, including its owning module (if any).
  5549. * 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).
  5550. * @param object the object to get the class name from
  5551. * @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.
  5552. */
  5553. Tools.getFullClassName = function (object, isType) {
  5554. if (isType === void 0) { isType = false; }
  5555. var className = null;
  5556. var moduleName = null;
  5557. if (!isType && object.getClassName) {
  5558. className = object.getClassName();
  5559. }
  5560. else {
  5561. if (object instanceof Object) {
  5562. var classObj = isType ? object : Object.getPrototypeOf(object);
  5563. className = classObj.constructor["__bjsclassName__"];
  5564. moduleName = classObj.constructor["__bjsmoduleName__"];
  5565. }
  5566. if (!className) {
  5567. className = typeof object;
  5568. }
  5569. }
  5570. if (!className) {
  5571. return null;
  5572. }
  5573. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  5574. };
  5575. /**
  5576. * 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.
  5577. * @param array
  5578. */
  5579. Tools.arrayOrStringFeeder = function (array) {
  5580. return function (index) {
  5581. if (index >= array.length) {
  5582. return null;
  5583. }
  5584. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5585. if (val && val.getHashCode) {
  5586. val = val.getHashCode();
  5587. }
  5588. if (typeof val === "string") {
  5589. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5590. }
  5591. return val;
  5592. };
  5593. };
  5594. /**
  5595. * Compute the hashCode of a stream of number
  5596. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5597. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5598. * @return the hash code computed
  5599. */
  5600. Tools.hashCodeFromStream = function (feeder) {
  5601. // Based from here: http://stackoverflow.com/a/7616484/802124
  5602. var hash = 0;
  5603. var index = 0;
  5604. var chr = feeder(index++);
  5605. while (chr != null) {
  5606. hash = ((hash << 5) - hash) + chr;
  5607. hash |= 0; // Convert to 32bit integer
  5608. chr = feeder(index++);
  5609. }
  5610. return hash;
  5611. };
  5612. Tools.BaseUrl = "";
  5613. Tools.CorsBehavior = "anonymous";
  5614. Tools.UseFallbackTexture = true;
  5615. // Logs
  5616. Tools._NoneLogLevel = 0;
  5617. Tools._MessageLogLevel = 1;
  5618. Tools._WarningLogLevel = 2;
  5619. Tools._ErrorLogLevel = 4;
  5620. Tools._LogCache = "";
  5621. Tools.errorsCount = 0;
  5622. Tools.Log = Tools._LogEnabled;
  5623. Tools.Warn = Tools._WarnEnabled;
  5624. Tools.Error = Tools._ErrorEnabled;
  5625. // Performances
  5626. Tools._PerformanceNoneLogLevel = 0;
  5627. Tools._PerformanceUserMarkLogLevel = 1;
  5628. Tools._PerformanceConsoleLogLevel = 2;
  5629. Tools._performance = window.performance;
  5630. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5631. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5632. return Tools;
  5633. }());
  5634. BABYLON.Tools = Tools;
  5635. /**
  5636. * This class is used to track a performance counter which is number based.
  5637. * The user has access to many properties which give statistics of different nature
  5638. *
  5639. * The implementer can track two kinds of Performance Counter: time and count
  5640. * 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.
  5641. * 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.
  5642. */
  5643. var PerfCounter = (function () {
  5644. function PerfCounter() {
  5645. this._startMonitoringTime = 0;
  5646. this._min = 0;
  5647. this._max = 0;
  5648. this._average = 0;
  5649. this._lastSecAverage = 0;
  5650. this._current = 0;
  5651. this._totalValueCount = 0;
  5652. this._totalAccumulated = 0;
  5653. this._lastSecAccumulated = 0;
  5654. this._lastSecTime = 0;
  5655. this._lastSecValueCount = 0;
  5656. }
  5657. Object.defineProperty(PerfCounter.prototype, "min", {
  5658. /**
  5659. * Returns the smallest value ever
  5660. */
  5661. get: function () {
  5662. return this._min;
  5663. },
  5664. enumerable: true,
  5665. configurable: true
  5666. });
  5667. Object.defineProperty(PerfCounter.prototype, "max", {
  5668. /**
  5669. * Returns the biggest value ever
  5670. */
  5671. get: function () {
  5672. return this._max;
  5673. },
  5674. enumerable: true,
  5675. configurable: true
  5676. });
  5677. Object.defineProperty(PerfCounter.prototype, "average", {
  5678. /**
  5679. * Returns the average value since the performance counter is running
  5680. */
  5681. get: function () {
  5682. return this._average;
  5683. },
  5684. enumerable: true,
  5685. configurable: true
  5686. });
  5687. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5688. /**
  5689. * Returns the average value of the last second the counter was monitored
  5690. */
  5691. get: function () {
  5692. return this._lastSecAverage;
  5693. },
  5694. enumerable: true,
  5695. configurable: true
  5696. });
  5697. Object.defineProperty(PerfCounter.prototype, "current", {
  5698. /**
  5699. * Returns the current value
  5700. */
  5701. get: function () {
  5702. return this._current;
  5703. },
  5704. enumerable: true,
  5705. configurable: true
  5706. });
  5707. Object.defineProperty(PerfCounter.prototype, "total", {
  5708. get: function () {
  5709. return this._totalAccumulated;
  5710. },
  5711. enumerable: true,
  5712. configurable: true
  5713. });
  5714. /**
  5715. * Call this method to start monitoring a new frame.
  5716. * 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.
  5717. */
  5718. PerfCounter.prototype.fetchNewFrame = function () {
  5719. this._totalValueCount++;
  5720. this._current = 0;
  5721. this._lastSecValueCount++;
  5722. };
  5723. /**
  5724. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5725. * @param newCount the count value to add to the monitored count
  5726. * @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.
  5727. */
  5728. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5729. this._current += newCount;
  5730. if (fetchResult) {
  5731. this._fetchResult();
  5732. }
  5733. };
  5734. /**
  5735. * Start monitoring this performance counter
  5736. */
  5737. PerfCounter.prototype.beginMonitoring = function () {
  5738. this._startMonitoringTime = Tools.Now;
  5739. };
  5740. /**
  5741. * Compute the time lapsed since the previous beginMonitoring() call.
  5742. * @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
  5743. */
  5744. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5745. if (newFrame === void 0) { newFrame = true; }
  5746. if (newFrame) {
  5747. this.fetchNewFrame();
  5748. }
  5749. var currentTime = Tools.Now;
  5750. this._current = currentTime - this._startMonitoringTime;
  5751. if (newFrame) {
  5752. this._fetchResult();
  5753. }
  5754. };
  5755. PerfCounter.prototype._fetchResult = function () {
  5756. this._totalAccumulated += this._current;
  5757. this._lastSecAccumulated += this._current;
  5758. // Min/Max update
  5759. this._min = Math.min(this._min, this._current);
  5760. this._max = Math.max(this._max, this._current);
  5761. this._average = this._totalAccumulated / this._totalValueCount;
  5762. // Reset last sec?
  5763. var now = Tools.Now;
  5764. if ((now - this._lastSecTime) > 1000) {
  5765. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5766. this._lastSecTime = now;
  5767. this._lastSecAccumulated = 0;
  5768. this._lastSecValueCount = 0;
  5769. }
  5770. };
  5771. return PerfCounter;
  5772. }());
  5773. BABYLON.PerfCounter = PerfCounter;
  5774. /**
  5775. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  5776. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5777. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5778. * @param name The name of the class, case should be preserved
  5779. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  5780. */
  5781. function className(name, module) {
  5782. return function (target) {
  5783. target["__bjsclassName__"] = name;
  5784. target["__bjsmoduleName__"] = (module != null) ? module : null;
  5785. };
  5786. }
  5787. BABYLON.className = className;
  5788. /**
  5789. * An implementation of a loop for asynchronous functions.
  5790. */
  5791. var AsyncLoop = (function () {
  5792. /**
  5793. * Constroctor.
  5794. * @param iterations the number of iterations.
  5795. * @param _fn the function to run each iteration
  5796. * @param _successCallback the callback that will be called upon succesful execution
  5797. * @param offset starting offset.
  5798. */
  5799. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5800. if (offset === void 0) { offset = 0; }
  5801. this.iterations = iterations;
  5802. this._fn = _fn;
  5803. this._successCallback = _successCallback;
  5804. this.index = offset - 1;
  5805. this._done = false;
  5806. }
  5807. /**
  5808. * Execute the next iteration. Must be called after the last iteration was finished.
  5809. */
  5810. AsyncLoop.prototype.executeNext = function () {
  5811. if (!this._done) {
  5812. if (this.index + 1 < this.iterations) {
  5813. ++this.index;
  5814. this._fn(this);
  5815. }
  5816. else {
  5817. this.breakLoop();
  5818. }
  5819. }
  5820. };
  5821. /**
  5822. * Break the loop and run the success callback.
  5823. */
  5824. AsyncLoop.prototype.breakLoop = function () {
  5825. this._done = true;
  5826. this._successCallback();
  5827. };
  5828. /**
  5829. * Helper function
  5830. */
  5831. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5832. if (offset === void 0) { offset = 0; }
  5833. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5834. loop.executeNext();
  5835. return loop;
  5836. };
  5837. /**
  5838. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5839. * @param iterations total number of iterations
  5840. * @param syncedIterations number of synchronous iterations in each async iteration.
  5841. * @param fn the function to call each iteration.
  5842. * @param callback a success call back that will be called when iterating stops.
  5843. * @param breakFunction a break condition (optional)
  5844. * @param timeout timeout settings for the setTimeout function. default - 0.
  5845. * @constructor
  5846. */
  5847. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5848. if (timeout === void 0) { timeout = 0; }
  5849. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5850. if (breakFunction && breakFunction())
  5851. loop.breakLoop();
  5852. else {
  5853. setTimeout(function () {
  5854. for (var i = 0; i < syncedIterations; ++i) {
  5855. var iteration = (loop.index * syncedIterations) + i;
  5856. if (iteration >= iterations)
  5857. break;
  5858. fn(iteration);
  5859. if (breakFunction && breakFunction()) {
  5860. loop.breakLoop();
  5861. break;
  5862. }
  5863. }
  5864. loop.executeNext();
  5865. }, timeout);
  5866. }
  5867. }, callback);
  5868. };
  5869. return AsyncLoop;
  5870. }());
  5871. BABYLON.AsyncLoop = AsyncLoop;
  5872. })(BABYLON || (BABYLON = {}));
  5873. //# sourceMappingURL=../Tools/babylon.tools.js.map
  5874. var BABYLON;
  5875. (function (BABYLON) {
  5876. var Internals;
  5877. (function (Internals) {
  5878. var _AlphaState = (function () {
  5879. /**
  5880. * Initializes the state.
  5881. */
  5882. function _AlphaState() {
  5883. this._isAlphaBlendDirty = false;
  5884. this._isBlendFunctionParametersDirty = false;
  5885. this._alphaBlend = false;
  5886. this._blendFunctionParameters = new Array(4);
  5887. this.reset();
  5888. }
  5889. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5890. get: function () {
  5891. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5892. },
  5893. enumerable: true,
  5894. configurable: true
  5895. });
  5896. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5897. get: function () {
  5898. return this._alphaBlend;
  5899. },
  5900. set: function (value) {
  5901. if (this._alphaBlend === value) {
  5902. return;
  5903. }
  5904. this._alphaBlend = value;
  5905. this._isAlphaBlendDirty = true;
  5906. },
  5907. enumerable: true,
  5908. configurable: true
  5909. });
  5910. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5911. if (this._blendFunctionParameters[0] === value0 &&
  5912. this._blendFunctionParameters[1] === value1 &&
  5913. this._blendFunctionParameters[2] === value2 &&
  5914. this._blendFunctionParameters[3] === value3) {
  5915. return;
  5916. }
  5917. this._blendFunctionParameters[0] = value0;
  5918. this._blendFunctionParameters[1] = value1;
  5919. this._blendFunctionParameters[2] = value2;
  5920. this._blendFunctionParameters[3] = value3;
  5921. this._isBlendFunctionParametersDirty = true;
  5922. };
  5923. _AlphaState.prototype.reset = function () {
  5924. this._alphaBlend = false;
  5925. this._blendFunctionParameters[0] = null;
  5926. this._blendFunctionParameters[1] = null;
  5927. this._blendFunctionParameters[2] = null;
  5928. this._blendFunctionParameters[3] = null;
  5929. this._isAlphaBlendDirty = true;
  5930. this._isBlendFunctionParametersDirty = false;
  5931. };
  5932. _AlphaState.prototype.apply = function (gl) {
  5933. if (!this.isDirty) {
  5934. return;
  5935. }
  5936. // Alpha blend
  5937. if (this._isAlphaBlendDirty) {
  5938. if (this._alphaBlend) {
  5939. gl.enable(gl.BLEND);
  5940. }
  5941. else {
  5942. gl.disable(gl.BLEND);
  5943. }
  5944. this._isAlphaBlendDirty = false;
  5945. }
  5946. // Alpha function
  5947. if (this._isBlendFunctionParametersDirty) {
  5948. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5949. this._isBlendFunctionParametersDirty = false;
  5950. }
  5951. };
  5952. return _AlphaState;
  5953. }());
  5954. Internals._AlphaState = _AlphaState;
  5955. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5956. })(BABYLON || (BABYLON = {}));
  5957. //# sourceMappingURL=../States/babylon.alphaCullingState.js.map
  5958. var BABYLON;
  5959. (function (BABYLON) {
  5960. var Internals;
  5961. (function (Internals) {
  5962. var _DepthCullingState = (function () {
  5963. /**
  5964. * Initializes the state.
  5965. */
  5966. function _DepthCullingState() {
  5967. this._isDepthTestDirty = false;
  5968. this._isDepthMaskDirty = false;
  5969. this._isDepthFuncDirty = false;
  5970. this._isCullFaceDirty = false;
  5971. this._isCullDirty = false;
  5972. this._isZOffsetDirty = false;
  5973. this.reset();
  5974. }
  5975. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5976. get: function () {
  5977. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5978. },
  5979. enumerable: true,
  5980. configurable: true
  5981. });
  5982. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5983. get: function () {
  5984. return this._zOffset;
  5985. },
  5986. set: function (value) {
  5987. if (this._zOffset === value) {
  5988. return;
  5989. }
  5990. this._zOffset = value;
  5991. this._isZOffsetDirty = true;
  5992. },
  5993. enumerable: true,
  5994. configurable: true
  5995. });
  5996. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5997. get: function () {
  5998. return this._cullFace;
  5999. },
  6000. set: function (value) {
  6001. if (this._cullFace === value) {
  6002. return;
  6003. }
  6004. this._cullFace = value;
  6005. this._isCullFaceDirty = true;
  6006. },
  6007. enumerable: true,
  6008. configurable: true
  6009. });
  6010. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6011. get: function () {
  6012. return this._cull;
  6013. },
  6014. set: function (value) {
  6015. if (this._cull === value) {
  6016. return;
  6017. }
  6018. this._cull = value;
  6019. this._isCullDirty = true;
  6020. },
  6021. enumerable: true,
  6022. configurable: true
  6023. });
  6024. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6025. get: function () {
  6026. return this._depthFunc;
  6027. },
  6028. set: function (value) {
  6029. if (this._depthFunc === value) {
  6030. return;
  6031. }
  6032. this._depthFunc = value;
  6033. this._isDepthFuncDirty = true;
  6034. },
  6035. enumerable: true,
  6036. configurable: true
  6037. });
  6038. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6039. get: function () {
  6040. return this._depthMask;
  6041. },
  6042. set: function (value) {
  6043. if (this._depthMask === value) {
  6044. return;
  6045. }
  6046. this._depthMask = value;
  6047. this._isDepthMaskDirty = true;
  6048. },
  6049. enumerable: true,
  6050. configurable: true
  6051. });
  6052. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6053. get: function () {
  6054. return this._depthTest;
  6055. },
  6056. set: function (value) {
  6057. if (this._depthTest === value) {
  6058. return;
  6059. }
  6060. this._depthTest = value;
  6061. this._isDepthTestDirty = true;
  6062. },
  6063. enumerable: true,
  6064. configurable: true
  6065. });
  6066. _DepthCullingState.prototype.reset = function () {
  6067. this._depthMask = true;
  6068. this._depthTest = true;
  6069. this._depthFunc = null;
  6070. this._cullFace = null;
  6071. this._cull = null;
  6072. this._zOffset = 0;
  6073. this._isDepthTestDirty = true;
  6074. this._isDepthMaskDirty = true;
  6075. this._isDepthFuncDirty = false;
  6076. this._isCullFaceDirty = false;
  6077. this._isCullDirty = false;
  6078. this._isZOffsetDirty = false;
  6079. };
  6080. _DepthCullingState.prototype.apply = function (gl) {
  6081. if (!this.isDirty) {
  6082. return;
  6083. }
  6084. // Cull
  6085. if (this._isCullDirty) {
  6086. if (this.cull) {
  6087. gl.enable(gl.CULL_FACE);
  6088. }
  6089. else {
  6090. gl.disable(gl.CULL_FACE);
  6091. }
  6092. this._isCullDirty = false;
  6093. }
  6094. // Cull face
  6095. if (this._isCullFaceDirty) {
  6096. gl.cullFace(this.cullFace);
  6097. this._isCullFaceDirty = false;
  6098. }
  6099. // Depth mask
  6100. if (this._isDepthMaskDirty) {
  6101. gl.depthMask(this.depthMask);
  6102. this._isDepthMaskDirty = false;
  6103. }
  6104. // Depth test
  6105. if (this._isDepthTestDirty) {
  6106. if (this.depthTest) {
  6107. gl.enable(gl.DEPTH_TEST);
  6108. }
  6109. else {
  6110. gl.disable(gl.DEPTH_TEST);
  6111. }
  6112. this._isDepthTestDirty = false;
  6113. }
  6114. // Depth func
  6115. if (this._isDepthFuncDirty) {
  6116. gl.depthFunc(this.depthFunc);
  6117. this._isDepthFuncDirty = false;
  6118. }
  6119. // zOffset
  6120. if (this._isZOffsetDirty) {
  6121. if (this.zOffset) {
  6122. gl.enable(gl.POLYGON_OFFSET_FILL);
  6123. gl.polygonOffset(this.zOffset, 0);
  6124. }
  6125. else {
  6126. gl.disable(gl.POLYGON_OFFSET_FILL);
  6127. }
  6128. this._isZOffsetDirty = false;
  6129. }
  6130. };
  6131. return _DepthCullingState;
  6132. }());
  6133. Internals._DepthCullingState = _DepthCullingState;
  6134. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6135. })(BABYLON || (BABYLON = {}));
  6136. //# sourceMappingURL=../States/babylon.depthCullingState.js.map
  6137. var BABYLON;
  6138. (function (BABYLON) {
  6139. var Internals;
  6140. (function (Internals) {
  6141. var _StencilState = (function () {
  6142. function _StencilState() {
  6143. this._isStencilTestDirty = false;
  6144. this._isStencilMaskDirty = false;
  6145. this._isStencilFuncDirty = false;
  6146. this._isStencilOpDirty = false;
  6147. this.reset();
  6148. }
  6149. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6150. get: function () {
  6151. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6152. },
  6153. enumerable: true,
  6154. configurable: true
  6155. });
  6156. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6157. get: function () {
  6158. return this._stencilFunc;
  6159. },
  6160. set: function (value) {
  6161. if (this._stencilFunc === value) {
  6162. return;
  6163. }
  6164. this._stencilFunc = value;
  6165. this._isStencilFuncDirty = true;
  6166. },
  6167. enumerable: true,
  6168. configurable: true
  6169. });
  6170. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6171. get: function () {
  6172. return this._stencilFuncRef;
  6173. },
  6174. set: function (value) {
  6175. if (this._stencilFuncRef === value) {
  6176. return;
  6177. }
  6178. this._stencilFuncRef = value;
  6179. this._isStencilFuncDirty = true;
  6180. },
  6181. enumerable: true,
  6182. configurable: true
  6183. });
  6184. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6185. get: function () {
  6186. return this._stencilFuncMask;
  6187. },
  6188. set: function (value) {
  6189. if (this._stencilFuncMask === value) {
  6190. return;
  6191. }
  6192. this._stencilFuncMask = value;
  6193. this._isStencilFuncDirty = true;
  6194. },
  6195. enumerable: true,
  6196. configurable: true
  6197. });
  6198. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6199. get: function () {
  6200. return this._stencilOpStencilFail;
  6201. },
  6202. set: function (value) {
  6203. if (this._stencilOpStencilFail === value) {
  6204. return;
  6205. }
  6206. this._stencilOpStencilFail = value;
  6207. this._isStencilOpDirty = true;
  6208. },
  6209. enumerable: true,
  6210. configurable: true
  6211. });
  6212. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6213. get: function () {
  6214. return this._stencilOpDepthFail;
  6215. },
  6216. set: function (value) {
  6217. if (this._stencilOpDepthFail === value) {
  6218. return;
  6219. }
  6220. this._stencilOpDepthFail = value;
  6221. this._isStencilOpDirty = true;
  6222. },
  6223. enumerable: true,
  6224. configurable: true
  6225. });
  6226. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6227. get: function () {
  6228. return this._stencilOpStencilDepthPass;
  6229. },
  6230. set: function (value) {
  6231. if (this._stencilOpStencilDepthPass === value) {
  6232. return;
  6233. }
  6234. this._stencilOpStencilDepthPass = value;
  6235. this._isStencilOpDirty = true;
  6236. },
  6237. enumerable: true,
  6238. configurable: true
  6239. });
  6240. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6241. get: function () {
  6242. return this._stencilMask;
  6243. },
  6244. set: function (value) {
  6245. if (this._stencilMask === value) {
  6246. return;
  6247. }
  6248. this._stencilMask = value;
  6249. this._isStencilMaskDirty = true;
  6250. },
  6251. enumerable: true,
  6252. configurable: true
  6253. });
  6254. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6255. get: function () {
  6256. return this._stencilTest;
  6257. },
  6258. set: function (value) {
  6259. if (this._stencilTest === value) {
  6260. return;
  6261. }
  6262. this._stencilTest = value;
  6263. this._isStencilTestDirty = true;
  6264. },
  6265. enumerable: true,
  6266. configurable: true
  6267. });
  6268. _StencilState.prototype.reset = function () {
  6269. this._stencilTest = false;
  6270. this._stencilMask = 0xFF;
  6271. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6272. this._stencilFuncRef = 1;
  6273. this._stencilFuncMask = 0xFF;
  6274. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6275. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6276. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6277. this._isStencilTestDirty = true;
  6278. this._isStencilMaskDirty = true;
  6279. this._isStencilFuncDirty = true;
  6280. this._isStencilOpDirty = true;
  6281. };
  6282. _StencilState.prototype.apply = function (gl) {
  6283. if (!this.isDirty) {
  6284. return;
  6285. }
  6286. // Stencil test
  6287. if (this._isStencilTestDirty) {
  6288. if (this.stencilTest) {
  6289. gl.enable(gl.STENCIL_TEST);
  6290. }
  6291. else {
  6292. gl.disable(gl.STENCIL_TEST);
  6293. }
  6294. this._isStencilTestDirty = false;
  6295. }
  6296. // Stencil mask
  6297. if (this._isStencilMaskDirty) {
  6298. gl.stencilMask(this.stencilMask);
  6299. this._isStencilMaskDirty = false;
  6300. }
  6301. // Stencil func
  6302. if (this._isStencilFuncDirty) {
  6303. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6304. this._isStencilFuncDirty = false;
  6305. }
  6306. // Stencil op
  6307. if (this._isStencilOpDirty) {
  6308. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6309. this._isStencilOpDirty = false;
  6310. }
  6311. };
  6312. return _StencilState;
  6313. }());
  6314. Internals._StencilState = _StencilState;
  6315. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6316. })(BABYLON || (BABYLON = {}));
  6317. //# sourceMappingURL=../States/babylon.stencilState.js.map
  6318. var BABYLON;
  6319. (function (BABYLON) {
  6320. var compileShader = function (gl, source, type, defines) {
  6321. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6322. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6323. gl.compileShader(shader);
  6324. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6325. throw new Error(gl.getShaderInfoLog(shader));
  6326. }
  6327. return shader;
  6328. };
  6329. var HALF_FLOAT_OES = 0x8D61;
  6330. var getWebGLTextureType = function (gl, type) {
  6331. if (type === Engine.TEXTURETYPE_FLOAT) {
  6332. return gl.FLOAT;
  6333. }
  6334. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6335. // Add Half Float Constant.
  6336. return HALF_FLOAT_OES;
  6337. }
  6338. return gl.UNSIGNED_BYTE;
  6339. };
  6340. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6341. var magFilter = gl.NEAREST;
  6342. var minFilter = gl.NEAREST;
  6343. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6344. magFilter = gl.LINEAR;
  6345. if (generateMipMaps) {
  6346. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6347. }
  6348. else {
  6349. minFilter = gl.LINEAR;
  6350. }
  6351. }
  6352. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6353. magFilter = gl.LINEAR;
  6354. if (generateMipMaps) {
  6355. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6356. }
  6357. else {
  6358. minFilter = gl.LINEAR;
  6359. }
  6360. }
  6361. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6362. magFilter = gl.NEAREST;
  6363. if (generateMipMaps) {
  6364. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6365. }
  6366. else {
  6367. minFilter = gl.NEAREST;
  6368. }
  6369. }
  6370. return {
  6371. min: minFilter,
  6372. mag: magFilter
  6373. };
  6374. };
  6375. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6376. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6377. var engine = scene.getEngine();
  6378. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6379. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6380. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6381. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6382. texture._baseWidth = width;
  6383. texture._baseHeight = height;
  6384. texture._width = potWidth;
  6385. texture._height = potHeight;
  6386. texture.isReady = true;
  6387. processFunction(potWidth, potHeight);
  6388. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6389. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6390. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6391. if (!noMipmap && !isCompressed) {
  6392. gl.generateMipmap(gl.TEXTURE_2D);
  6393. }
  6394. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6395. engine.resetTextureCache();
  6396. scene._removePendingData(texture);
  6397. texture.onLoadedCallbacks.forEach(function (callback) {
  6398. callback();
  6399. });
  6400. texture.onLoadedCallbacks = [];
  6401. };
  6402. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6403. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6404. var img;
  6405. var onload = function () {
  6406. loadedImages[index] = img;
  6407. loadedImages._internalCount++;
  6408. scene._removePendingData(img);
  6409. if (loadedImages._internalCount === 6) {
  6410. onfinish(loadedImages);
  6411. }
  6412. };
  6413. var onerror = function () {
  6414. scene._removePendingData(img);
  6415. if (onErrorCallBack) {
  6416. onErrorCallBack();
  6417. }
  6418. };
  6419. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6420. scene._addPendingData(img);
  6421. };
  6422. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6423. if (onError === void 0) { onError = null; }
  6424. var loadedImages = [];
  6425. loadedImages._internalCount = 0;
  6426. for (var index = 0; index < 6; index++) {
  6427. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6428. }
  6429. };
  6430. var InstancingAttributeInfo = (function () {
  6431. function InstancingAttributeInfo() {
  6432. }
  6433. return InstancingAttributeInfo;
  6434. }());
  6435. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6436. var EngineCapabilities = (function () {
  6437. function EngineCapabilities() {
  6438. }
  6439. return EngineCapabilities;
  6440. }());
  6441. BABYLON.EngineCapabilities = EngineCapabilities;
  6442. /**
  6443. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6444. */
  6445. var Engine = (function () {
  6446. /**
  6447. * @constructor
  6448. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6449. * @param {boolean} [antialias] - enable antialias
  6450. * @param options - further options to be sent to the getContext function
  6451. */
  6452. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6453. var _this = this;
  6454. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6455. // Public members
  6456. this.isFullscreen = false;
  6457. this.isPointerLock = false;
  6458. this.cullBackFaces = true;
  6459. this.renderEvenInBackground = true;
  6460. // To enable/disable IDB support and avoid XHR on .manifest
  6461. this.enableOfflineSupport = true;
  6462. this.scenes = new Array();
  6463. this._windowIsBackground = false;
  6464. this._webGLVersion = "1.0";
  6465. this._badOS = false;
  6466. this._drawCalls = new BABYLON.PerfCounter();
  6467. this._renderingQueueLaunched = false;
  6468. this._activeRenderLoops = [];
  6469. // FPS
  6470. this.fpsRange = 60;
  6471. this.previousFramesDuration = [];
  6472. this.fps = 60;
  6473. this.deltaTime = 0;
  6474. // States
  6475. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6476. this._stencilState = new BABYLON.Internals._StencilState();
  6477. this._alphaState = new BABYLON.Internals._AlphaState();
  6478. this._alphaMode = Engine.ALPHA_DISABLE;
  6479. // Cache
  6480. this._loadedTexturesCache = new Array();
  6481. this._maxTextureChannels = 16;
  6482. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6483. this._compiledEffects = {};
  6484. this._vertexAttribArraysEnabled = [];
  6485. this._uintIndicesCurrentlySet = false;
  6486. this._currentBoundBuffer = new Array();
  6487. this._currentBufferPointers = [];
  6488. this._currentInstanceLocations = new Array();
  6489. this._currentInstanceBuffers = new Array();
  6490. this._onVRFullScreenTriggered = function () {
  6491. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6492. //get the old size before we change
  6493. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6494. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6495. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6496. //But actually, no browser follow the specs...
  6497. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6498. //get the width and height, change the render size
  6499. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6500. var width, height;
  6501. _this.setHardwareScalingLevel(1);
  6502. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6503. }
  6504. else {
  6505. //When the specs are implemented, need to uncomment this.
  6506. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6507. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6508. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6509. _this._vrDisplayEnabled = undefined;
  6510. }
  6511. };
  6512. this._renderingCanvas = canvas;
  6513. this._externalData = new BABYLON.StringDictionary();
  6514. options = options || {};
  6515. if (antialias != null) {
  6516. options.antialias = antialias;
  6517. }
  6518. if (options.preserveDrawingBuffer === undefined) {
  6519. options.preserveDrawingBuffer = false;
  6520. }
  6521. // Checks if some of the format renders first to allow the use of webgl inspector.
  6522. var renderToFullFloat = this._canRenderToFloatTexture();
  6523. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6524. // GL
  6525. //try {
  6526. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6527. // if (this._gl) {
  6528. // this._webGLVersion = "2.0";
  6529. // }
  6530. //} catch (e) {
  6531. // // Do nothing
  6532. //}
  6533. if (!this._gl) {
  6534. if (!canvas) {
  6535. throw new Error("The provided canvas is null or undefined.");
  6536. }
  6537. try {
  6538. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6539. }
  6540. catch (e) {
  6541. throw new Error("WebGL not supported");
  6542. }
  6543. }
  6544. if (!this._gl) {
  6545. throw new Error("WebGL not supported");
  6546. }
  6547. this._onBlur = function () {
  6548. _this._windowIsBackground = true;
  6549. };
  6550. this._onFocus = function () {
  6551. _this._windowIsBackground = false;
  6552. };
  6553. window.addEventListener("blur", this._onBlur);
  6554. window.addEventListener("focus", this._onFocus);
  6555. // Viewport
  6556. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6557. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6558. this.resize();
  6559. // Caps
  6560. this._isStencilEnable = options.stencil;
  6561. this._caps = new EngineCapabilities();
  6562. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6563. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6564. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6565. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6566. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6567. // Infos
  6568. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6569. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6570. if (rendererInfo != null) {
  6571. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6572. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6573. }
  6574. if (!this._glVendor) {
  6575. this._glVendor = "Unknown vendor";
  6576. }
  6577. if (!this._glRenderer) {
  6578. this._glRenderer = "Unknown renderer";
  6579. }
  6580. // Extensions
  6581. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6582. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6583. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6584. 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');
  6585. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6586. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6587. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6588. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6589. this._caps.highPrecisionShaderSupported = true;
  6590. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6591. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6592. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6593. this._caps.textureFloatRender = renderToFullFloat;
  6594. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6595. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6596. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6597. if (this._gl.getShaderPrecisionFormat) {
  6598. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6599. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6600. }
  6601. // Depth buffer
  6602. this.setDepthBuffer(true);
  6603. this.setDepthFunctionToLessOrEqual();
  6604. this.setDepthWrite(true);
  6605. // Fullscreen
  6606. this._onFullscreenChange = function () {
  6607. if (document.fullscreen !== undefined) {
  6608. _this.isFullscreen = document.fullscreen;
  6609. }
  6610. else if (document.mozFullScreen !== undefined) {
  6611. _this.isFullscreen = document.mozFullScreen;
  6612. }
  6613. else if (document.webkitIsFullScreen !== undefined) {
  6614. _this.isFullscreen = document.webkitIsFullScreen;
  6615. }
  6616. else if (document.msIsFullScreen !== undefined) {
  6617. _this.isFullscreen = document.msIsFullScreen;
  6618. }
  6619. // Pointer lock
  6620. if (_this.isFullscreen && _this._pointerLockRequested) {
  6621. canvas.requestPointerLock = canvas.requestPointerLock ||
  6622. canvas.msRequestPointerLock ||
  6623. canvas.mozRequestPointerLock ||
  6624. canvas.webkitRequestPointerLock;
  6625. if (canvas.requestPointerLock) {
  6626. canvas.requestPointerLock();
  6627. }
  6628. }
  6629. };
  6630. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6631. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6632. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6633. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6634. // Pointer lock
  6635. this._onPointerLockChange = function () {
  6636. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6637. document.webkitPointerLockElement === canvas ||
  6638. document.msPointerLockElement === canvas ||
  6639. document.pointerLockElement === canvas);
  6640. };
  6641. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6642. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6643. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6644. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6645. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6646. Engine.audioEngine = new BABYLON.AudioEngine();
  6647. }
  6648. //default loading screen
  6649. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6650. //Load WebVR Devices
  6651. if (options.autoEnableWebVR) {
  6652. this.initWebVR();
  6653. }
  6654. //Detect if we are running on a faulty buggy OS.
  6655. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6656. //ua sniffing is the tool of the devil.
  6657. this._badOS = regexp.test(navigator.userAgent);
  6658. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6659. }
  6660. Object.defineProperty(Engine, "NEVER", {
  6661. get: function () {
  6662. return Engine._NEVER;
  6663. },
  6664. enumerable: true,
  6665. configurable: true
  6666. });
  6667. Object.defineProperty(Engine, "ALWAYS", {
  6668. get: function () {
  6669. return Engine._ALWAYS;
  6670. },
  6671. enumerable: true,
  6672. configurable: true
  6673. });
  6674. Object.defineProperty(Engine, "LESS", {
  6675. get: function () {
  6676. return Engine._LESS;
  6677. },
  6678. enumerable: true,
  6679. configurable: true
  6680. });
  6681. Object.defineProperty(Engine, "EQUAL", {
  6682. get: function () {
  6683. return Engine._EQUAL;
  6684. },
  6685. enumerable: true,
  6686. configurable: true
  6687. });
  6688. Object.defineProperty(Engine, "LEQUAL", {
  6689. get: function () {
  6690. return Engine._LEQUAL;
  6691. },
  6692. enumerable: true,
  6693. configurable: true
  6694. });
  6695. Object.defineProperty(Engine, "GREATER", {
  6696. get: function () {
  6697. return Engine._GREATER;
  6698. },
  6699. enumerable: true,
  6700. configurable: true
  6701. });
  6702. Object.defineProperty(Engine, "GEQUAL", {
  6703. get: function () {
  6704. return Engine._GEQUAL;
  6705. },
  6706. enumerable: true,
  6707. configurable: true
  6708. });
  6709. Object.defineProperty(Engine, "NOTEQUAL", {
  6710. get: function () {
  6711. return Engine._NOTEQUAL;
  6712. },
  6713. enumerable: true,
  6714. configurable: true
  6715. });
  6716. Object.defineProperty(Engine, "KEEP", {
  6717. get: function () {
  6718. return Engine._KEEP;
  6719. },
  6720. enumerable: true,
  6721. configurable: true
  6722. });
  6723. Object.defineProperty(Engine, "REPLACE", {
  6724. get: function () {
  6725. return Engine._REPLACE;
  6726. },
  6727. enumerable: true,
  6728. configurable: true
  6729. });
  6730. Object.defineProperty(Engine, "INCR", {
  6731. get: function () {
  6732. return Engine._INCR;
  6733. },
  6734. enumerable: true,
  6735. configurable: true
  6736. });
  6737. Object.defineProperty(Engine, "DECR", {
  6738. get: function () {
  6739. return Engine._DECR;
  6740. },
  6741. enumerable: true,
  6742. configurable: true
  6743. });
  6744. Object.defineProperty(Engine, "INVERT", {
  6745. get: function () {
  6746. return Engine._INVERT;
  6747. },
  6748. enumerable: true,
  6749. configurable: true
  6750. });
  6751. Object.defineProperty(Engine, "INCR_WRAP", {
  6752. get: function () {
  6753. return Engine._INCR_WRAP;
  6754. },
  6755. enumerable: true,
  6756. configurable: true
  6757. });
  6758. Object.defineProperty(Engine, "DECR_WRAP", {
  6759. get: function () {
  6760. return Engine._DECR_WRAP;
  6761. },
  6762. enumerable: true,
  6763. configurable: true
  6764. });
  6765. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6766. get: function () {
  6767. return Engine._ALPHA_DISABLE;
  6768. },
  6769. enumerable: true,
  6770. configurable: true
  6771. });
  6772. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6773. get: function () {
  6774. return Engine._ALPHA_ONEONE;
  6775. },
  6776. enumerable: true,
  6777. configurable: true
  6778. });
  6779. Object.defineProperty(Engine, "ALPHA_ADD", {
  6780. get: function () {
  6781. return Engine._ALPHA_ADD;
  6782. },
  6783. enumerable: true,
  6784. configurable: true
  6785. });
  6786. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6787. get: function () {
  6788. return Engine._ALPHA_COMBINE;
  6789. },
  6790. enumerable: true,
  6791. configurable: true
  6792. });
  6793. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6794. get: function () {
  6795. return Engine._ALPHA_SUBTRACT;
  6796. },
  6797. enumerable: true,
  6798. configurable: true
  6799. });
  6800. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6801. get: function () {
  6802. return Engine._ALPHA_MULTIPLY;
  6803. },
  6804. enumerable: true,
  6805. configurable: true
  6806. });
  6807. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6808. get: function () {
  6809. return Engine._ALPHA_MAXIMIZED;
  6810. },
  6811. enumerable: true,
  6812. configurable: true
  6813. });
  6814. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6815. get: function () {
  6816. return Engine._DELAYLOADSTATE_NONE;
  6817. },
  6818. enumerable: true,
  6819. configurable: true
  6820. });
  6821. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6822. get: function () {
  6823. return Engine._DELAYLOADSTATE_LOADED;
  6824. },
  6825. enumerable: true,
  6826. configurable: true
  6827. });
  6828. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6829. get: function () {
  6830. return Engine._DELAYLOADSTATE_LOADING;
  6831. },
  6832. enumerable: true,
  6833. configurable: true
  6834. });
  6835. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6836. get: function () {
  6837. return Engine._DELAYLOADSTATE_NOTLOADED;
  6838. },
  6839. enumerable: true,
  6840. configurable: true
  6841. });
  6842. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6843. get: function () {
  6844. return Engine._TEXTUREFORMAT_ALPHA;
  6845. },
  6846. enumerable: true,
  6847. configurable: true
  6848. });
  6849. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6850. get: function () {
  6851. return Engine._TEXTUREFORMAT_LUMINANCE;
  6852. },
  6853. enumerable: true,
  6854. configurable: true
  6855. });
  6856. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6857. get: function () {
  6858. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6859. },
  6860. enumerable: true,
  6861. configurable: true
  6862. });
  6863. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6864. get: function () {
  6865. return Engine._TEXTUREFORMAT_RGB;
  6866. },
  6867. enumerable: true,
  6868. configurable: true
  6869. });
  6870. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6871. get: function () {
  6872. return Engine._TEXTUREFORMAT_RGBA;
  6873. },
  6874. enumerable: true,
  6875. configurable: true
  6876. });
  6877. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6878. get: function () {
  6879. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6880. },
  6881. enumerable: true,
  6882. configurable: true
  6883. });
  6884. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6885. get: function () {
  6886. return Engine._TEXTURETYPE_FLOAT;
  6887. },
  6888. enumerable: true,
  6889. configurable: true
  6890. });
  6891. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6892. get: function () {
  6893. return Engine._TEXTURETYPE_HALF_FLOAT;
  6894. },
  6895. enumerable: true,
  6896. configurable: true
  6897. });
  6898. Object.defineProperty(Engine, "Version", {
  6899. get: function () {
  6900. return "2.5.-beta";
  6901. },
  6902. enumerable: true,
  6903. configurable: true
  6904. });
  6905. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6906. get: function () {
  6907. return this._webGLVersion;
  6908. },
  6909. enumerable: true,
  6910. configurable: true
  6911. });
  6912. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  6913. /**
  6914. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  6915. */
  6916. get: function () {
  6917. return this._isStencilEnable;
  6918. },
  6919. enumerable: true,
  6920. configurable: true
  6921. });
  6922. Engine.prototype._prepareWorkingCanvas = function () {
  6923. if (this._workingCanvas) {
  6924. return;
  6925. }
  6926. this._workingCanvas = document.createElement("canvas");
  6927. this._workingContext = this._workingCanvas.getContext("2d");
  6928. };
  6929. Engine.prototype.resetTextureCache = function () {
  6930. for (var index = 0; index < this._maxTextureChannels; index++) {
  6931. this._activeTexturesCache[index] = null;
  6932. }
  6933. };
  6934. Engine.prototype.getGlInfo = function () {
  6935. return {
  6936. vendor: this._glVendor,
  6937. renderer: this._glRenderer,
  6938. version: this._glVersion
  6939. };
  6940. };
  6941. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6942. if (useScreen === void 0) { useScreen = false; }
  6943. var viewport = camera.viewport;
  6944. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6945. };
  6946. Engine.prototype.getRenderWidth = function (useScreen) {
  6947. if (useScreen === void 0) { useScreen = false; }
  6948. if (!useScreen && this._currentRenderTarget) {
  6949. return this._currentRenderTarget._width;
  6950. }
  6951. return this._renderingCanvas.width;
  6952. };
  6953. Engine.prototype.getRenderHeight = function (useScreen) {
  6954. if (useScreen === void 0) { useScreen = false; }
  6955. if (!useScreen && this._currentRenderTarget) {
  6956. return this._currentRenderTarget._height;
  6957. }
  6958. return this._renderingCanvas.height;
  6959. };
  6960. Engine.prototype.getRenderingCanvas = function () {
  6961. return this._renderingCanvas;
  6962. };
  6963. Engine.prototype.getRenderingCanvasClientRect = function () {
  6964. return this._renderingCanvas.getBoundingClientRect();
  6965. };
  6966. Engine.prototype.setHardwareScalingLevel = function (level) {
  6967. this._hardwareScalingLevel = level;
  6968. this.resize();
  6969. };
  6970. Engine.prototype.getHardwareScalingLevel = function () {
  6971. return this._hardwareScalingLevel;
  6972. };
  6973. Engine.prototype.getLoadedTexturesCache = function () {
  6974. return this._loadedTexturesCache;
  6975. };
  6976. Engine.prototype.getCaps = function () {
  6977. return this._caps;
  6978. };
  6979. Object.defineProperty(Engine.prototype, "drawCalls", {
  6980. get: function () {
  6981. return this._drawCalls.current;
  6982. },
  6983. enumerable: true,
  6984. configurable: true
  6985. });
  6986. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6987. get: function () {
  6988. return this._drawCalls;
  6989. },
  6990. enumerable: true,
  6991. configurable: true
  6992. });
  6993. Engine.prototype.getDepthFunction = function () {
  6994. return this._depthCullingState.depthFunc;
  6995. };
  6996. Engine.prototype.setDepthFunction = function (depthFunc) {
  6997. this._depthCullingState.depthFunc = depthFunc;
  6998. };
  6999. Engine.prototype.setDepthFunctionToGreater = function () {
  7000. this._depthCullingState.depthFunc = this._gl.GREATER;
  7001. };
  7002. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7003. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7004. };
  7005. Engine.prototype.setDepthFunctionToLess = function () {
  7006. this._depthCullingState.depthFunc = this._gl.LESS;
  7007. };
  7008. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7009. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7010. };
  7011. Engine.prototype.getStencilBuffer = function () {
  7012. return this._stencilState.stencilTest;
  7013. };
  7014. Engine.prototype.setStencilBuffer = function (enable) {
  7015. this._stencilState.stencilTest = enable;
  7016. };
  7017. Engine.prototype.getStencilMask = function () {
  7018. return this._stencilState.stencilMask;
  7019. };
  7020. Engine.prototype.setStencilMask = function (mask) {
  7021. this._stencilState.stencilMask = mask;
  7022. };
  7023. Engine.prototype.getStencilFunction = function () {
  7024. return this._stencilState.stencilFunc;
  7025. };
  7026. Engine.prototype.getStencilFunctionReference = function () {
  7027. return this._stencilState.stencilFuncRef;
  7028. };
  7029. Engine.prototype.getStencilFunctionMask = function () {
  7030. return this._stencilState.stencilFuncMask;
  7031. };
  7032. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7033. this._stencilState.stencilFunc = stencilFunc;
  7034. };
  7035. Engine.prototype.setStencilFunctionReference = function (reference) {
  7036. this._stencilState.stencilFuncRef = reference;
  7037. };
  7038. Engine.prototype.setStencilFunctionMask = function (mask) {
  7039. this._stencilState.stencilFuncMask = mask;
  7040. };
  7041. Engine.prototype.getStencilOperationFail = function () {
  7042. return this._stencilState.stencilOpStencilFail;
  7043. };
  7044. Engine.prototype.getStencilOperationDepthFail = function () {
  7045. return this._stencilState.stencilOpDepthFail;
  7046. };
  7047. Engine.prototype.getStencilOperationPass = function () {
  7048. return this._stencilState.stencilOpStencilDepthPass;
  7049. };
  7050. Engine.prototype.setStencilOperationFail = function (operation) {
  7051. this._stencilState.stencilOpStencilFail = operation;
  7052. };
  7053. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7054. this._stencilState.stencilOpDepthFail = operation;
  7055. };
  7056. Engine.prototype.setStencilOperationPass = function (operation) {
  7057. this._stencilState.stencilOpStencilDepthPass = operation;
  7058. };
  7059. /**
  7060. * stop executing a render loop function and remove it from the execution array
  7061. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7062. */
  7063. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7064. if (!renderFunction) {
  7065. this._activeRenderLoops = [];
  7066. return;
  7067. }
  7068. var index = this._activeRenderLoops.indexOf(renderFunction);
  7069. if (index >= 0) {
  7070. this._activeRenderLoops.splice(index, 1);
  7071. }
  7072. };
  7073. Engine.prototype._renderLoop = function () {
  7074. var shouldRender = true;
  7075. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7076. shouldRender = false;
  7077. }
  7078. if (shouldRender) {
  7079. // Start new frame
  7080. this.beginFrame();
  7081. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7082. var renderFunction = this._activeRenderLoops[index];
  7083. renderFunction();
  7084. }
  7085. // Present
  7086. this.endFrame();
  7087. }
  7088. if (this._activeRenderLoops.length > 0) {
  7089. // Register new frame
  7090. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7091. }
  7092. else {
  7093. this._renderingQueueLaunched = false;
  7094. }
  7095. };
  7096. /**
  7097. * Register and execute a render loop. The engine can have more than one render function.
  7098. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7099. * @example
  7100. * engine.runRenderLoop(function () {
  7101. * scene.render()
  7102. * })
  7103. */
  7104. Engine.prototype.runRenderLoop = function (renderFunction) {
  7105. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7106. return;
  7107. }
  7108. this._activeRenderLoops.push(renderFunction);
  7109. if (!this._renderingQueueLaunched) {
  7110. this._renderingQueueLaunched = true;
  7111. this._bindedRenderFunction = this._renderLoop.bind(this);
  7112. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7113. }
  7114. };
  7115. /**
  7116. * Toggle full screen mode.
  7117. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7118. * @param {any} options - an options object to be sent to the requestFullscreen function
  7119. */
  7120. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7121. if (this.isFullscreen) {
  7122. BABYLON.Tools.ExitFullscreen();
  7123. }
  7124. else {
  7125. this._pointerLockRequested = requestPointerLock;
  7126. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7127. }
  7128. };
  7129. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7130. if (stencil === void 0) { stencil = false; }
  7131. this.applyStates();
  7132. var mode = 0;
  7133. if (backBuffer) {
  7134. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7135. mode |= this._gl.COLOR_BUFFER_BIT;
  7136. }
  7137. if (depth) {
  7138. this._gl.clearDepth(1.0);
  7139. mode |= this._gl.DEPTH_BUFFER_BIT;
  7140. }
  7141. if (stencil) {
  7142. this._gl.clearStencil(0);
  7143. mode |= this._gl.STENCIL_BUFFER_BIT;
  7144. }
  7145. this._gl.clear(mode);
  7146. };
  7147. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7148. var gl = this._gl;
  7149. // Save state
  7150. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7151. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7152. // Change state
  7153. gl.enable(gl.SCISSOR_TEST);
  7154. gl.scissor(x, y, width, height);
  7155. // Clear
  7156. this.clear(clearColor, true, true, true);
  7157. // Restore state
  7158. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7159. if (curScissor === true) {
  7160. gl.enable(gl.SCISSOR_TEST);
  7161. }
  7162. else {
  7163. gl.disable(gl.SCISSOR_TEST);
  7164. }
  7165. };
  7166. /**
  7167. * Set the WebGL's viewport
  7168. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7169. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7170. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7171. */
  7172. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7173. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  7174. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  7175. var x = viewport.x || 0;
  7176. var y = viewport.y || 0;
  7177. this._cachedViewport = viewport;
  7178. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7179. };
  7180. /**
  7181. * Directly set the WebGL Viewport
  7182. * The x, y, width & height are directly passed to the WebGL call
  7183. * @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.
  7184. */
  7185. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7186. var currentViewport = this._cachedViewport;
  7187. this._cachedViewport = null;
  7188. this._gl.viewport(x, y, width, height);
  7189. return currentViewport;
  7190. };
  7191. Engine.prototype.beginFrame = function () {
  7192. this._measureFps();
  7193. };
  7194. Engine.prototype.endFrame = function () {
  7195. //force a flush in case we are using a bad OS.
  7196. if (this._badOS) {
  7197. this.flushFramebuffer();
  7198. }
  7199. //submit frame to the vr device, if enabled
  7200. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7201. this._vrDisplayEnabled.submitFrame();
  7202. }
  7203. };
  7204. /**
  7205. * resize the view according to the canvas' size.
  7206. * @example
  7207. * window.addEventListener("resize", function () {
  7208. * engine.resize();
  7209. * });
  7210. */
  7211. Engine.prototype.resize = function () {
  7212. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7213. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7214. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7215. for (var index = 0; index < this.scenes.length; index++) {
  7216. var scene = this.scenes[index];
  7217. if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
  7218. scene.debugLayer._syncPositions();
  7219. }
  7220. }
  7221. };
  7222. /**
  7223. * force a specific size of the canvas
  7224. * @param {number} width - the new canvas' width
  7225. * @param {number} height - the new canvas' height
  7226. */
  7227. Engine.prototype.setSize = function (width, height) {
  7228. this._renderingCanvas.width = width;
  7229. this._renderingCanvas.height = height;
  7230. for (var index = 0; index < this.scenes.length; index++) {
  7231. var scene = this.scenes[index];
  7232. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7233. var cam = scene.cameras[camIndex];
  7234. cam._currentRenderId = 0;
  7235. }
  7236. }
  7237. };
  7238. //WebVR functions
  7239. Engine.prototype.initWebVR = function () {
  7240. if (!this.vrDisplaysPromise) {
  7241. this._getVRDisplays();
  7242. }
  7243. };
  7244. Engine.prototype.enableVR = function (vrDevice) {
  7245. this._vrDisplayEnabled = vrDevice;
  7246. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7247. };
  7248. Engine.prototype.disableVR = function () {
  7249. if (this._vrDisplayEnabled) {
  7250. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7251. }
  7252. };
  7253. Engine.prototype._getVRDisplays = function () {
  7254. var _this = this;
  7255. var getWebVRDevices = function (devices) {
  7256. var size = devices.length;
  7257. var i = 0;
  7258. _this._vrDisplays = devices.filter(function (device) {
  7259. return devices[i] instanceof VRDisplay;
  7260. });
  7261. return _this._vrDisplays;
  7262. };
  7263. //using a key due to typescript
  7264. if (navigator.getVRDisplays) {
  7265. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7266. }
  7267. };
  7268. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7269. this._currentRenderTarget = texture;
  7270. this.bindUnboundFramebuffer(texture._framebuffer);
  7271. var gl = this._gl;
  7272. if (texture.isCube) {
  7273. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7274. }
  7275. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7276. this.wipeCaches();
  7277. };
  7278. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7279. if (this._currentFramebuffer !== framebuffer) {
  7280. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7281. this._currentFramebuffer = framebuffer;
  7282. }
  7283. };
  7284. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7285. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7286. this._currentRenderTarget = null;
  7287. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7288. var gl = this._gl;
  7289. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7290. gl.generateMipmap(gl.TEXTURE_2D);
  7291. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7292. }
  7293. this.bindUnboundFramebuffer(null);
  7294. };
  7295. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7296. if (texture.generateMipMaps) {
  7297. var gl = this._gl;
  7298. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7299. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7300. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7301. }
  7302. };
  7303. Engine.prototype.flushFramebuffer = function () {
  7304. this._gl.flush();
  7305. };
  7306. Engine.prototype.restoreDefaultFramebuffer = function () {
  7307. this._currentRenderTarget = null;
  7308. this.bindUnboundFramebuffer(null);
  7309. this.setViewport(this._cachedViewport);
  7310. this.wipeCaches();
  7311. };
  7312. // VBOs
  7313. Engine.prototype._resetVertexBufferBinding = function () {
  7314. this.bindArrayBuffer(null);
  7315. this._cachedVertexBuffers = null;
  7316. };
  7317. Engine.prototype.createVertexBuffer = function (vertices) {
  7318. var vbo = this._gl.createBuffer();
  7319. this.bindArrayBuffer(vbo);
  7320. if (vertices instanceof Float32Array) {
  7321. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7322. }
  7323. else {
  7324. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7325. }
  7326. this._resetVertexBufferBinding();
  7327. vbo.references = 1;
  7328. return vbo;
  7329. };
  7330. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7331. var vbo = this._gl.createBuffer();
  7332. this.bindArrayBuffer(vbo);
  7333. if (vertices instanceof Float32Array) {
  7334. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7335. }
  7336. else {
  7337. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7338. }
  7339. this._resetVertexBufferBinding();
  7340. vbo.references = 1;
  7341. return vbo;
  7342. };
  7343. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7344. this.bindArrayBuffer(vertexBuffer);
  7345. if (offset === undefined) {
  7346. offset = 0;
  7347. }
  7348. if (count === undefined) {
  7349. if (vertices instanceof Float32Array) {
  7350. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7351. }
  7352. else {
  7353. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7354. }
  7355. }
  7356. else {
  7357. if (vertices instanceof Float32Array) {
  7358. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7359. }
  7360. else {
  7361. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7362. }
  7363. }
  7364. this._resetVertexBufferBinding();
  7365. };
  7366. Engine.prototype._resetIndexBufferBinding = function () {
  7367. this.bindIndexBuffer(null);
  7368. this._cachedIndexBuffer = null;
  7369. };
  7370. Engine.prototype.createIndexBuffer = function (indices) {
  7371. var vbo = this._gl.createBuffer();
  7372. this.bindIndexBuffer(vbo);
  7373. // Check for 32 bits indices
  7374. var arrayBuffer;
  7375. var need32Bits = false;
  7376. if (this._caps.uintIndices) {
  7377. for (var index = 0; index < indices.length; index++) {
  7378. if (indices[index] > 65535) {
  7379. need32Bits = true;
  7380. break;
  7381. }
  7382. }
  7383. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7384. }
  7385. else {
  7386. arrayBuffer = new Uint16Array(indices);
  7387. }
  7388. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7389. this._resetIndexBufferBinding();
  7390. vbo.references = 1;
  7391. vbo.is32Bits = need32Bits;
  7392. return vbo;
  7393. };
  7394. Engine.prototype.bindArrayBuffer = function (buffer) {
  7395. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7396. };
  7397. Engine.prototype.bindIndexBuffer = function (buffer) {
  7398. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7399. };
  7400. Engine.prototype.bindBuffer = function (buffer, target) {
  7401. if (this._currentBoundBuffer[target] !== buffer) {
  7402. this._gl.bindBuffer(target, buffer);
  7403. this._currentBoundBuffer[target] = buffer;
  7404. }
  7405. };
  7406. Engine.prototype.updateArrayBuffer = function (data) {
  7407. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7408. };
  7409. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7410. var pointer = this._currentBufferPointers[indx];
  7411. var changed = false;
  7412. if (!pointer) {
  7413. changed = true;
  7414. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7415. }
  7416. else {
  7417. if (pointer.buffer !== buffer) {
  7418. pointer.buffer = buffer;
  7419. changed = true;
  7420. }
  7421. if (pointer.size !== size) {
  7422. pointer.size = size;
  7423. changed = true;
  7424. }
  7425. if (pointer.type !== type) {
  7426. pointer.type = type;
  7427. changed = true;
  7428. }
  7429. if (pointer.normalized !== normalized) {
  7430. pointer.normalized = normalized;
  7431. changed = true;
  7432. }
  7433. if (pointer.stride !== stride) {
  7434. pointer.stride = stride;
  7435. changed = true;
  7436. }
  7437. if (pointer.offset !== offset) {
  7438. pointer.offset = offset;
  7439. changed = true;
  7440. }
  7441. }
  7442. if (changed) {
  7443. this.bindArrayBuffer(buffer);
  7444. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7445. }
  7446. };
  7447. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7448. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7449. this._cachedVertexBuffers = vertexBuffer;
  7450. this._cachedEffectForVertexBuffers = effect;
  7451. var attributesCount = effect.getAttributesCount();
  7452. var offset = 0;
  7453. for (var index = 0; index < attributesCount; index++) {
  7454. if (index < vertexDeclaration.length) {
  7455. var order = effect.getAttributeLocation(index);
  7456. if (order >= 0) {
  7457. if (!this._vertexAttribArraysEnabled[order]) {
  7458. this._gl.enableVertexAttribArray(order);
  7459. this._vertexAttribArraysEnabled[order] = true;
  7460. }
  7461. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7462. }
  7463. offset += vertexDeclaration[index] * 4;
  7464. }
  7465. else {
  7466. //disable effect attributes that have no data
  7467. var order = effect.getAttributeLocation(index);
  7468. if (this._vertexAttribArraysEnabled[order]) {
  7469. this._gl.disableVertexAttribArray(order);
  7470. this._vertexAttribArraysEnabled[order] = false;
  7471. }
  7472. }
  7473. }
  7474. }
  7475. if (this._cachedIndexBuffer !== indexBuffer) {
  7476. this._cachedIndexBuffer = indexBuffer;
  7477. this.bindIndexBuffer(indexBuffer);
  7478. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7479. }
  7480. };
  7481. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7482. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7483. this._cachedVertexBuffers = vertexBuffers;
  7484. this._cachedEffectForVertexBuffers = effect;
  7485. var attributes = effect.getAttributesNames();
  7486. for (var index = 0; index < attributes.length; index++) {
  7487. var order = effect.getAttributeLocation(index);
  7488. if (order >= 0) {
  7489. var vertexBuffer = vertexBuffers[attributes[index]];
  7490. if (!vertexBuffer) {
  7491. if (this._vertexAttribArraysEnabled[order]) {
  7492. this._gl.disableVertexAttribArray(order);
  7493. this._vertexAttribArraysEnabled[order] = false;
  7494. }
  7495. continue;
  7496. }
  7497. if (!this._vertexAttribArraysEnabled[order]) {
  7498. this._gl.enableVertexAttribArray(order);
  7499. this._vertexAttribArraysEnabled[order] = true;
  7500. }
  7501. var buffer = vertexBuffer.getBuffer();
  7502. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7503. if (vertexBuffer.getIsInstanced()) {
  7504. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7505. this._currentInstanceLocations.push(order);
  7506. this._currentInstanceBuffers.push(buffer);
  7507. }
  7508. }
  7509. }
  7510. }
  7511. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7512. this._cachedIndexBuffer = indexBuffer;
  7513. this.bindIndexBuffer(indexBuffer);
  7514. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7515. }
  7516. };
  7517. Engine.prototype.unbindInstanceAttributes = function () {
  7518. var boundBuffer;
  7519. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7520. var instancesBuffer = this._currentInstanceBuffers[i];
  7521. if (boundBuffer != instancesBuffer) {
  7522. boundBuffer = instancesBuffer;
  7523. this.bindArrayBuffer(instancesBuffer);
  7524. }
  7525. var offsetLocation = this._currentInstanceLocations[i];
  7526. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7527. }
  7528. this._currentInstanceBuffers.length = 0;
  7529. this._currentInstanceLocations.length = 0;
  7530. };
  7531. Engine.prototype._releaseBuffer = function (buffer) {
  7532. buffer.references--;
  7533. if (buffer.references === 0) {
  7534. this._gl.deleteBuffer(buffer);
  7535. return true;
  7536. }
  7537. return false;
  7538. };
  7539. Engine.prototype.createInstancesBuffer = function (capacity) {
  7540. var buffer = this._gl.createBuffer();
  7541. buffer.capacity = capacity;
  7542. this.bindArrayBuffer(buffer);
  7543. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7544. return buffer;
  7545. };
  7546. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7547. this._gl.deleteBuffer(buffer);
  7548. };
  7549. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7550. this.bindArrayBuffer(instancesBuffer);
  7551. if (data) {
  7552. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7553. }
  7554. if (offsetLocations[0].index !== undefined) {
  7555. var stride = 0;
  7556. for (var i = 0; i < offsetLocations.length; i++) {
  7557. var ai = offsetLocations[i];
  7558. stride += ai.attributeSize * 4;
  7559. }
  7560. for (var i = 0; i < offsetLocations.length; i++) {
  7561. var ai = offsetLocations[i];
  7562. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7563. this._gl.enableVertexAttribArray(ai.index);
  7564. this._vertexAttribArraysEnabled[ai.index] = true;
  7565. }
  7566. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7567. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7568. this._currentInstanceLocations.push(ai.index);
  7569. this._currentInstanceBuffers.push(instancesBuffer);
  7570. }
  7571. }
  7572. else {
  7573. for (var index = 0; index < 4; index++) {
  7574. var offsetLocation = offsetLocations[index];
  7575. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7576. this._gl.enableVertexAttribArray(offsetLocation);
  7577. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7578. }
  7579. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7580. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7581. this._currentInstanceLocations.push(offsetLocation);
  7582. this._currentInstanceBuffers.push(instancesBuffer);
  7583. }
  7584. }
  7585. };
  7586. Engine.prototype.applyStates = function () {
  7587. this._depthCullingState.apply(this._gl);
  7588. this._stencilState.apply(this._gl);
  7589. this._alphaState.apply(this._gl);
  7590. };
  7591. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7592. // Apply states
  7593. this.applyStates();
  7594. this._drawCalls.addCount(1, false);
  7595. // Render
  7596. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7597. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7598. if (instancesCount) {
  7599. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7600. return;
  7601. }
  7602. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7603. };
  7604. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7605. // Apply states
  7606. this.applyStates();
  7607. this._drawCalls.addCount(1, false);
  7608. if (instancesCount) {
  7609. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7610. return;
  7611. }
  7612. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7613. };
  7614. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7615. // Apply states
  7616. this.applyStates();
  7617. this._drawCalls.addCount(1, false);
  7618. if (instancesCount) {
  7619. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7620. return;
  7621. }
  7622. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7623. };
  7624. // Shaders
  7625. Engine.prototype._releaseEffect = function (effect) {
  7626. if (this._compiledEffects[effect._key]) {
  7627. delete this._compiledEffects[effect._key];
  7628. if (effect.getProgram()) {
  7629. this._gl.deleteProgram(effect.getProgram());
  7630. }
  7631. }
  7632. };
  7633. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7634. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7635. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7636. var name = vertex + "+" + fragment + "@" + defines;
  7637. if (this._compiledEffects[name]) {
  7638. return this._compiledEffects[name];
  7639. }
  7640. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7641. effect._key = name;
  7642. this._compiledEffects[name] = effect;
  7643. return effect;
  7644. };
  7645. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7646. if (uniformsNames === void 0) { uniformsNames = []; }
  7647. if (samplers === void 0) { samplers = []; }
  7648. if (defines === void 0) { defines = ""; }
  7649. return this.createEffect({
  7650. vertex: "particles",
  7651. fragmentElement: fragmentName
  7652. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7653. };
  7654. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7655. context = context || this._gl;
  7656. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7657. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7658. var shaderProgram = context.createProgram();
  7659. context.attachShader(shaderProgram, vertexShader);
  7660. context.attachShader(shaderProgram, fragmentShader);
  7661. context.linkProgram(shaderProgram);
  7662. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7663. if (!linked) {
  7664. var error = context.getProgramInfoLog(shaderProgram);
  7665. if (error) {
  7666. throw new Error(error);
  7667. }
  7668. }
  7669. context.deleteShader(vertexShader);
  7670. context.deleteShader(fragmentShader);
  7671. return shaderProgram;
  7672. };
  7673. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7674. var results = [];
  7675. for (var index = 0; index < uniformsNames.length; index++) {
  7676. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7677. }
  7678. return results;
  7679. };
  7680. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7681. var results = [];
  7682. for (var index = 0; index < attributesNames.length; index++) {
  7683. try {
  7684. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7685. }
  7686. catch (e) {
  7687. results.push(-1);
  7688. }
  7689. }
  7690. return results;
  7691. };
  7692. Engine.prototype.enableEffect = function (effect) {
  7693. //if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7694. // if (effect && effect.onBind) {
  7695. // effect.onBind(effect);
  7696. // }
  7697. // return;
  7698. //}
  7699. // Use program
  7700. this.setProgram(effect.getProgram());
  7701. this._currentEffect = effect;
  7702. if (effect.onBind) {
  7703. effect.onBind(effect);
  7704. }
  7705. };
  7706. Engine.prototype.setIntArray = function (uniform, array) {
  7707. if (!uniform)
  7708. return;
  7709. this._gl.uniform1iv(uniform, array);
  7710. };
  7711. Engine.prototype.setIntArray2 = function (uniform, array) {
  7712. if (!uniform || array.length % 2 !== 0)
  7713. return;
  7714. this._gl.uniform2iv(uniform, array);
  7715. };
  7716. Engine.prototype.setIntArray3 = function (uniform, array) {
  7717. if (!uniform || array.length % 3 !== 0)
  7718. return;
  7719. this._gl.uniform3iv(uniform, array);
  7720. };
  7721. Engine.prototype.setIntArray4 = function (uniform, array) {
  7722. if (!uniform || array.length % 4 !== 0)
  7723. return;
  7724. this._gl.uniform4iv(uniform, array);
  7725. };
  7726. Engine.prototype.setFloatArray = function (uniform, array) {
  7727. if (!uniform)
  7728. return;
  7729. this._gl.uniform1fv(uniform, array);
  7730. };
  7731. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7732. if (!uniform || array.length % 2 !== 0)
  7733. return;
  7734. this._gl.uniform2fv(uniform, array);
  7735. };
  7736. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7737. if (!uniform || array.length % 3 !== 0)
  7738. return;
  7739. this._gl.uniform3fv(uniform, array);
  7740. };
  7741. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7742. if (!uniform || array.length % 4 !== 0)
  7743. return;
  7744. this._gl.uniform4fv(uniform, array);
  7745. };
  7746. Engine.prototype.setArray = function (uniform, array) {
  7747. if (!uniform)
  7748. return;
  7749. this._gl.uniform1fv(uniform, array);
  7750. };
  7751. Engine.prototype.setArray2 = function (uniform, array) {
  7752. if (!uniform || array.length % 2 !== 0)
  7753. return;
  7754. this._gl.uniform2fv(uniform, array);
  7755. };
  7756. Engine.prototype.setArray3 = function (uniform, array) {
  7757. if (!uniform || array.length % 3 !== 0)
  7758. return;
  7759. this._gl.uniform3fv(uniform, array);
  7760. };
  7761. Engine.prototype.setArray4 = function (uniform, array) {
  7762. if (!uniform || array.length % 4 !== 0)
  7763. return;
  7764. this._gl.uniform4fv(uniform, array);
  7765. };
  7766. Engine.prototype.setMatrices = function (uniform, matrices) {
  7767. if (!uniform)
  7768. return;
  7769. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7770. };
  7771. Engine.prototype.setMatrix = function (uniform, matrix) {
  7772. if (!uniform)
  7773. return;
  7774. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7775. };
  7776. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7777. if (!uniform)
  7778. return;
  7779. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7780. };
  7781. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7782. if (!uniform)
  7783. return;
  7784. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7785. };
  7786. Engine.prototype.setFloat = function (uniform, value) {
  7787. if (!uniform)
  7788. return;
  7789. this._gl.uniform1f(uniform, value);
  7790. };
  7791. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7792. if (!uniform)
  7793. return;
  7794. this._gl.uniform2f(uniform, x, y);
  7795. };
  7796. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7797. if (!uniform)
  7798. return;
  7799. this._gl.uniform3f(uniform, x, y, z);
  7800. };
  7801. Engine.prototype.setBool = function (uniform, bool) {
  7802. if (!uniform)
  7803. return;
  7804. this._gl.uniform1i(uniform, bool);
  7805. };
  7806. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7807. if (!uniform)
  7808. return;
  7809. this._gl.uniform4f(uniform, x, y, z, w);
  7810. };
  7811. Engine.prototype.setColor3 = function (uniform, color3) {
  7812. if (!uniform)
  7813. return;
  7814. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7815. };
  7816. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7817. if (!uniform)
  7818. return;
  7819. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7820. };
  7821. // States
  7822. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7823. if (zOffset === void 0) { zOffset = 0; }
  7824. if (reverseSide === void 0) { reverseSide = false; }
  7825. // Culling
  7826. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7827. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7828. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7829. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7830. if (culling) {
  7831. this._depthCullingState.cullFace = cullFace;
  7832. this._depthCullingState.cull = true;
  7833. }
  7834. else {
  7835. this._depthCullingState.cull = false;
  7836. }
  7837. }
  7838. // Z offset
  7839. this._depthCullingState.zOffset = zOffset;
  7840. };
  7841. Engine.prototype.setDepthBuffer = function (enable) {
  7842. this._depthCullingState.depthTest = enable;
  7843. };
  7844. Engine.prototype.getDepthWrite = function () {
  7845. return this._depthCullingState.depthMask;
  7846. };
  7847. Engine.prototype.setDepthWrite = function (enable) {
  7848. this._depthCullingState.depthMask = enable;
  7849. };
  7850. Engine.prototype.setColorWrite = function (enable) {
  7851. this._gl.colorMask(enable, enable, enable, enable);
  7852. };
  7853. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7854. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7855. if (this._alphaMode === mode) {
  7856. return;
  7857. }
  7858. switch (mode) {
  7859. case Engine.ALPHA_DISABLE:
  7860. this._alphaState.alphaBlend = false;
  7861. break;
  7862. case Engine.ALPHA_COMBINE:
  7863. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7864. this._alphaState.alphaBlend = true;
  7865. break;
  7866. case Engine.ALPHA_ONEONE:
  7867. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7868. this._alphaState.alphaBlend = true;
  7869. break;
  7870. case Engine.ALPHA_ADD:
  7871. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7872. this._alphaState.alphaBlend = true;
  7873. break;
  7874. case Engine.ALPHA_SUBTRACT:
  7875. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7876. this._alphaState.alphaBlend = true;
  7877. break;
  7878. case Engine.ALPHA_MULTIPLY:
  7879. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7880. this._alphaState.alphaBlend = true;
  7881. break;
  7882. case Engine.ALPHA_MAXIMIZED:
  7883. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7884. this._alphaState.alphaBlend = true;
  7885. break;
  7886. }
  7887. if (!noDepthWriteChange) {
  7888. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7889. }
  7890. this._alphaMode = mode;
  7891. };
  7892. Engine.prototype.getAlphaMode = function () {
  7893. return this._alphaMode;
  7894. };
  7895. Engine.prototype.setAlphaTesting = function (enable) {
  7896. this._alphaTest = enable;
  7897. };
  7898. Engine.prototype.getAlphaTesting = function () {
  7899. return this._alphaTest;
  7900. };
  7901. // Textures
  7902. Engine.prototype.wipeCaches = function () {
  7903. this.resetTextureCache();
  7904. this._currentEffect = null;
  7905. this._stencilState.reset();
  7906. this._depthCullingState.reset();
  7907. this.setDepthFunctionToLessOrEqual();
  7908. this._alphaState.reset();
  7909. this._cachedVertexBuffers = null;
  7910. this._cachedIndexBuffer = null;
  7911. this._cachedEffectForVertexBuffers = null;
  7912. };
  7913. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7914. var gl = this._gl;
  7915. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7916. var magFilter = gl.NEAREST;
  7917. var minFilter = gl.NEAREST;
  7918. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7919. magFilter = gl.LINEAR;
  7920. minFilter = gl.LINEAR;
  7921. }
  7922. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7923. magFilter = gl.LINEAR;
  7924. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7925. }
  7926. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7927. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7928. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7929. texture.samplingMode = samplingMode;
  7930. };
  7931. Engine.prototype.createTexture = function (urlOrList, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7932. var _this = this;
  7933. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7934. if (onLoad === void 0) { onLoad = null; }
  7935. if (onError === void 0) { onError = null; }
  7936. if (buffer === void 0) { buffer = null; }
  7937. var texture = this._gl.createTexture();
  7938. var url = ((urlOrList.constructor === Array) ? urlOrList[0] : urlOrList);
  7939. var extension;
  7940. var fromData = false;
  7941. if (url.substr(0, 5) === "data:") {
  7942. fromData = true;
  7943. }
  7944. if (!fromData)
  7945. extension = url.substr(url.length - 4, 4).toLowerCase();
  7946. else {
  7947. var oldUrl = url;
  7948. fromData = oldUrl.split(':');
  7949. url = oldUrl;
  7950. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7951. }
  7952. var isDDS = (extension === ".dds");
  7953. var isTGA = (extension === ".tga");
  7954. scene._addPendingData(texture);
  7955. texture.url = url;
  7956. texture.noMipmap = noMipmap;
  7957. texture.references = 1;
  7958. texture.samplingMode = samplingMode;
  7959. texture.onLoadedCallbacks = [onLoad];
  7960. this._loadedTexturesCache.push(texture);
  7961. var onerror = function () {
  7962. scene._removePendingData(texture);
  7963. if (onError) {
  7964. onError();
  7965. }
  7966. };
  7967. var callback;
  7968. if (isTGA) {
  7969. callback = function (arrayBuffer) {
  7970. var data = new Uint8Array(arrayBuffer);
  7971. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7972. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7973. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7974. }, samplingMode);
  7975. };
  7976. if (!(fromData instanceof Array))
  7977. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7978. callback(arrayBuffer);
  7979. }, null, scene.database, true, onerror);
  7980. else
  7981. callback(buffer);
  7982. }
  7983. else if (isDDS) {
  7984. if (!this.getCaps().s3tc) {
  7985. if (urlOrList instanceof Array) {
  7986. var newList = urlOrList.slice(1);
  7987. if (newList.length > 0) {
  7988. return this.createTexture(newList, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer);
  7989. }
  7990. }
  7991. onerror();
  7992. return null;
  7993. }
  7994. callback = function (data) {
  7995. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7996. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7997. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7998. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7999. }, samplingMode);
  8000. };
  8001. if (!(fromData instanceof Array))
  8002. BABYLON.Tools.LoadFile(url, function (data) {
  8003. callback(data);
  8004. }, null, scene.database, true, onerror);
  8005. else
  8006. callback(buffer);
  8007. }
  8008. else {
  8009. var onload = function (img) {
  8010. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8011. var isPot = (img.width === potWidth && img.height === potHeight);
  8012. if (!isPot) {
  8013. _this._prepareWorkingCanvas();
  8014. _this._workingCanvas.width = potWidth;
  8015. _this._workingCanvas.height = potHeight;
  8016. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8017. _this._workingContext.imageSmoothingEnabled = false;
  8018. _this._workingContext.mozImageSmoothingEnabled = false;
  8019. _this._workingContext.oImageSmoothingEnabled = false;
  8020. _this._workingContext.webkitImageSmoothingEnabled = false;
  8021. _this._workingContext.msImageSmoothingEnabled = false;
  8022. }
  8023. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8024. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8025. _this._workingContext.imageSmoothingEnabled = true;
  8026. _this._workingContext.mozImageSmoothingEnabled = true;
  8027. _this._workingContext.oImageSmoothingEnabled = true;
  8028. _this._workingContext.webkitImageSmoothingEnabled = true;
  8029. _this._workingContext.msImageSmoothingEnabled = true;
  8030. }
  8031. }
  8032. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8033. }, samplingMode);
  8034. };
  8035. if (!(fromData instanceof Array))
  8036. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8037. else
  8038. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8039. }
  8040. return texture;
  8041. };
  8042. Engine.prototype._getInternalFormat = function (format) {
  8043. var internalFormat = this._gl.RGBA;
  8044. switch (format) {
  8045. case Engine.TEXTUREFORMAT_ALPHA:
  8046. internalFormat = this._gl.ALPHA;
  8047. break;
  8048. case Engine.TEXTUREFORMAT_LUMINANCE:
  8049. internalFormat = this._gl.LUMINANCE;
  8050. break;
  8051. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8052. internalFormat = this._gl.LUMINANCE_ALPHA;
  8053. break;
  8054. case Engine.TEXTUREFORMAT_RGB:
  8055. internalFormat = this._gl.RGB;
  8056. break;
  8057. case Engine.TEXTUREFORMAT_RGBA:
  8058. internalFormat = this._gl.RGBA;
  8059. break;
  8060. }
  8061. return internalFormat;
  8062. };
  8063. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8064. if (compression === void 0) { compression = null; }
  8065. var internalFormat = this._getInternalFormat(format);
  8066. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8067. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8068. if (texture._width % 4 !== 0) {
  8069. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8070. }
  8071. if (compression) {
  8072. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8073. }
  8074. else {
  8075. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8076. }
  8077. if (texture.generateMipMaps) {
  8078. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8079. }
  8080. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8081. this.resetTextureCache();
  8082. texture.isReady = true;
  8083. };
  8084. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8085. if (compression === void 0) { compression = null; }
  8086. var texture = this._gl.createTexture();
  8087. texture._baseWidth = width;
  8088. texture._baseHeight = height;
  8089. texture._width = width;
  8090. texture._height = height;
  8091. texture.references = 1;
  8092. this.updateRawTexture(texture, data, format, invertY, compression);
  8093. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8094. // Filters
  8095. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8096. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8097. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8098. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8099. texture.samplingMode = samplingMode;
  8100. this._loadedTexturesCache.push(texture);
  8101. return texture;
  8102. };
  8103. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8104. var texture = this._gl.createTexture();
  8105. texture._baseWidth = width;
  8106. texture._baseHeight = height;
  8107. if (generateMipMaps) {
  8108. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8109. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8110. }
  8111. this.resetTextureCache();
  8112. texture._width = width;
  8113. texture._height = height;
  8114. texture.isReady = false;
  8115. texture.generateMipMaps = generateMipMaps;
  8116. texture.references = 1;
  8117. texture.samplingMode = samplingMode;
  8118. this.updateTextureSamplingMode(samplingMode, texture);
  8119. this._loadedTexturesCache.push(texture);
  8120. return texture;
  8121. };
  8122. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8123. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8124. if (texture.isCube) {
  8125. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8126. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8127. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8128. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8129. }
  8130. else {
  8131. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8132. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8133. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8134. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8135. }
  8136. };
  8137. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8138. if (premulAlpha === void 0) { premulAlpha = false; }
  8139. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8140. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8141. if (premulAlpha) {
  8142. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8143. }
  8144. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8145. if (texture.generateMipMaps) {
  8146. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8147. }
  8148. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8149. if (premulAlpha) {
  8150. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8151. }
  8152. this.resetTextureCache();
  8153. texture.isReady = true;
  8154. };
  8155. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8156. if (texture._isDisabled) {
  8157. return;
  8158. }
  8159. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8160. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8161. try {
  8162. // Testing video texture support
  8163. if (this._videoTextureSupported === undefined) {
  8164. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8165. if (this._gl.getError() !== 0) {
  8166. this._videoTextureSupported = false;
  8167. }
  8168. else {
  8169. this._videoTextureSupported = true;
  8170. }
  8171. }
  8172. // Copy video through the current working canvas if video texture is not supported
  8173. if (!this._videoTextureSupported) {
  8174. if (!texture._workingCanvas) {
  8175. texture._workingCanvas = document.createElement("canvas");
  8176. texture._workingContext = texture._workingCanvas.getContext("2d");
  8177. texture._workingCanvas.width = texture._width;
  8178. texture._workingCanvas.height = texture._height;
  8179. }
  8180. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8181. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8182. }
  8183. else {
  8184. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8185. }
  8186. if (texture.generateMipMaps) {
  8187. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8188. }
  8189. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8190. this.resetTextureCache();
  8191. texture.isReady = true;
  8192. }
  8193. catch (ex) {
  8194. // Something unexpected
  8195. // Let's disable the texture
  8196. texture._isDisabled = true;
  8197. }
  8198. };
  8199. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8200. // old version had a "generateMipMaps" arg instead of options.
  8201. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8202. // in the same way, generateDepthBuffer is defaulted to true
  8203. var generateMipMaps = false;
  8204. var generateDepthBuffer = true;
  8205. var generateStencilBuffer = false;
  8206. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8207. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8208. if (options !== undefined) {
  8209. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8210. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8211. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8212. type = options.type === undefined ? type : options.type;
  8213. if (options.samplingMode !== undefined) {
  8214. samplingMode = options.samplingMode;
  8215. }
  8216. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8217. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8218. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8219. }
  8220. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8221. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8222. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8223. }
  8224. }
  8225. var gl = this._gl;
  8226. var texture = gl.createTexture();
  8227. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8228. var width = size.width || size;
  8229. var height = size.height || size;
  8230. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8231. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8232. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8233. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8234. }
  8235. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8236. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8237. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8238. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8239. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  8240. var depthStencilBuffer;
  8241. // Create the depth/stencil buffer
  8242. if (generateStencilBuffer) {
  8243. depthStencilBuffer = gl.createRenderbuffer();
  8244. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8245. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8246. }
  8247. else if (generateDepthBuffer) {
  8248. depthStencilBuffer = gl.createRenderbuffer();
  8249. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8250. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8251. }
  8252. // Create the framebuffer
  8253. var framebuffer = gl.createFramebuffer();
  8254. this.bindUnboundFramebuffer(framebuffer);
  8255. // Manage attachments
  8256. if (generateStencilBuffer) {
  8257. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8258. }
  8259. else if (generateDepthBuffer) {
  8260. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8261. }
  8262. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8263. if (generateMipMaps) {
  8264. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8265. }
  8266. // Unbind
  8267. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8268. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8269. this.bindUnboundFramebuffer(null);
  8270. texture._framebuffer = framebuffer;
  8271. if (generateDepthBuffer) {
  8272. texture._depthBuffer = depthStencilBuffer;
  8273. }
  8274. texture._baseWidth = width;
  8275. texture._baseHeight = height;
  8276. texture._width = width;
  8277. texture._height = height;
  8278. texture.isReady = true;
  8279. texture.generateMipMaps = generateMipMaps;
  8280. texture.references = 1;
  8281. texture.samplingMode = samplingMode;
  8282. texture.type = type;
  8283. this.resetTextureCache();
  8284. this._loadedTexturesCache.push(texture);
  8285. return texture;
  8286. };
  8287. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8288. var gl = this._gl;
  8289. var texture = gl.createTexture();
  8290. var generateMipMaps = true;
  8291. var generateDepthBuffer = true;
  8292. var generateStencilBuffer = false;
  8293. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8294. if (options !== undefined) {
  8295. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8296. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8297. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8298. if (options.samplingMode !== undefined) {
  8299. samplingMode = options.samplingMode;
  8300. }
  8301. }
  8302. texture.isCube = true;
  8303. texture.references = 1;
  8304. texture.generateMipMaps = generateMipMaps;
  8305. texture.references = 1;
  8306. texture.samplingMode = samplingMode;
  8307. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8308. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8309. for (var face = 0; face < 6; face++) {
  8310. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8311. }
  8312. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8313. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8314. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8315. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8316. // Create the depth buffer
  8317. var depthStencilBuffer;
  8318. // Create the depth/stencil buffer
  8319. if (generateStencilBuffer) {
  8320. depthStencilBuffer = gl.createRenderbuffer();
  8321. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8322. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8323. }
  8324. else if (generateDepthBuffer) {
  8325. depthStencilBuffer = gl.createRenderbuffer();
  8326. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8327. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8328. }
  8329. // Create the framebuffer
  8330. var framebuffer = gl.createFramebuffer();
  8331. this.bindUnboundFramebuffer(framebuffer);
  8332. // Manage attachments
  8333. if (generateStencilBuffer) {
  8334. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8335. }
  8336. else if (generateDepthBuffer) {
  8337. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8338. }
  8339. // Mipmaps
  8340. if (texture.generateMipMaps) {
  8341. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8342. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8343. }
  8344. // Unbind
  8345. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8346. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8347. this.bindUnboundFramebuffer(null);
  8348. texture._framebuffer = framebuffer;
  8349. if (generateDepthBuffer) {
  8350. texture._depthBuffer = depthStencilBuffer;
  8351. }
  8352. texture._width = size;
  8353. texture._height = size;
  8354. texture.isReady = true;
  8355. this.resetTextureCache();
  8356. this._loadedTexturesCache.push(texture);
  8357. return texture;
  8358. };
  8359. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8360. var _this = this;
  8361. if (onLoad === void 0) { onLoad = null; }
  8362. if (onError === void 0) { onError = null; }
  8363. var gl = this._gl;
  8364. var texture = gl.createTexture();
  8365. texture.isCube = true;
  8366. texture.url = rootUrl;
  8367. texture.references = 1;
  8368. texture.onLoadedCallbacks = [];
  8369. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  8370. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8371. if (isDDS) {
  8372. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8373. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8374. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8375. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8376. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8377. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8378. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8379. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8380. }
  8381. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8382. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8383. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8384. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8385. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8386. _this.resetTextureCache();
  8387. texture._width = info.width;
  8388. texture._height = info.height;
  8389. texture.isReady = true;
  8390. }, null, null, true, onError);
  8391. }
  8392. else {
  8393. cascadeLoad(rootUrl, scene, function (imgs) {
  8394. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8395. var height = width;
  8396. _this._prepareWorkingCanvas();
  8397. _this._workingCanvas.width = width;
  8398. _this._workingCanvas.height = height;
  8399. var faces = [
  8400. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8401. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8402. ];
  8403. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8404. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8405. for (var index = 0; index < faces.length; index++) {
  8406. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8407. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8408. }
  8409. if (!noMipmap) {
  8410. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8411. }
  8412. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8413. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8414. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8415. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8416. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8417. _this.resetTextureCache();
  8418. texture._width = width;
  8419. texture._height = height;
  8420. texture.isReady = true;
  8421. texture.onLoadedCallbacks.forEach(function (callback) {
  8422. callback();
  8423. });
  8424. if (onLoad) {
  8425. onLoad();
  8426. }
  8427. }, files, onError);
  8428. }
  8429. this._loadedTexturesCache.push(texture);
  8430. return texture;
  8431. };
  8432. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8433. texture._width = width;
  8434. texture._height = height;
  8435. texture._size = width * height;
  8436. texture._baseWidth = width;
  8437. texture._baseHeight = height;
  8438. };
  8439. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8440. var _this = this;
  8441. var gl = this._gl;
  8442. var texture = gl.createTexture();
  8443. scene._addPendingData(texture);
  8444. texture.isCube = true;
  8445. texture.references = 1;
  8446. texture.url = url;
  8447. var internalFormat = this._getInternalFormat(format);
  8448. var textureType = gl.UNSIGNED_BYTE;
  8449. if (type === Engine.TEXTURETYPE_FLOAT) {
  8450. textureType = gl.FLOAT;
  8451. }
  8452. var width = size;
  8453. var height = width;
  8454. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8455. texture._width = width;
  8456. texture._height = height;
  8457. var onerror = function () {
  8458. scene._removePendingData(texture);
  8459. };
  8460. var internalCallback = function (data) {
  8461. var rgbeDataArrays = callback(data);
  8462. var facesIndex = [
  8463. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8464. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8465. ];
  8466. width = texture._width;
  8467. height = texture._height;
  8468. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8469. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8470. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8471. if (!noMipmap && isPot) {
  8472. if (mipmmapGenerator) {
  8473. var arrayTemp = [];
  8474. // Data are known to be in +X +Y +Z -X -Y -Z
  8475. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8476. arrayTemp.push(rgbeDataArrays[0]); // +X
  8477. arrayTemp.push(rgbeDataArrays[3]); // -X
  8478. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8479. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8480. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8481. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8482. var mipData = mipmmapGenerator(arrayTemp);
  8483. for (var level = 0; level < mipData.length; level++) {
  8484. var mipSize = width >> level;
  8485. // mipData is order in +X -X +Y -Y +Z -Z
  8486. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8487. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8488. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8489. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8490. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8491. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8492. }
  8493. }
  8494. else {
  8495. // Data are known to be in +X +Y +Z -X -Y -Z
  8496. for (var index = 0; index < facesIndex.length; index++) {
  8497. var faceData = rgbeDataArrays[index];
  8498. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8499. }
  8500. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8501. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8502. // By following the webgl standard changes from Revision 7, 2014/11/24
  8503. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8504. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8505. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8506. // Data are known to be in +X +Y +Z -X -Y -Z
  8507. for (var index = 0; index < facesIndex.length; index++) {
  8508. var faceData = rgbeDataArrays[index];
  8509. // Create a new RGBA Face.
  8510. var newFaceData = new Float32Array(width * height * 4);
  8511. for (var x = 0; x < width; x++) {
  8512. for (var y = 0; y < height; y++) {
  8513. var index_1 = (y * width + x) * 3;
  8514. var newIndex = (y * width + x) * 4;
  8515. // Map Old Value to new value.
  8516. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8517. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8518. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8519. // Add fully opaque alpha channel.
  8520. newFaceData[newIndex + 3] = 1;
  8521. }
  8522. }
  8523. // Reupload the face.
  8524. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8525. }
  8526. // Try to generate mipmap again.
  8527. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8528. }
  8529. }
  8530. }
  8531. else {
  8532. noMipmap = true;
  8533. }
  8534. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8535. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8536. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8537. }
  8538. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8539. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8540. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8541. }
  8542. else {
  8543. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8544. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8545. }
  8546. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8547. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8548. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8549. texture.isReady = true;
  8550. _this.resetTextureCache();
  8551. scene._removePendingData(texture);
  8552. };
  8553. BABYLON.Tools.LoadFile(url, function (data) {
  8554. internalCallback(data);
  8555. }, onerror, scene.database, true);
  8556. return texture;
  8557. };
  8558. ;
  8559. Engine.prototype._releaseTexture = function (texture) {
  8560. var gl = this._gl;
  8561. if (texture._framebuffer) {
  8562. gl.deleteFramebuffer(texture._framebuffer);
  8563. }
  8564. if (texture._depthBuffer) {
  8565. gl.deleteRenderbuffer(texture._depthBuffer);
  8566. }
  8567. gl.deleteTexture(texture);
  8568. // Unbind channels
  8569. this.unbindAllTextures();
  8570. var index = this._loadedTexturesCache.indexOf(texture);
  8571. if (index !== -1) {
  8572. this._loadedTexturesCache.splice(index, 1);
  8573. }
  8574. };
  8575. Engine.prototype.setProgram = function (program) {
  8576. if (this._currentProgram !== program) {
  8577. this._gl.useProgram(program);
  8578. this._currentProgram = program;
  8579. }
  8580. };
  8581. Engine.prototype.bindSamplers = function (effect) {
  8582. this.setProgram(effect.getProgram());
  8583. var samplers = effect.getSamplers();
  8584. for (var index = 0; index < samplers.length; index++) {
  8585. var uniform = effect.getUniform(samplers[index]);
  8586. this._gl.uniform1i(uniform, index);
  8587. }
  8588. this._currentEffect = null;
  8589. };
  8590. Engine.prototype.activateTexture = function (texture) {
  8591. if (this._activeTexture !== texture) {
  8592. this._gl.activeTexture(texture);
  8593. this._activeTexture = texture;
  8594. }
  8595. };
  8596. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8597. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8598. this._gl.bindTexture(target, texture);
  8599. this._activeTexturesCache[this._activeTexture] = texture;
  8600. }
  8601. };
  8602. Engine.prototype._bindTexture = function (channel, texture) {
  8603. if (channel < 0) {
  8604. return;
  8605. }
  8606. this.activateTexture(this._gl["TEXTURE" + channel]);
  8607. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8608. };
  8609. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8610. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8611. };
  8612. Engine.prototype.unbindAllTextures = function () {
  8613. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8614. this.activateTexture(this._gl["TEXTURE" + channel]);
  8615. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8616. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8617. }
  8618. };
  8619. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8620. if (channel < 0) {
  8621. return;
  8622. }
  8623. this._gl.uniform1i(uniform, channel);
  8624. this._setTexture(channel, texture);
  8625. };
  8626. Engine.prototype._setTexture = function (channel, texture) {
  8627. // Not ready?
  8628. if (!texture || !texture.isReady()) {
  8629. if (this._activeTexturesCache[channel] != null) {
  8630. this.activateTexture(this._gl["TEXTURE" + channel]);
  8631. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8632. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8633. }
  8634. return;
  8635. }
  8636. // Video
  8637. var alreadyActivated = false;
  8638. if (texture instanceof BABYLON.VideoTexture) {
  8639. this.activateTexture(this._gl["TEXTURE" + channel]);
  8640. alreadyActivated = true;
  8641. texture.update();
  8642. }
  8643. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8644. texture.delayLoad();
  8645. return;
  8646. }
  8647. var internalTexture = texture.getInternalTexture();
  8648. if (this._activeTexturesCache[channel] === internalTexture) {
  8649. return;
  8650. }
  8651. if (!alreadyActivated) {
  8652. this.activateTexture(this._gl["TEXTURE" + channel]);
  8653. }
  8654. if (internalTexture.isCube) {
  8655. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8656. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8657. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8658. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8659. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8660. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8661. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8662. }
  8663. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8664. }
  8665. else {
  8666. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8667. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8668. internalTexture._cachedWrapU = texture.wrapU;
  8669. switch (texture.wrapU) {
  8670. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8671. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8672. break;
  8673. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8674. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8675. break;
  8676. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8677. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8678. break;
  8679. }
  8680. }
  8681. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8682. internalTexture._cachedWrapV = texture.wrapV;
  8683. switch (texture.wrapV) {
  8684. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8685. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8686. break;
  8687. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8688. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8689. break;
  8690. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8691. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8692. break;
  8693. }
  8694. }
  8695. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8696. }
  8697. };
  8698. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8699. if (channel < 0) {
  8700. return;
  8701. }
  8702. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8703. this._textureUnits = new Int32Array(textures.length);
  8704. }
  8705. for (var i = 0; i < textures.length; i++) {
  8706. this._textureUnits[i] = channel + i;
  8707. }
  8708. this._gl.uniform1iv(uniform, this._textureUnits);
  8709. for (var index = 0; index < textures.length; index++) {
  8710. this._setTexture(channel + index, textures[index]);
  8711. }
  8712. };
  8713. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8714. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8715. var value = texture.anisotropicFilteringLevel;
  8716. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8717. value = 1;
  8718. }
  8719. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8720. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8721. texture._cachedAnisotropicFilteringLevel = value;
  8722. }
  8723. };
  8724. Engine.prototype.readPixels = function (x, y, width, height) {
  8725. var data = new Uint8Array(height * width * 4);
  8726. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8727. return data;
  8728. };
  8729. /**
  8730. * Add an externaly attached data from its key.
  8731. * This method call will fail and return false, if such key already exists.
  8732. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8733. * @param key the unique key that identifies the data
  8734. * @param data the data object to associate to the key for this Engine instance
  8735. * @return true if no such key were already present and the data was added successfully, false otherwise
  8736. */
  8737. Engine.prototype.addExternalData = function (key, data) {
  8738. return this._externalData.add(key, data);
  8739. };
  8740. /**
  8741. * Get an externaly attached data from its key
  8742. * @param key the unique key that identifies the data
  8743. * @return the associated data, if present (can be null), or undefined if not present
  8744. */
  8745. Engine.prototype.getExternalData = function (key) {
  8746. return this._externalData.get(key);
  8747. };
  8748. /**
  8749. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8750. * @param key the unique key that identifies the data
  8751. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8752. * @return the associated data, can be null if the factory returned null.
  8753. */
  8754. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8755. return this._externalData.getOrAddWithFactory(key, factory);
  8756. };
  8757. /**
  8758. * Remove an externaly attached data from the Engine instance
  8759. * @param key the unique key that identifies the data
  8760. * @return true if the data was successfully removed, false if it doesn't exist
  8761. */
  8762. Engine.prototype.removeExternalData = function (key) {
  8763. return this._externalData.remove(key);
  8764. };
  8765. Engine.prototype.releaseInternalTexture = function (texture) {
  8766. if (!texture) {
  8767. return;
  8768. }
  8769. texture.references--;
  8770. // Final reference ?
  8771. if (texture.references === 0) {
  8772. var texturesCache = this.getLoadedTexturesCache();
  8773. var index = texturesCache.indexOf(texture);
  8774. if (index > -1) {
  8775. texturesCache.splice(index, 1);
  8776. }
  8777. this._releaseTexture(texture);
  8778. }
  8779. };
  8780. Engine.prototype.unbindAllAttributes = function () {
  8781. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8782. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8783. continue;
  8784. }
  8785. this._gl.disableVertexAttribArray(i);
  8786. this._vertexAttribArraysEnabled[i] = false;
  8787. }
  8788. };
  8789. // Dispose
  8790. Engine.prototype.dispose = function () {
  8791. this.hideLoadingUI();
  8792. this.stopRenderLoop();
  8793. // Release scenes
  8794. while (this.scenes.length) {
  8795. this.scenes[0].dispose();
  8796. }
  8797. // Release audio engine
  8798. Engine.audioEngine.dispose();
  8799. // Release effects
  8800. for (var name in this._compiledEffects) {
  8801. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8802. }
  8803. // Unbind
  8804. this.unbindAllAttributes();
  8805. this._gl = null;
  8806. //WebVR
  8807. this.disableVR();
  8808. // Events
  8809. window.removeEventListener("blur", this._onBlur);
  8810. window.removeEventListener("focus", this._onFocus);
  8811. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8812. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8813. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8814. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8815. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8816. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8817. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8818. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8819. };
  8820. // Loading screen
  8821. Engine.prototype.displayLoadingUI = function () {
  8822. this._loadingScreen.displayLoadingUI();
  8823. };
  8824. Engine.prototype.hideLoadingUI = function () {
  8825. this._loadingScreen.hideLoadingUI();
  8826. };
  8827. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8828. get: function () {
  8829. return this._loadingScreen;
  8830. },
  8831. set: function (loadingScreen) {
  8832. this._loadingScreen = loadingScreen;
  8833. },
  8834. enumerable: true,
  8835. configurable: true
  8836. });
  8837. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8838. set: function (text) {
  8839. this._loadingScreen.loadingUIText = text;
  8840. },
  8841. enumerable: true,
  8842. configurable: true
  8843. });
  8844. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8845. set: function (color) {
  8846. this._loadingScreen.loadingUIBackgroundColor = color;
  8847. },
  8848. enumerable: true,
  8849. configurable: true
  8850. });
  8851. Engine.prototype.attachContextLostEvent = function (callback) {
  8852. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8853. };
  8854. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8855. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8856. };
  8857. Engine.prototype.getVertexShaderSource = function (program) {
  8858. var shaders = this._gl.getAttachedShaders(program);
  8859. return this._gl.getShaderSource(shaders[0]);
  8860. };
  8861. Engine.prototype.getFragmentShaderSource = function (program) {
  8862. var shaders = this._gl.getAttachedShaders(program);
  8863. return this._gl.getShaderSource(shaders[1]);
  8864. };
  8865. // FPS
  8866. Engine.prototype.getFps = function () {
  8867. return this.fps;
  8868. };
  8869. Engine.prototype.getDeltaTime = function () {
  8870. return this.deltaTime;
  8871. };
  8872. Engine.prototype._measureFps = function () {
  8873. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8874. var length = this.previousFramesDuration.length;
  8875. if (length >= 2) {
  8876. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8877. }
  8878. if (length >= this.fpsRange) {
  8879. if (length > this.fpsRange) {
  8880. this.previousFramesDuration.splice(0, 1);
  8881. length = this.previousFramesDuration.length;
  8882. }
  8883. var sum = 0;
  8884. for (var id = 0; id < length - 1; id++) {
  8885. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8886. }
  8887. this.fps = 1000.0 / (sum / (length - 1));
  8888. }
  8889. };
  8890. Engine.prototype._canRenderToFloatTexture = function () {
  8891. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8892. };
  8893. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8894. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8895. };
  8896. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8897. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8898. var tempcanvas = document.createElement("canvas");
  8899. tempcanvas.height = 16;
  8900. tempcanvas.width = 16;
  8901. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8902. // extension.
  8903. var ext = gl.getExtension(extension);
  8904. if (!ext) {
  8905. return false;
  8906. }
  8907. // setup GLSL program
  8908. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8909. var fragmentCode = "precision mediump float;\n uniform vec4 u_color;\n uniform sampler2D u_texture;\n\n void main() {\n gl_FragColor = texture2D(u_texture, vec2(0.5, 0.5)) * u_color;\n }";
  8910. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8911. gl.useProgram(program);
  8912. // look up where the vertex data needs to go.
  8913. var positionLocation = gl.getAttribLocation(program, "a_position");
  8914. var colorLoc = gl.getUniformLocation(program, "u_color");
  8915. // provide texture coordinates for the rectangle.
  8916. var positionBuffer = gl.createBuffer();
  8917. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8918. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8919. -1.0, -1.0,
  8920. 1.0, -1.0,
  8921. -1.0, 1.0,
  8922. -1.0, 1.0,
  8923. 1.0, -1.0,
  8924. 1.0, 1.0]), gl.STATIC_DRAW);
  8925. gl.enableVertexAttribArray(positionLocation);
  8926. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8927. var whiteTex = gl.createTexture();
  8928. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8929. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8930. var tex = gl.createTexture();
  8931. gl.bindTexture(gl.TEXTURE_2D, tex);
  8932. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8933. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8934. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8935. var fb = gl.createFramebuffer();
  8936. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8937. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8938. var cleanup = function () {
  8939. gl.deleteProgram(program);
  8940. gl.disableVertexAttribArray(positionLocation);
  8941. gl.deleteBuffer(positionBuffer);
  8942. gl.deleteFramebuffer(fb);
  8943. gl.deleteTexture(whiteTex);
  8944. gl.deleteTexture(tex);
  8945. };
  8946. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8947. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8948. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8949. cleanup();
  8950. return false;
  8951. }
  8952. // Draw the rectangle.
  8953. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8954. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8955. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8956. gl.bindTexture(gl.TEXTURE_2D, tex);
  8957. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8958. gl.clearColor(1, 0, 0, 1);
  8959. gl.clear(gl.COLOR_BUFFER_BIT);
  8960. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8961. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8962. var pixel = new Uint8Array(4);
  8963. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8964. if (pixel[0] !== 0 ||
  8965. pixel[1] < 248 ||
  8966. pixel[2] < 248 ||
  8967. pixel[3] < 254) {
  8968. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8969. cleanup();
  8970. return false;
  8971. }
  8972. // Succesfully rendered to "format" texture.
  8973. cleanup();
  8974. return true;
  8975. };
  8976. // Statics
  8977. Engine.isSupported = function () {
  8978. try {
  8979. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8980. if (navigator.isCocoonJS) {
  8981. return true;
  8982. }
  8983. var tempcanvas = document.createElement("canvas");
  8984. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8985. return gl != null && !!window.WebGLRenderingContext;
  8986. }
  8987. catch (e) {
  8988. return false;
  8989. }
  8990. };
  8991. // Const statics
  8992. Engine._ALPHA_DISABLE = 0;
  8993. Engine._ALPHA_ADD = 1;
  8994. Engine._ALPHA_COMBINE = 2;
  8995. Engine._ALPHA_SUBTRACT = 3;
  8996. Engine._ALPHA_MULTIPLY = 4;
  8997. Engine._ALPHA_MAXIMIZED = 5;
  8998. Engine._ALPHA_ONEONE = 6;
  8999. Engine._DELAYLOADSTATE_NONE = 0;
  9000. Engine._DELAYLOADSTATE_LOADED = 1;
  9001. Engine._DELAYLOADSTATE_LOADING = 2;
  9002. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  9003. Engine._TEXTUREFORMAT_ALPHA = 0;
  9004. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  9005. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  9006. Engine._TEXTUREFORMAT_RGB = 4;
  9007. Engine._TEXTUREFORMAT_RGBA = 5;
  9008. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  9009. Engine._TEXTURETYPE_FLOAT = 1;
  9010. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  9011. // Depht or Stencil test Constants.
  9012. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  9013. 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.
  9014. 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.
  9015. 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.
  9016. 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.
  9017. 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.
  9018. 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.
  9019. 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.
  9020. // Stencil Actions Constants.
  9021. Engine._KEEP = 0x1E00;
  9022. Engine._REPLACE = 0x1E01;
  9023. Engine._INCR = 0x1E02;
  9024. Engine._DECR = 0x1E03;
  9025. Engine._INVERT = 0x150A;
  9026. Engine._INCR_WRAP = 0x8507;
  9027. Engine._DECR_WRAP = 0x8508;
  9028. // Updatable statics so stick with vars here
  9029. Engine.CollisionsEpsilon = 0.001;
  9030. Engine.CodeRepository = "src/";
  9031. Engine.ShadersRepository = "src/Shaders/";
  9032. return Engine;
  9033. }());
  9034. BABYLON.Engine = Engine;
  9035. })(BABYLON || (BABYLON = {}));
  9036. //# sourceMappingURL=babylon.engine.js.map
  9037. var BABYLON;
  9038. (function (BABYLON) {
  9039. /**
  9040. * Node is the basic class for all scene objects (Mesh, Light Camera).
  9041. */
  9042. var Node = (function () {
  9043. /**
  9044. * @constructor
  9045. * @param {string} name - the name and id to be given to this node
  9046. * @param {BABYLON.Scene} the scene this node will be added to
  9047. */
  9048. function Node(name, scene) {
  9049. this.state = "";
  9050. this.metadata = null;
  9051. this.doNotSerialize = false;
  9052. this.animations = new Array();
  9053. this._ranges = {};
  9054. this._childrenFlag = -1;
  9055. this._isEnabled = true;
  9056. this._isReady = true;
  9057. this._currentRenderId = -1;
  9058. this._parentRenderId = -1;
  9059. /**
  9060. * An event triggered when the mesh is disposed.
  9061. * @type {BABYLON.Observable}
  9062. */
  9063. this.onDisposeObservable = new BABYLON.Observable();
  9064. this.name = name;
  9065. this.id = name;
  9066. this._scene = scene;
  9067. this._initCache();
  9068. }
  9069. Object.defineProperty(Node.prototype, "parent", {
  9070. get: function () {
  9071. return this._parentNode;
  9072. },
  9073. set: function (parent) {
  9074. if (this._parentNode === parent) {
  9075. return;
  9076. }
  9077. if (this._parentNode) {
  9078. var index = this._parentNode._children.indexOf(this);
  9079. if (index !== -1) {
  9080. this._parentNode._children.splice(index, 1);
  9081. }
  9082. }
  9083. this._parentNode = parent;
  9084. if (this._parentNode) {
  9085. if (!this._parentNode._children) {
  9086. this._parentNode._children = new Array();
  9087. }
  9088. this._parentNode._children.push(this);
  9089. }
  9090. },
  9091. enumerable: true,
  9092. configurable: true
  9093. });
  9094. Object.defineProperty(Node.prototype, "onDispose", {
  9095. set: function (callback) {
  9096. if (this._onDisposeObserver) {
  9097. this.onDisposeObservable.remove(this._onDisposeObserver);
  9098. }
  9099. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9100. },
  9101. enumerable: true,
  9102. configurable: true
  9103. });
  9104. Node.prototype.getScene = function () {
  9105. return this._scene;
  9106. };
  9107. Node.prototype.getEngine = function () {
  9108. return this._scene.getEngine();
  9109. };
  9110. // override it in derived class
  9111. Node.prototype.getWorldMatrix = function () {
  9112. return BABYLON.Matrix.Identity();
  9113. };
  9114. // override it in derived class if you add new variables to the cache
  9115. // and call the parent class method
  9116. Node.prototype._initCache = function () {
  9117. this._cache = {};
  9118. this._cache.parent = undefined;
  9119. };
  9120. Node.prototype.updateCache = function (force) {
  9121. if (!force && this.isSynchronized())
  9122. return;
  9123. this._cache.parent = this.parent;
  9124. this._updateCache();
  9125. };
  9126. // override it in derived class if you add new variables to the cache
  9127. // and call the parent class method if !ignoreParentClass
  9128. Node.prototype._updateCache = function (ignoreParentClass) {
  9129. };
  9130. // override it in derived class if you add new variables to the cache
  9131. Node.prototype._isSynchronized = function () {
  9132. return true;
  9133. };
  9134. Node.prototype._markSyncedWithParent = function () {
  9135. this._parentRenderId = this.parent._currentRenderId;
  9136. };
  9137. Node.prototype.isSynchronizedWithParent = function () {
  9138. if (!this.parent) {
  9139. return true;
  9140. }
  9141. if (this._parentRenderId !== this.parent._currentRenderId) {
  9142. return false;
  9143. }
  9144. return this.parent.isSynchronized();
  9145. };
  9146. Node.prototype.isSynchronized = function (updateCache) {
  9147. var check = this.hasNewParent();
  9148. check = check || !this.isSynchronizedWithParent();
  9149. check = check || !this._isSynchronized();
  9150. if (updateCache)
  9151. this.updateCache(true);
  9152. return !check;
  9153. };
  9154. Node.prototype.hasNewParent = function (update) {
  9155. if (this._cache.parent === this.parent)
  9156. return false;
  9157. if (update)
  9158. this._cache.parent = this.parent;
  9159. return true;
  9160. };
  9161. /**
  9162. * Is this node ready to be used/rendered
  9163. * @return {boolean} is it ready
  9164. */
  9165. Node.prototype.isReady = function () {
  9166. return this._isReady;
  9167. };
  9168. /**
  9169. * Is this node enabled.
  9170. * If the node has a parent and is enabled, the parent will be inspected as well.
  9171. * @return {boolean} whether this node (and its parent) is enabled.
  9172. * @see setEnabled
  9173. */
  9174. Node.prototype.isEnabled = function () {
  9175. if (!this._isEnabled) {
  9176. return false;
  9177. }
  9178. if (this.parent) {
  9179. return this.parent.isEnabled();
  9180. }
  9181. return true;
  9182. };
  9183. /**
  9184. * Set the enabled state of this node.
  9185. * @param {boolean} value - the new enabled state
  9186. * @see isEnabled
  9187. */
  9188. Node.prototype.setEnabled = function (value) {
  9189. this._isEnabled = value;
  9190. };
  9191. /**
  9192. * Is this node a descendant of the given node.
  9193. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9194. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9195. * @see parent
  9196. */
  9197. Node.prototype.isDescendantOf = function (ancestor) {
  9198. if (this.parent) {
  9199. if (this.parent === ancestor) {
  9200. return true;
  9201. }
  9202. return this.parent.isDescendantOf(ancestor);
  9203. }
  9204. return false;
  9205. };
  9206. /**
  9207. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9208. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9209. * @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.
  9210. * @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.
  9211. */
  9212. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9213. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9214. if (!this._children) {
  9215. return;
  9216. }
  9217. for (var index = 0; index < this._children.length; index++) {
  9218. var item = this._children[index];
  9219. if (!predicate || predicate(item)) {
  9220. results.push(item);
  9221. }
  9222. if (!directDescendantsOnly) {
  9223. item._getDescendants(results, false, predicate);
  9224. }
  9225. }
  9226. };
  9227. /**
  9228. * Will return all nodes that have this node as ascendant.
  9229. * @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.
  9230. * @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.
  9231. * @return {BABYLON.Node[]} all children nodes of all types.
  9232. */
  9233. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9234. var results = [];
  9235. this._getDescendants(results, directDescendantsOnly, predicate);
  9236. return results;
  9237. };
  9238. /**
  9239. * @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.
  9240. * @Deprecated, legacy support.
  9241. * use getDecendants instead.
  9242. */
  9243. Node.prototype.getChildren = function (predicate) {
  9244. return this.getDescendants(true, predicate);
  9245. };
  9246. /**
  9247. * Get all child-meshes of this node.
  9248. */
  9249. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9250. var results = [];
  9251. this._getDescendants(results, directDecendantsOnly, function (node) {
  9252. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9253. });
  9254. return results;
  9255. };
  9256. Node.prototype._setReady = function (state) {
  9257. if (state === this._isReady) {
  9258. return;
  9259. }
  9260. if (!state) {
  9261. this._isReady = false;
  9262. return;
  9263. }
  9264. this._isReady = true;
  9265. if (this.onReady) {
  9266. this.onReady(this);
  9267. }
  9268. };
  9269. Node.prototype.getAnimationByName = function (name) {
  9270. for (var i = 0; i < this.animations.length; i++) {
  9271. var animation = this.animations[i];
  9272. if (animation.name === name) {
  9273. return animation;
  9274. }
  9275. }
  9276. return null;
  9277. };
  9278. Node.prototype.createAnimationRange = function (name, from, to) {
  9279. // check name not already in use
  9280. if (!this._ranges[name]) {
  9281. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9282. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9283. if (this.animations[i]) {
  9284. this.animations[i].createRange(name, from, to);
  9285. }
  9286. }
  9287. }
  9288. };
  9289. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9290. if (deleteFrames === void 0) { deleteFrames = true; }
  9291. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9292. if (this.animations[i]) {
  9293. this.animations[i].deleteRange(name, deleteFrames);
  9294. }
  9295. }
  9296. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9297. };
  9298. Node.prototype.getAnimationRange = function (name) {
  9299. return this._ranges[name];
  9300. };
  9301. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9302. var range = this.getAnimationRange(name);
  9303. if (!range) {
  9304. return null;
  9305. }
  9306. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9307. };
  9308. Node.prototype.serializeAnimationRanges = function () {
  9309. var serializationRanges = [];
  9310. for (var name in this._ranges) {
  9311. var range = {};
  9312. range.name = name;
  9313. range.from = this._ranges[name].from;
  9314. range.to = this._ranges[name].to;
  9315. serializationRanges.push(range);
  9316. }
  9317. return serializationRanges;
  9318. };
  9319. Node.prototype.dispose = function () {
  9320. this.parent = null;
  9321. // Callback
  9322. this.onDisposeObservable.notifyObservers(this);
  9323. this.onDisposeObservable.clear();
  9324. };
  9325. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9326. if (parsedNode.ranges) {
  9327. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9328. var data = parsedNode.ranges[index];
  9329. node.createAnimationRange(data.name, data.from, data.to);
  9330. }
  9331. }
  9332. };
  9333. __decorate([
  9334. BABYLON.serialize()
  9335. ], Node.prototype, "name", void 0);
  9336. __decorate([
  9337. BABYLON.serialize()
  9338. ], Node.prototype, "id", void 0);
  9339. __decorate([
  9340. BABYLON.serialize()
  9341. ], Node.prototype, "uniqueId", void 0);
  9342. __decorate([
  9343. BABYLON.serialize()
  9344. ], Node.prototype, "state", void 0);
  9345. __decorate([
  9346. BABYLON.serialize()
  9347. ], Node.prototype, "metadata", void 0);
  9348. return Node;
  9349. }());
  9350. BABYLON.Node = Node;
  9351. })(BABYLON || (BABYLON = {}));
  9352. //# sourceMappingURL=babylon.node.js.map
  9353. var BABYLON;
  9354. (function (BABYLON) {
  9355. var FilesInput = (function () {
  9356. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9357. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9358. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9359. this._engine = p_engine;
  9360. this._canvas = p_canvas;
  9361. this._currentScene = p_scene;
  9362. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9363. this._progressCallback = p_progressCallback;
  9364. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9365. this._textureLoadingCallback = p_textureLoadingCallback;
  9366. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9367. }
  9368. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9369. var _this = this;
  9370. if (p_elementToMonitor) {
  9371. this._elementToMonitor = p_elementToMonitor;
  9372. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9373. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9374. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9375. }
  9376. };
  9377. FilesInput.prototype.renderFunction = function () {
  9378. if (this._additionnalRenderLoopLogicCallback) {
  9379. this._additionnalRenderLoopLogicCallback();
  9380. }
  9381. if (this._currentScene) {
  9382. if (this._textureLoadingCallback) {
  9383. var remaining = this._currentScene.getWaitingItemsCount();
  9384. if (remaining > 0) {
  9385. this._textureLoadingCallback(remaining);
  9386. }
  9387. }
  9388. this._currentScene.render();
  9389. }
  9390. };
  9391. FilesInput.prototype.drag = function (e) {
  9392. e.stopPropagation();
  9393. e.preventDefault();
  9394. };
  9395. FilesInput.prototype.drop = function (eventDrop) {
  9396. eventDrop.stopPropagation();
  9397. eventDrop.preventDefault();
  9398. this.loadFiles(eventDrop);
  9399. };
  9400. FilesInput.prototype.loadFiles = function (event) {
  9401. if (this._startingProcessingFilesCallback)
  9402. this._startingProcessingFilesCallback();
  9403. // Handling data transfer via drag'n'drop
  9404. if (event && event.dataTransfer && event.dataTransfer.files) {
  9405. this._filesToLoad = event.dataTransfer.files;
  9406. }
  9407. // Handling files from input files
  9408. if (event && event.target && event.target.files) {
  9409. this._filesToLoad = event.target.files;
  9410. }
  9411. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9412. for (var i = 0; i < this._filesToLoad.length; i++) {
  9413. switch (this._filesToLoad[i].type) {
  9414. case "image/jpeg":
  9415. case "image/png":
  9416. case "image/bmp":
  9417. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9418. break;
  9419. case "image/targa":
  9420. case "image/vnd.ms-dds":
  9421. case "audio/wav":
  9422. case "audio/x-wav":
  9423. case "audio/mp3":
  9424. case "audio/mpeg":
  9425. case "audio/mpeg3":
  9426. case "audio/x-mpeg-3":
  9427. case "audio/ogg":
  9428. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9429. break;
  9430. default:
  9431. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  9432. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9433. }
  9434. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  9435. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  9436. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9437. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9438. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9439. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9440. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9441. this._sceneFileToLoad = this._filesToLoad[i];
  9442. }
  9443. break;
  9444. }
  9445. }
  9446. this.reload();
  9447. }
  9448. };
  9449. FilesInput.prototype.reload = function () {
  9450. var _this = this;
  9451. var that = this;
  9452. // If a ".babylon" file has been provided
  9453. if (this._sceneFileToLoad) {
  9454. if (this._currentScene) {
  9455. if (BABYLON.Tools.errorsCount > 0) {
  9456. BABYLON.Tools.ClearLogCache();
  9457. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9458. }
  9459. this._engine.stopRenderLoop();
  9460. this._currentScene.dispose();
  9461. }
  9462. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9463. that._currentScene = newScene;
  9464. // Wait for textures and shaders to be ready
  9465. that._currentScene.executeWhenReady(function () {
  9466. // Attach camera to canvas inputs
  9467. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9468. that._currentScene.createDefaultCameraOrLight();
  9469. }
  9470. that._currentScene.activeCamera.attachControl(that._canvas);
  9471. if (that._sceneLoadedCallback) {
  9472. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9473. }
  9474. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9475. });
  9476. }, function (progress) {
  9477. if (_this._progressCallback) {
  9478. _this._progressCallback(progress);
  9479. }
  9480. });
  9481. }
  9482. else {
  9483. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9484. }
  9485. };
  9486. FilesInput.FilesTextures = new Array();
  9487. FilesInput.FilesToLoad = new Array();
  9488. return FilesInput;
  9489. }());
  9490. BABYLON.FilesInput = FilesInput;
  9491. })(BABYLON || (BABYLON = {}));
  9492. //# sourceMappingURL=../Tools/babylon.filesInput.js.map
  9493. var BABYLON;
  9494. (function (BABYLON) {
  9495. var IntersectionInfo = (function () {
  9496. function IntersectionInfo(bu, bv, distance) {
  9497. this.bu = bu;
  9498. this.bv = bv;
  9499. this.distance = distance;
  9500. this.faceId = 0;
  9501. this.subMeshId = 0;
  9502. }
  9503. return IntersectionInfo;
  9504. }());
  9505. BABYLON.IntersectionInfo = IntersectionInfo;
  9506. var PickingInfo = (function () {
  9507. function PickingInfo() {
  9508. this.hit = false;
  9509. this.distance = 0;
  9510. this.pickedPoint = null;
  9511. this.pickedMesh = null;
  9512. this.bu = 0;
  9513. this.bv = 0;
  9514. this.faceId = -1;
  9515. this.subMeshId = 0;
  9516. this.pickedSprite = null;
  9517. }
  9518. // Methods
  9519. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9520. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9521. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9522. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9523. return null;
  9524. }
  9525. var indices = this.pickedMesh.getIndices();
  9526. var result;
  9527. if (useVerticesNormals) {
  9528. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9529. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9530. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9531. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9532. normal0 = normal0.scale(this.bu);
  9533. normal1 = normal1.scale(this.bv);
  9534. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9535. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9536. }
  9537. else {
  9538. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9539. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9540. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9541. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9542. var p1p2 = vertex1.subtract(vertex2);
  9543. var p3p2 = vertex3.subtract(vertex2);
  9544. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9545. }
  9546. if (useWorldCoordinates) {
  9547. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9548. }
  9549. return BABYLON.Vector3.Normalize(result);
  9550. };
  9551. PickingInfo.prototype.getTextureCoordinates = function () {
  9552. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9553. return null;
  9554. }
  9555. var indices = this.pickedMesh.getIndices();
  9556. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9557. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9558. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9559. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9560. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9561. uv1 = uv1.scale(this.bu);
  9562. uv2 = uv2.scale(this.bv);
  9563. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9564. };
  9565. return PickingInfo;
  9566. }());
  9567. BABYLON.PickingInfo = PickingInfo;
  9568. })(BABYLON || (BABYLON = {}));
  9569. //# sourceMappingURL=../Collisions/babylon.pickingInfo.js.map
  9570. var BABYLON;
  9571. (function (BABYLON) {
  9572. var BoundingSphere = (function () {
  9573. function BoundingSphere(minimum, maximum) {
  9574. this.minimum = minimum;
  9575. this.maximum = maximum;
  9576. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9577. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9578. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9579. this.radius = distance * 0.5;
  9580. this.centerWorld = BABYLON.Vector3.Zero();
  9581. this._update(BABYLON.Matrix.Identity());
  9582. }
  9583. // Methods
  9584. BoundingSphere.prototype._update = function (world) {
  9585. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9586. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9587. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9588. };
  9589. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9590. for (var i = 0; i < 6; i++) {
  9591. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9592. return false;
  9593. }
  9594. return true;
  9595. };
  9596. BoundingSphere.prototype.intersectsPoint = function (point) {
  9597. var x = this.centerWorld.x - point.x;
  9598. var y = this.centerWorld.y - point.y;
  9599. var z = this.centerWorld.z - point.z;
  9600. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9601. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9602. return false;
  9603. return true;
  9604. };
  9605. // Statics
  9606. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9607. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9608. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9609. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9610. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9611. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9612. return false;
  9613. return true;
  9614. };
  9615. return BoundingSphere;
  9616. }());
  9617. BABYLON.BoundingSphere = BoundingSphere;
  9618. })(BABYLON || (BABYLON = {}));
  9619. //# sourceMappingURL=../Culling/babylon.boundingSphere.js.map
  9620. var BABYLON;
  9621. (function (BABYLON) {
  9622. var BoundingBox = (function () {
  9623. function BoundingBox(minimum, maximum) {
  9624. this.minimum = minimum;
  9625. this.maximum = maximum;
  9626. this.vectors = new Array();
  9627. this.vectorsWorld = new Array();
  9628. // Bounding vectors
  9629. this.vectors.push(this.minimum.clone());
  9630. this.vectors.push(this.maximum.clone());
  9631. this.vectors.push(this.minimum.clone());
  9632. this.vectors[2].x = this.maximum.x;
  9633. this.vectors.push(this.minimum.clone());
  9634. this.vectors[3].y = this.maximum.y;
  9635. this.vectors.push(this.minimum.clone());
  9636. this.vectors[4].z = this.maximum.z;
  9637. this.vectors.push(this.maximum.clone());
  9638. this.vectors[5].z = this.minimum.z;
  9639. this.vectors.push(this.maximum.clone());
  9640. this.vectors[6].x = this.minimum.x;
  9641. this.vectors.push(this.maximum.clone());
  9642. this.vectors[7].y = this.minimum.y;
  9643. // OBB
  9644. this.center = this.maximum.add(this.minimum).scale(0.5);
  9645. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9646. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9647. // World
  9648. for (var index = 0; index < this.vectors.length; index++) {
  9649. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9650. }
  9651. this.minimumWorld = BABYLON.Vector3.Zero();
  9652. this.maximumWorld = BABYLON.Vector3.Zero();
  9653. this._update(BABYLON.Matrix.Identity());
  9654. }
  9655. // Methods
  9656. BoundingBox.prototype.getWorldMatrix = function () {
  9657. return this._worldMatrix;
  9658. };
  9659. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9660. this._worldMatrix.copyFrom(matrix);
  9661. return this;
  9662. };
  9663. BoundingBox.prototype._update = function (world) {
  9664. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9665. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9666. for (var index = 0; index < this.vectors.length; index++) {
  9667. var v = this.vectorsWorld[index];
  9668. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9669. if (v.x < this.minimumWorld.x)
  9670. this.minimumWorld.x = v.x;
  9671. if (v.y < this.minimumWorld.y)
  9672. this.minimumWorld.y = v.y;
  9673. if (v.z < this.minimumWorld.z)
  9674. this.minimumWorld.z = v.z;
  9675. if (v.x > this.maximumWorld.x)
  9676. this.maximumWorld.x = v.x;
  9677. if (v.y > this.maximumWorld.y)
  9678. this.maximumWorld.y = v.y;
  9679. if (v.z > this.maximumWorld.z)
  9680. this.maximumWorld.z = v.z;
  9681. }
  9682. // OBB
  9683. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9684. this.center.scaleInPlace(0.5);
  9685. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9686. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9687. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9688. this._worldMatrix = world;
  9689. };
  9690. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9691. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9692. };
  9693. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9694. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9695. };
  9696. BoundingBox.prototype.intersectsPoint = function (point) {
  9697. var delta = -BABYLON.Epsilon;
  9698. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9699. return false;
  9700. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9701. return false;
  9702. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9703. return false;
  9704. return true;
  9705. };
  9706. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9707. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9708. };
  9709. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9710. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9711. return false;
  9712. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9713. return false;
  9714. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9715. return false;
  9716. return true;
  9717. };
  9718. // Statics
  9719. BoundingBox.Intersects = function (box0, box1) {
  9720. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9721. return false;
  9722. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9723. return false;
  9724. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9725. return false;
  9726. return true;
  9727. };
  9728. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9729. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9730. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9731. return (num <= (sphereRadius * sphereRadius));
  9732. };
  9733. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9734. for (var p = 0; p < 6; p++) {
  9735. for (var i = 0; i < 8; i++) {
  9736. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9737. return false;
  9738. }
  9739. }
  9740. }
  9741. return true;
  9742. };
  9743. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9744. for (var p = 0; p < 6; p++) {
  9745. var inCount = 8;
  9746. for (var i = 0; i < 8; i++) {
  9747. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9748. --inCount;
  9749. }
  9750. else {
  9751. break;
  9752. }
  9753. }
  9754. if (inCount === 0)
  9755. return false;
  9756. }
  9757. return true;
  9758. };
  9759. return BoundingBox;
  9760. }());
  9761. BABYLON.BoundingBox = BoundingBox;
  9762. })(BABYLON || (BABYLON = {}));
  9763. //# sourceMappingURL=../Culling/babylon.boundingBox.js.map
  9764. var BABYLON;
  9765. (function (BABYLON) {
  9766. var computeBoxExtents = function (axis, box) {
  9767. var p = BABYLON.Vector3.Dot(box.center, axis);
  9768. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9769. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9770. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9771. var r = r0 + r1 + r2;
  9772. return {
  9773. min: p - r,
  9774. max: p + r
  9775. };
  9776. };
  9777. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9778. var axisOverlap = function (axis, box0, box1) {
  9779. var result0 = computeBoxExtents(axis, box0);
  9780. var result1 = computeBoxExtents(axis, box1);
  9781. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9782. };
  9783. var BoundingInfo = (function () {
  9784. function BoundingInfo(minimum, maximum) {
  9785. this.minimum = minimum;
  9786. this.maximum = maximum;
  9787. this._isLocked = false;
  9788. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9789. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9790. }
  9791. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9792. get: function () {
  9793. return this._isLocked;
  9794. },
  9795. set: function (value) {
  9796. this._isLocked = value;
  9797. },
  9798. enumerable: true,
  9799. configurable: true
  9800. });
  9801. // Methods
  9802. BoundingInfo.prototype.update = function (world) {
  9803. if (this._isLocked) {
  9804. return;
  9805. }
  9806. this.boundingBox._update(world);
  9807. this.boundingSphere._update(world);
  9808. };
  9809. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9810. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9811. return false;
  9812. return this.boundingBox.isInFrustum(frustumPlanes);
  9813. };
  9814. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9815. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9816. };
  9817. BoundingInfo.prototype._checkCollision = function (collider) {
  9818. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9819. };
  9820. BoundingInfo.prototype.intersectsPoint = function (point) {
  9821. if (!this.boundingSphere.centerWorld) {
  9822. return false;
  9823. }
  9824. if (!this.boundingSphere.intersectsPoint(point)) {
  9825. return false;
  9826. }
  9827. if (!this.boundingBox.intersectsPoint(point)) {
  9828. return false;
  9829. }
  9830. return true;
  9831. };
  9832. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9833. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9834. return false;
  9835. }
  9836. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9837. return false;
  9838. }
  9839. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9840. return false;
  9841. }
  9842. if (!precise) {
  9843. return true;
  9844. }
  9845. var box0 = this.boundingBox;
  9846. var box1 = boundingInfo.boundingBox;
  9847. if (!axisOverlap(box0.directions[0], box0, box1))
  9848. return false;
  9849. if (!axisOverlap(box0.directions[1], box0, box1))
  9850. return false;
  9851. if (!axisOverlap(box0.directions[2], box0, box1))
  9852. return false;
  9853. if (!axisOverlap(box1.directions[0], box0, box1))
  9854. return false;
  9855. if (!axisOverlap(box1.directions[1], box0, box1))
  9856. return false;
  9857. if (!axisOverlap(box1.directions[2], box0, box1))
  9858. return false;
  9859. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9860. return false;
  9861. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9862. return false;
  9863. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9864. return false;
  9865. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9866. return false;
  9867. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9868. return false;
  9869. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9870. return false;
  9871. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9872. return false;
  9873. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9874. return false;
  9875. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9876. return false;
  9877. return true;
  9878. };
  9879. return BoundingInfo;
  9880. }());
  9881. BABYLON.BoundingInfo = BoundingInfo;
  9882. })(BABYLON || (BABYLON = {}));
  9883. //# sourceMappingURL=../Culling/babylon.boundingInfo.js.map
  9884. var BABYLON;
  9885. (function (BABYLON) {
  9886. var Ray = (function () {
  9887. function Ray(origin, direction, length) {
  9888. if (length === void 0) { length = Number.MAX_VALUE; }
  9889. this.origin = origin;
  9890. this.direction = direction;
  9891. this.length = length;
  9892. this._show = false;
  9893. }
  9894. // Methods
  9895. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9896. var d = 0.0;
  9897. var maxValue = Number.MAX_VALUE;
  9898. var inv;
  9899. var min;
  9900. var max;
  9901. var temp;
  9902. if (Math.abs(this.direction.x) < 0.0000001) {
  9903. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9904. return false;
  9905. }
  9906. }
  9907. else {
  9908. inv = 1.0 / this.direction.x;
  9909. min = (minimum.x - this.origin.x) * inv;
  9910. max = (maximum.x - this.origin.x) * inv;
  9911. if (max === -Infinity) {
  9912. max = Infinity;
  9913. }
  9914. if (min > max) {
  9915. temp = min;
  9916. min = max;
  9917. max = temp;
  9918. }
  9919. d = Math.max(min, d);
  9920. maxValue = Math.min(max, maxValue);
  9921. if (d > maxValue) {
  9922. return false;
  9923. }
  9924. }
  9925. if (Math.abs(this.direction.y) < 0.0000001) {
  9926. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9927. return false;
  9928. }
  9929. }
  9930. else {
  9931. inv = 1.0 / this.direction.y;
  9932. min = (minimum.y - this.origin.y) * inv;
  9933. max = (maximum.y - this.origin.y) * inv;
  9934. if (max === -Infinity) {
  9935. max = Infinity;
  9936. }
  9937. if (min > max) {
  9938. temp = min;
  9939. min = max;
  9940. max = temp;
  9941. }
  9942. d = Math.max(min, d);
  9943. maxValue = Math.min(max, maxValue);
  9944. if (d > maxValue) {
  9945. return false;
  9946. }
  9947. }
  9948. if (Math.abs(this.direction.z) < 0.0000001) {
  9949. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9950. return false;
  9951. }
  9952. }
  9953. else {
  9954. inv = 1.0 / this.direction.z;
  9955. min = (minimum.z - this.origin.z) * inv;
  9956. max = (maximum.z - this.origin.z) * inv;
  9957. if (max === -Infinity) {
  9958. max = Infinity;
  9959. }
  9960. if (min > max) {
  9961. temp = min;
  9962. min = max;
  9963. max = temp;
  9964. }
  9965. d = Math.max(min, d);
  9966. maxValue = Math.min(max, maxValue);
  9967. if (d > maxValue) {
  9968. return false;
  9969. }
  9970. }
  9971. return true;
  9972. };
  9973. Ray.prototype.intersectsBox = function (box) {
  9974. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9975. };
  9976. Ray.prototype.intersectsSphere = function (sphere) {
  9977. var x = sphere.center.x - this.origin.x;
  9978. var y = sphere.center.y - this.origin.y;
  9979. var z = sphere.center.z - this.origin.z;
  9980. var pyth = (x * x) + (y * y) + (z * z);
  9981. var rr = sphere.radius * sphere.radius;
  9982. if (pyth <= rr) {
  9983. return true;
  9984. }
  9985. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9986. if (dot < 0.0) {
  9987. return false;
  9988. }
  9989. var temp = pyth - (dot * dot);
  9990. return temp <= rr;
  9991. };
  9992. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9993. if (!this._edge1) {
  9994. this._edge1 = BABYLON.Vector3.Zero();
  9995. this._edge2 = BABYLON.Vector3.Zero();
  9996. this._pvec = BABYLON.Vector3.Zero();
  9997. this._tvec = BABYLON.Vector3.Zero();
  9998. this._qvec = BABYLON.Vector3.Zero();
  9999. }
  10000. vertex1.subtractToRef(vertex0, this._edge1);
  10001. vertex2.subtractToRef(vertex0, this._edge2);
  10002. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  10003. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  10004. if (det === 0) {
  10005. return null;
  10006. }
  10007. var invdet = 1 / det;
  10008. this.origin.subtractToRef(vertex0, this._tvec);
  10009. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  10010. if (bu < 0 || bu > 1.0) {
  10011. return null;
  10012. }
  10013. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  10014. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  10015. if (bv < 0 || bu + bv > 1.0) {
  10016. return null;
  10017. }
  10018. //check if the distance is longer than the predefined length.
  10019. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  10020. if (distance > this.length) {
  10021. return null;
  10022. }
  10023. return new BABYLON.IntersectionInfo(bu, bv, distance);
  10024. };
  10025. Ray.prototype.intersectsPlane = function (plane) {
  10026. var distance;
  10027. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  10028. if (Math.abs(result1) < 9.99999997475243E-07) {
  10029. return null;
  10030. }
  10031. else {
  10032. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  10033. distance = (-plane.d - result2) / result1;
  10034. if (distance < 0.0) {
  10035. if (distance < -9.99999997475243E-07) {
  10036. return null;
  10037. }
  10038. else {
  10039. return 0;
  10040. }
  10041. }
  10042. return distance;
  10043. }
  10044. };
  10045. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  10046. var tm = BABYLON.Tmp.Matrix[0];
  10047. mesh.getWorldMatrix().invertToRef(tm);
  10048. var ray = Ray.Transform(this, tm);
  10049. return mesh.intersects(ray, fastCheck);
  10050. };
  10051. Ray.prototype.show = function (scene, color) {
  10052. this._renderFunction = this._render.bind(this);
  10053. this._show = true;
  10054. this._scene = scene;
  10055. this._renderPoints = [this.origin, this.origin.add(this.direction.scale(this.length))];
  10056. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  10057. if (color) {
  10058. this._renderLine.color.copyFrom(color);
  10059. }
  10060. this._scene.registerBeforeRender(this._renderFunction);
  10061. };
  10062. Ray.prototype.hide = function () {
  10063. if (this._show) {
  10064. this._show = false;
  10065. this._scene.unregisterBeforeRender(this._renderFunction);
  10066. }
  10067. if (this._renderLine) {
  10068. this._renderLine.dispose();
  10069. this._renderLine = null;
  10070. this._renderPoints = null;
  10071. }
  10072. };
  10073. Ray.prototype._render = function () {
  10074. var point = this._renderPoints[1];
  10075. point.copyFrom(this.direction);
  10076. point.scaleInPlace(this.length);
  10077. point.addInPlace(this.origin);
  10078. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  10079. };
  10080. /**
  10081. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  10082. * @param sega the first point of the segment to test the intersection against
  10083. * @param segb the second point of the segment to test the intersection against
  10084. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  10085. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  10086. */
  10087. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  10088. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  10089. var u = segb.subtract(sega);
  10090. var v = rsegb.subtract(this.origin);
  10091. var w = sega.subtract(this.origin);
  10092. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  10093. var b = BABYLON.Vector3.Dot(u, v);
  10094. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  10095. var d = BABYLON.Vector3.Dot(u, w);
  10096. var e = BABYLON.Vector3.Dot(v, w);
  10097. var D = a * c - b * b; // always >= 0
  10098. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  10099. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  10100. // compute the line parameters of the two closest points
  10101. if (D < Ray.smallnum) {
  10102. sN = 0.0; // force using point P0 on segment S1
  10103. sD = 1.0; // to prevent possible division by 0.0 later
  10104. tN = e;
  10105. tD = c;
  10106. }
  10107. else {
  10108. sN = (b * e - c * d);
  10109. tN = (a * e - b * d);
  10110. if (sN < 0.0) {
  10111. sN = 0.0;
  10112. tN = e;
  10113. tD = c;
  10114. }
  10115. else if (sN > sD) {
  10116. sN = sD;
  10117. tN = e + b;
  10118. tD = c;
  10119. }
  10120. }
  10121. if (tN < 0.0) {
  10122. tN = 0.0;
  10123. // recompute sc for this edge
  10124. if (-d < 0.0) {
  10125. sN = 0.0;
  10126. }
  10127. else if (-d > a)
  10128. sN = sD;
  10129. else {
  10130. sN = -d;
  10131. sD = a;
  10132. }
  10133. }
  10134. else if (tN > tD) {
  10135. tN = tD;
  10136. // recompute sc for this edge
  10137. if ((-d + b) < 0.0) {
  10138. sN = 0;
  10139. }
  10140. else if ((-d + b) > a) {
  10141. sN = sD;
  10142. }
  10143. else {
  10144. sN = (-d + b);
  10145. sD = a;
  10146. }
  10147. }
  10148. // finally do the division to get sc and tc
  10149. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  10150. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  10151. // get the difference of the two closest points
  10152. var qtc = v.multiplyByFloats(tc, tc, tc);
  10153. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  10154. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  10155. if (isIntersected) {
  10156. return qtc.length();
  10157. }
  10158. return -1;
  10159. };
  10160. // Statics
  10161. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  10162. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  10163. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  10164. var direction = end.subtract(start);
  10165. direction.normalize();
  10166. return new Ray(start, direction);
  10167. };
  10168. /**
  10169. * 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
  10170. * transformed to the given world matrix.
  10171. * @param origin The origin point
  10172. * @param end The end point
  10173. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10174. */
  10175. Ray.CreateNewFromTo = function (origin, end, world) {
  10176. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10177. var direction = end.subtract(origin);
  10178. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10179. direction.normalize();
  10180. return Ray.Transform(new Ray(origin, direction, length), world);
  10181. };
  10182. Ray.Transform = function (ray, matrix) {
  10183. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10184. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10185. newDirection.normalize();
  10186. return new Ray(newOrigin, newDirection, ray.length);
  10187. };
  10188. Ray.smallnum = 0.00000001;
  10189. Ray.rayl = 10e8;
  10190. return Ray;
  10191. }());
  10192. BABYLON.Ray = Ray;
  10193. })(BABYLON || (BABYLON = {}));
  10194. //# sourceMappingURL=../Culling/babylon.ray.js.map
  10195. var BABYLON;
  10196. (function (BABYLON) {
  10197. var AbstractMesh = (function (_super) {
  10198. __extends(AbstractMesh, _super);
  10199. // Constructor
  10200. function AbstractMesh(name, scene) {
  10201. var _this = this;
  10202. _super.call(this, name, scene);
  10203. // Events
  10204. /**
  10205. * An event triggered when this mesh collides with another one
  10206. * @type {BABYLON.Observable}
  10207. */
  10208. this.onCollideObservable = new BABYLON.Observable();
  10209. /**
  10210. * An event triggered when the collision's position changes
  10211. * @type {BABYLON.Observable}
  10212. */
  10213. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10214. /**
  10215. * An event triggered after the world matrix is updated
  10216. * @type {BABYLON.Observable}
  10217. */
  10218. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10219. // Properties
  10220. this.definedFacingForward = true; // orientation for POV movement & rotation
  10221. this.position = new BABYLON.Vector3(0, 0, 0);
  10222. this._rotation = new BABYLON.Vector3(0, 0, 0);
  10223. this._scaling = new BABYLON.Vector3(1, 1, 1);
  10224. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10225. this.visibility = 1.0;
  10226. this.alphaIndex = Number.MAX_VALUE;
  10227. this.infiniteDistance = false;
  10228. this.isVisible = true;
  10229. this.isPickable = true;
  10230. this.showBoundingBox = false;
  10231. this.showSubMeshesBoundingBox = false;
  10232. this.isBlocker = false;
  10233. this.renderingGroupId = 0;
  10234. this.receiveShadows = false;
  10235. this.renderOutline = false;
  10236. this.outlineColor = BABYLON.Color3.Red();
  10237. this.outlineWidth = 0.02;
  10238. this.renderOverlay = false;
  10239. this.overlayColor = BABYLON.Color3.Red();
  10240. this.overlayAlpha = 0.5;
  10241. this.hasVertexAlpha = false;
  10242. this.useVertexColors = true;
  10243. this.applyFog = true;
  10244. this.computeBonesUsingShaders = true;
  10245. this.scalingDeterminant = 1;
  10246. this.numBoneInfluencers = 4;
  10247. this.useOctreeForRenderingSelection = true;
  10248. this.useOctreeForPicking = true;
  10249. this.useOctreeForCollisions = true;
  10250. this.layerMask = 0x0FFFFFFF;
  10251. this.alwaysSelectAsActiveMesh = false;
  10252. // Collisions
  10253. this._checkCollisions = false;
  10254. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10255. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10256. this._collider = new BABYLON.Collider();
  10257. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10258. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10259. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10260. // Edges
  10261. this.edgesWidth = 1;
  10262. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10263. // Cache
  10264. this._localWorld = BABYLON.Matrix.Zero();
  10265. this._worldMatrix = BABYLON.Matrix.Zero();
  10266. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10267. this._absolutePosition = BABYLON.Vector3.Zero();
  10268. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10269. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10270. this._isDirty = false;
  10271. this._pivotMatrix = BABYLON.Matrix.Identity();
  10272. this._isDisposed = false;
  10273. this._renderId = 0;
  10274. this._intersectionsInProgress = new Array();
  10275. this._isWorldMatrixFrozen = false;
  10276. this._unIndexed = false;
  10277. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10278. if (collidedMesh === void 0) { collidedMesh = null; }
  10279. //TODO move this to the collision coordinator!
  10280. if (_this.getScene().workerCollisions)
  10281. newPosition.multiplyInPlace(_this._collider.radius);
  10282. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10283. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10284. _this.position.addInPlace(_this._diffPositionForCollisions);
  10285. }
  10286. if (collidedMesh) {
  10287. _this.onCollideObservable.notifyObservers(collidedMesh);
  10288. }
  10289. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10290. };
  10291. scene.addMesh(this);
  10292. }
  10293. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10294. get: function () {
  10295. return AbstractMesh._BILLBOARDMODE_NONE;
  10296. },
  10297. enumerable: true,
  10298. configurable: true
  10299. });
  10300. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10301. get: function () {
  10302. return AbstractMesh._BILLBOARDMODE_X;
  10303. },
  10304. enumerable: true,
  10305. configurable: true
  10306. });
  10307. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10308. get: function () {
  10309. return AbstractMesh._BILLBOARDMODE_Y;
  10310. },
  10311. enumerable: true,
  10312. configurable: true
  10313. });
  10314. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10315. get: function () {
  10316. return AbstractMesh._BILLBOARDMODE_Z;
  10317. },
  10318. enumerable: true,
  10319. configurable: true
  10320. });
  10321. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10322. get: function () {
  10323. return AbstractMesh._BILLBOARDMODE_ALL;
  10324. },
  10325. enumerable: true,
  10326. configurable: true
  10327. });
  10328. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10329. set: function (callback) {
  10330. if (this._onCollideObserver) {
  10331. this.onCollideObservable.remove(this._onCollideObserver);
  10332. }
  10333. this._onCollideObserver = this.onCollideObservable.add(callback);
  10334. },
  10335. enumerable: true,
  10336. configurable: true
  10337. });
  10338. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10339. set: function (callback) {
  10340. if (this._onCollisionPositionChangeObserver) {
  10341. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10342. }
  10343. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10344. },
  10345. enumerable: true,
  10346. configurable: true
  10347. });
  10348. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10349. get: function () {
  10350. return this._skeleton;
  10351. },
  10352. set: function (value) {
  10353. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10354. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10355. }
  10356. if (value && value.needInitialSkinMatrix) {
  10357. value._registerMeshWithPoseMatrix(this);
  10358. }
  10359. this._skeleton = value;
  10360. if (!this._skeleton) {
  10361. this._bonesTransformMatrices = null;
  10362. }
  10363. },
  10364. enumerable: true,
  10365. configurable: true
  10366. });
  10367. /**
  10368. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10369. */
  10370. AbstractMesh.prototype.toString = function (fullDetails) {
  10371. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10372. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10373. if (this._skeleton) {
  10374. ret += ", skeleton: " + this._skeleton.name;
  10375. }
  10376. if (fullDetails) {
  10377. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10378. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10379. }
  10380. return ret;
  10381. };
  10382. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10383. /**
  10384. * Getting the rotation object.
  10385. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10386. */
  10387. get: function () {
  10388. return this._rotation;
  10389. },
  10390. set: function (newRotation) {
  10391. this._rotation = newRotation;
  10392. },
  10393. enumerable: true,
  10394. configurable: true
  10395. });
  10396. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10397. get: function () {
  10398. return this._scaling;
  10399. },
  10400. set: function (newScaling) {
  10401. this._scaling = newScaling;
  10402. if (this.physicsImpostor) {
  10403. this.physicsImpostor.forceUpdate();
  10404. }
  10405. },
  10406. enumerable: true,
  10407. configurable: true
  10408. });
  10409. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10410. get: function () {
  10411. return this._rotationQuaternion;
  10412. },
  10413. set: function (quaternion) {
  10414. this._rotationQuaternion = quaternion;
  10415. //reset the rotation vector.
  10416. if (quaternion && this.rotation.length()) {
  10417. this.rotation.copyFromFloats(0, 0, 0);
  10418. }
  10419. },
  10420. enumerable: true,
  10421. configurable: true
  10422. });
  10423. // Methods
  10424. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10425. this._poseMatrix.copyFrom(matrix);
  10426. };
  10427. AbstractMesh.prototype.getPoseMatrix = function () {
  10428. return this._poseMatrix;
  10429. };
  10430. AbstractMesh.prototype.disableEdgesRendering = function () {
  10431. if (this._edgesRenderer !== undefined) {
  10432. this._edgesRenderer.dispose();
  10433. this._edgesRenderer = undefined;
  10434. }
  10435. };
  10436. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10437. if (epsilon === void 0) { epsilon = 0.95; }
  10438. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10439. this.disableEdgesRendering();
  10440. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10441. };
  10442. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10443. get: function () {
  10444. return false;
  10445. },
  10446. enumerable: true,
  10447. configurable: true
  10448. });
  10449. AbstractMesh.prototype.getLOD = function (camera) {
  10450. return this;
  10451. };
  10452. AbstractMesh.prototype.getTotalVertices = function () {
  10453. return 0;
  10454. };
  10455. AbstractMesh.prototype.getIndices = function () {
  10456. return null;
  10457. };
  10458. AbstractMesh.prototype.getVerticesData = function (kind) {
  10459. return null;
  10460. };
  10461. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10462. return false;
  10463. };
  10464. AbstractMesh.prototype.getBoundingInfo = function () {
  10465. if (this._masterMesh) {
  10466. return this._masterMesh.getBoundingInfo();
  10467. }
  10468. if (!this._boundingInfo) {
  10469. this._updateBoundingInfo();
  10470. }
  10471. return this._boundingInfo;
  10472. };
  10473. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10474. this._boundingInfo = boundingInfo;
  10475. };
  10476. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10477. get: function () {
  10478. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10479. },
  10480. enumerable: true,
  10481. configurable: true
  10482. });
  10483. AbstractMesh.prototype._preActivate = function () {
  10484. };
  10485. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10486. };
  10487. AbstractMesh.prototype._activate = function (renderId) {
  10488. this._renderId = renderId;
  10489. };
  10490. AbstractMesh.prototype.getWorldMatrix = function () {
  10491. if (this._masterMesh) {
  10492. return this._masterMesh.getWorldMatrix();
  10493. }
  10494. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10495. this.computeWorldMatrix();
  10496. }
  10497. return this._worldMatrix;
  10498. };
  10499. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10500. get: function () {
  10501. return this._worldMatrix;
  10502. },
  10503. enumerable: true,
  10504. configurable: true
  10505. });
  10506. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10507. get: function () {
  10508. return this._absolutePosition;
  10509. },
  10510. enumerable: true,
  10511. configurable: true
  10512. });
  10513. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10514. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10515. this.computeWorldMatrix(true);
  10516. this._isWorldMatrixFrozen = true;
  10517. };
  10518. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10519. this._isWorldMatrixFrozen = false;
  10520. this.computeWorldMatrix(true);
  10521. };
  10522. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10523. get: function () {
  10524. return this._isWorldMatrixFrozen;
  10525. },
  10526. enumerable: true,
  10527. configurable: true
  10528. });
  10529. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10530. axis.normalize();
  10531. if (!this.rotationQuaternion) {
  10532. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10533. this.rotation = BABYLON.Vector3.Zero();
  10534. }
  10535. var rotationQuaternion;
  10536. if (!space || space === BABYLON.Space.LOCAL) {
  10537. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10538. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10539. }
  10540. else {
  10541. if (this.parent) {
  10542. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10543. invertParentWorldMatrix.invert();
  10544. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10545. }
  10546. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10547. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10548. }
  10549. };
  10550. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10551. var displacementVector = axis.scale(distance);
  10552. if (!space || space === BABYLON.Space.LOCAL) {
  10553. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10554. this.setPositionWithLocalVector(tempV3);
  10555. }
  10556. else {
  10557. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10558. }
  10559. };
  10560. AbstractMesh.prototype.getAbsolutePosition = function () {
  10561. this.computeWorldMatrix();
  10562. return this._absolutePosition;
  10563. };
  10564. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10565. if (!absolutePosition) {
  10566. return;
  10567. }
  10568. var absolutePositionX;
  10569. var absolutePositionY;
  10570. var absolutePositionZ;
  10571. if (absolutePosition.x === undefined) {
  10572. if (arguments.length < 3) {
  10573. return;
  10574. }
  10575. absolutePositionX = arguments[0];
  10576. absolutePositionY = arguments[1];
  10577. absolutePositionZ = arguments[2];
  10578. }
  10579. else {
  10580. absolutePositionX = absolutePosition.x;
  10581. absolutePositionY = absolutePosition.y;
  10582. absolutePositionZ = absolutePosition.z;
  10583. }
  10584. if (this.parent) {
  10585. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10586. invertParentWorldMatrix.invert();
  10587. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10588. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10589. }
  10590. else {
  10591. this.position.x = absolutePositionX;
  10592. this.position.y = absolutePositionY;
  10593. this.position.z = absolutePositionZ;
  10594. }
  10595. };
  10596. // ================================== Point of View Movement =================================
  10597. /**
  10598. * Perform relative position change from the point of view of behind the front of the mesh.
  10599. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10600. * Supports definition of mesh facing forward or backward.
  10601. * @param {number} amountRight
  10602. * @param {number} amountUp
  10603. * @param {number} amountForward
  10604. */
  10605. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10606. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10607. };
  10608. /**
  10609. * Calculate relative position change from the point of view of behind the front of the mesh.
  10610. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10611. * Supports definition of mesh facing forward or backward.
  10612. * @param {number} amountRight
  10613. * @param {number} amountUp
  10614. * @param {number} amountForward
  10615. */
  10616. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10617. var rotMatrix = new BABYLON.Matrix();
  10618. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10619. rotQuaternion.toRotationMatrix(rotMatrix);
  10620. var translationDelta = BABYLON.Vector3.Zero();
  10621. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10622. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10623. return translationDelta;
  10624. };
  10625. // ================================== Point of View Rotation =================================
  10626. /**
  10627. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10628. * Supports definition of mesh facing forward or backward.
  10629. * @param {number} flipBack
  10630. * @param {number} twirlClockwise
  10631. * @param {number} tiltRight
  10632. */
  10633. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10634. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10635. };
  10636. /**
  10637. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10638. * Supports definition of mesh facing forward or backward.
  10639. * @param {number} flipBack
  10640. * @param {number} twirlClockwise
  10641. * @param {number} tiltRight
  10642. */
  10643. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10644. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10645. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10646. };
  10647. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10648. this._pivotMatrix = matrix;
  10649. this._cache.pivotMatrixUpdated = true;
  10650. };
  10651. AbstractMesh.prototype.getPivotMatrix = function () {
  10652. return this._pivotMatrix;
  10653. };
  10654. AbstractMesh.prototype._isSynchronized = function () {
  10655. if (this._isDirty) {
  10656. return false;
  10657. }
  10658. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10659. return false;
  10660. if (this._cache.pivotMatrixUpdated) {
  10661. return false;
  10662. }
  10663. if (this.infiniteDistance) {
  10664. return false;
  10665. }
  10666. if (!this._cache.position.equals(this.position))
  10667. return false;
  10668. if (this.rotationQuaternion) {
  10669. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10670. return false;
  10671. }
  10672. if (!this._cache.rotation.equals(this.rotation))
  10673. return false;
  10674. if (!this._cache.scaling.equals(this.scaling))
  10675. return false;
  10676. return true;
  10677. };
  10678. AbstractMesh.prototype._initCache = function () {
  10679. _super.prototype._initCache.call(this);
  10680. this._cache.localMatrixUpdated = false;
  10681. this._cache.position = BABYLON.Vector3.Zero();
  10682. this._cache.scaling = BABYLON.Vector3.Zero();
  10683. this._cache.rotation = BABYLON.Vector3.Zero();
  10684. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10685. this._cache.billboardMode = -1;
  10686. };
  10687. AbstractMesh.prototype.markAsDirty = function (property) {
  10688. if (property === "rotation") {
  10689. this.rotationQuaternion = null;
  10690. }
  10691. this._currentRenderId = Number.MAX_VALUE;
  10692. this._isDirty = true;
  10693. };
  10694. AbstractMesh.prototype._updateBoundingInfo = function () {
  10695. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10696. this._boundingInfo.update(this.worldMatrixFromCache);
  10697. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10698. };
  10699. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10700. if (!this.subMeshes) {
  10701. return;
  10702. }
  10703. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10704. var subMesh = this.subMeshes[subIndex];
  10705. if (!subMesh.IsGlobal) {
  10706. subMesh.updateBoundingInfo(matrix);
  10707. }
  10708. }
  10709. };
  10710. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10711. if (this._isWorldMatrixFrozen) {
  10712. return this._worldMatrix;
  10713. }
  10714. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10715. this._currentRenderId = this.getScene().getRenderId();
  10716. return this._worldMatrix;
  10717. }
  10718. this._cache.position.copyFrom(this.position);
  10719. this._cache.scaling.copyFrom(this.scaling);
  10720. this._cache.pivotMatrixUpdated = false;
  10721. this._cache.billboardMode = this.billboardMode;
  10722. this._currentRenderId = this.getScene().getRenderId();
  10723. this._isDirty = false;
  10724. // Scaling
  10725. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10726. // Rotation
  10727. //rotate, if quaternion is set and rotation was used
  10728. if (this.rotationQuaternion) {
  10729. var len = this.rotation.length();
  10730. if (len) {
  10731. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10732. this.rotation.copyFromFloats(0, 0, 0);
  10733. }
  10734. }
  10735. if (this.rotationQuaternion) {
  10736. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10737. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10738. }
  10739. else {
  10740. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10741. this._cache.rotation.copyFrom(this.rotation);
  10742. }
  10743. // Translation
  10744. if (this.infiniteDistance && !this.parent) {
  10745. var camera = this.getScene().activeCamera;
  10746. if (camera) {
  10747. var cameraWorldMatrix = camera.getWorldMatrix();
  10748. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10749. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10750. }
  10751. }
  10752. else {
  10753. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10754. }
  10755. // Composing transformations
  10756. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10757. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10758. // Billboarding
  10759. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10760. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10761. var localPosition = BABYLON.Tmp.Vector3[0];
  10762. if (this.parent && this.parent.getWorldMatrix) {
  10763. this._markSyncedWithParent();
  10764. var parentMatrix;
  10765. if (this._meshToBoneReferal) {
  10766. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10767. parentMatrix = BABYLON.Tmp.Matrix[6];
  10768. }
  10769. else {
  10770. parentMatrix = this.parent.getWorldMatrix();
  10771. }
  10772. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10773. localPosition = BABYLON.Tmp.Vector3[1];
  10774. }
  10775. var zero = this.getScene().activeCamera.globalPosition.clone();
  10776. if (this.parent && this.parent.position) {
  10777. localPosition.addInPlace(this.parent.position);
  10778. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10779. }
  10780. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10781. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10782. zero.x = localPosition.x + BABYLON.Epsilon;
  10783. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10784. zero.y = localPosition.y + BABYLON.Epsilon;
  10785. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10786. zero.z = localPosition.z + BABYLON.Epsilon;
  10787. }
  10788. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10789. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10790. BABYLON.Tmp.Matrix[3].invert();
  10791. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10792. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10793. }
  10794. // Local world
  10795. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10796. // Parent
  10797. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10798. this._markSyncedWithParent();
  10799. if (this._meshToBoneReferal) {
  10800. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10801. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10802. }
  10803. else {
  10804. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10805. }
  10806. }
  10807. else {
  10808. this._worldMatrix.copyFrom(this._localWorld);
  10809. }
  10810. // Bounding info
  10811. this._updateBoundingInfo();
  10812. // Absolute position
  10813. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10814. // Callbacks
  10815. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10816. if (!this._poseMatrix) {
  10817. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10818. }
  10819. return this._worldMatrix;
  10820. };
  10821. /**
  10822. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10823. * @param func: callback function to add
  10824. */
  10825. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10826. this.onAfterWorldMatrixUpdateObservable.add(func);
  10827. };
  10828. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10829. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10830. };
  10831. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10832. this.computeWorldMatrix();
  10833. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10834. };
  10835. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10836. this.computeWorldMatrix();
  10837. var invLocalWorldMatrix = this._localWorld.clone();
  10838. invLocalWorldMatrix.invert();
  10839. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10840. };
  10841. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10842. this.computeWorldMatrix(true);
  10843. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10844. };
  10845. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10846. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10847. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10848. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10849. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10850. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10851. /// <returns>Mesh oriented towards targetMesh</returns>
  10852. if (yawCor === void 0) { yawCor = 0; }
  10853. if (pitchCor === void 0) { pitchCor = 0; }
  10854. if (rollCor === void 0) { rollCor = 0; }
  10855. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10856. var dv = AbstractMesh._lookAtVectorCache;
  10857. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10858. targetPoint.subtractToRef(pos, dv);
  10859. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10860. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10861. var pitch = Math.atan2(dv.y, len);
  10862. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10863. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10864. };
  10865. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10866. this._meshToBoneReferal = affectedMesh;
  10867. this.parent = bone;
  10868. if (bone.getWorldMatrix().determinant() < 0) {
  10869. this.scalingDeterminant *= -1;
  10870. }
  10871. };
  10872. AbstractMesh.prototype.detachFromBone = function () {
  10873. if (this.parent.getWorldMatrix().determinant() < 0) {
  10874. this.scalingDeterminant *= -1;
  10875. }
  10876. this._meshToBoneReferal = null;
  10877. this.parent = null;
  10878. };
  10879. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10880. return this._boundingInfo.isInFrustum(frustumPlanes);
  10881. };
  10882. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10883. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10884. ;
  10885. };
  10886. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10887. if (!this._boundingInfo || !mesh._boundingInfo) {
  10888. return false;
  10889. }
  10890. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10891. };
  10892. AbstractMesh.prototype.intersectsPoint = function (point) {
  10893. if (!this._boundingInfo) {
  10894. return false;
  10895. }
  10896. return this._boundingInfo.intersectsPoint(point);
  10897. };
  10898. // Physics
  10899. /**
  10900. * @Deprecated. Use new PhysicsImpostor instead.
  10901. * */
  10902. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10903. //legacy support
  10904. if (impostor.impostor) {
  10905. options = impostor;
  10906. impostor = impostor.impostor;
  10907. }
  10908. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10909. return this.physicsImpostor.physicsBody;
  10910. };
  10911. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10912. return this.physicsImpostor;
  10913. };
  10914. /**
  10915. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10916. */
  10917. AbstractMesh.prototype.getPhysicsMass = function () {
  10918. return this.physicsImpostor.getParam("mass");
  10919. };
  10920. /**
  10921. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10922. */
  10923. AbstractMesh.prototype.getPhysicsFriction = function () {
  10924. return this.physicsImpostor.getParam("friction");
  10925. };
  10926. /**
  10927. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10928. */
  10929. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10930. return this.physicsImpostor.getParam("restitution");
  10931. };
  10932. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10933. if (!camera) {
  10934. camera = this.getScene().activeCamera;
  10935. }
  10936. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10937. };
  10938. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10939. if (!camera) {
  10940. camera = this.getScene().activeCamera;
  10941. }
  10942. return this.absolutePosition.subtract(camera.position).length();
  10943. };
  10944. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10945. if (!this.physicsImpostor) {
  10946. return;
  10947. }
  10948. this.physicsImpostor.applyImpulse(force, contactPoint);
  10949. };
  10950. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10951. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10952. return;
  10953. }
  10954. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10955. mainPivot: pivot1,
  10956. connectedPivot: pivot2,
  10957. nativeParams: options
  10958. });
  10959. };
  10960. /**
  10961. * @Deprecated
  10962. */
  10963. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10964. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10965. this.updatePhysicsBody();
  10966. };
  10967. /**
  10968. * @Deprecated
  10969. * Calling this function is not needed anymore.
  10970. * The physics engine takes care of transofmration automatically.
  10971. */
  10972. AbstractMesh.prototype.updatePhysicsBody = function () {
  10973. //Unneeded
  10974. };
  10975. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10976. // Collisions
  10977. get: function () {
  10978. return this._checkCollisions;
  10979. },
  10980. set: function (collisionEnabled) {
  10981. this._checkCollisions = collisionEnabled;
  10982. if (this.getScene().workerCollisions) {
  10983. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10984. }
  10985. },
  10986. enumerable: true,
  10987. configurable: true
  10988. });
  10989. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10990. var globalPosition = this.getAbsolutePosition();
  10991. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10992. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10993. this._collider.radius = this.ellipsoid;
  10994. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10995. };
  10996. // Submeshes octree
  10997. /**
  10998. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10999. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  11000. */
  11001. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  11002. if (maxCapacity === void 0) { maxCapacity = 64; }
  11003. if (maxDepth === void 0) { maxDepth = 2; }
  11004. if (!this._submeshesOctree) {
  11005. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  11006. }
  11007. this.computeWorldMatrix(true);
  11008. // Update octree
  11009. var bbox = this.getBoundingInfo().boundingBox;
  11010. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  11011. return this._submeshesOctree;
  11012. };
  11013. // Collisions
  11014. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  11015. this._generatePointsArray();
  11016. // Transformation
  11017. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  11018. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  11019. subMesh._lastColliderWorldVertices = [];
  11020. subMesh._trianglePlanes = [];
  11021. var start = subMesh.verticesStart;
  11022. var end = (subMesh.verticesStart + subMesh.verticesCount);
  11023. for (var i = start; i < end; i++) {
  11024. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  11025. }
  11026. }
  11027. // Collide
  11028. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  11029. if (collider.collisionFound) {
  11030. collider.collidedMesh = this;
  11031. }
  11032. };
  11033. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  11034. var subMeshes;
  11035. var len;
  11036. // Octrees
  11037. if (this._submeshesOctree && this.useOctreeForCollisions) {
  11038. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  11039. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  11040. len = intersections.length;
  11041. subMeshes = intersections.data;
  11042. }
  11043. else {
  11044. subMeshes = this.subMeshes;
  11045. len = subMeshes.length;
  11046. }
  11047. for (var index = 0; index < len; index++) {
  11048. var subMesh = subMeshes[index];
  11049. // Bounding test
  11050. if (len > 1 && !subMesh._checkCollision(collider))
  11051. continue;
  11052. this._collideForSubMesh(subMesh, transformMatrix, collider);
  11053. }
  11054. };
  11055. AbstractMesh.prototype._checkCollision = function (collider) {
  11056. // Bounding box test
  11057. if (!this._boundingInfo._checkCollision(collider))
  11058. return;
  11059. // Transformation matrix
  11060. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  11061. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  11062. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  11063. };
  11064. // Picking
  11065. AbstractMesh.prototype._generatePointsArray = function () {
  11066. return false;
  11067. };
  11068. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  11069. var pickingInfo = new BABYLON.PickingInfo();
  11070. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  11071. return pickingInfo;
  11072. }
  11073. if (!this._generatePointsArray()) {
  11074. return pickingInfo;
  11075. }
  11076. var intersectInfo = null;
  11077. // Octrees
  11078. var subMeshes;
  11079. var len;
  11080. if (this._submeshesOctree && this.useOctreeForPicking) {
  11081. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  11082. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  11083. len = intersections.length;
  11084. subMeshes = intersections.data;
  11085. }
  11086. else {
  11087. subMeshes = this.subMeshes;
  11088. len = subMeshes.length;
  11089. }
  11090. for (var index = 0; index < len; index++) {
  11091. var subMesh = subMeshes[index];
  11092. // Bounding test
  11093. if (len > 1 && !subMesh.canIntersects(ray))
  11094. continue;
  11095. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  11096. if (currentIntersectInfo) {
  11097. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11098. intersectInfo = currentIntersectInfo;
  11099. intersectInfo.subMeshId = index;
  11100. if (fastCheck) {
  11101. break;
  11102. }
  11103. }
  11104. }
  11105. }
  11106. if (intersectInfo) {
  11107. // Get picked point
  11108. var world = this.getWorldMatrix();
  11109. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  11110. var direction = ray.direction.clone();
  11111. direction = direction.scale(intersectInfo.distance);
  11112. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  11113. var pickedPoint = worldOrigin.add(worldDirection);
  11114. // Return result
  11115. pickingInfo.hit = true;
  11116. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  11117. pickingInfo.pickedPoint = pickedPoint;
  11118. pickingInfo.pickedMesh = this;
  11119. pickingInfo.bu = intersectInfo.bu;
  11120. pickingInfo.bv = intersectInfo.bv;
  11121. pickingInfo.faceId = intersectInfo.faceId;
  11122. pickingInfo.subMeshId = intersectInfo.subMeshId;
  11123. return pickingInfo;
  11124. }
  11125. return pickingInfo;
  11126. };
  11127. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11128. return null;
  11129. };
  11130. AbstractMesh.prototype.releaseSubMeshes = function () {
  11131. if (this.subMeshes) {
  11132. while (this.subMeshes.length) {
  11133. this.subMeshes[0].dispose();
  11134. }
  11135. }
  11136. else {
  11137. this.subMeshes = new Array();
  11138. }
  11139. };
  11140. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  11141. var _this = this;
  11142. var index;
  11143. // Action manager
  11144. if (this.actionManager) {
  11145. this.actionManager.dispose();
  11146. this.actionManager = null;
  11147. }
  11148. // Skeleton
  11149. this.skeleton = null;
  11150. // Animations
  11151. this.getScene().stopAnimation(this);
  11152. // Physics
  11153. if (this.physicsImpostor) {
  11154. this.physicsImpostor.dispose();
  11155. }
  11156. // Intersections in progress
  11157. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  11158. var other = this._intersectionsInProgress[index];
  11159. var pos = other._intersectionsInProgress.indexOf(this);
  11160. other._intersectionsInProgress.splice(pos, 1);
  11161. }
  11162. this._intersectionsInProgress = [];
  11163. // Lights
  11164. var lights = this.getScene().lights;
  11165. lights.forEach(function (light) {
  11166. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11167. if (meshIndex !== -1) {
  11168. light.includedOnlyMeshes.splice(meshIndex, 1);
  11169. }
  11170. meshIndex = light.excludedMeshes.indexOf(_this);
  11171. if (meshIndex !== -1) {
  11172. light.excludedMeshes.splice(meshIndex, 1);
  11173. }
  11174. // Shadow generators
  11175. var generator = light.getShadowGenerator();
  11176. if (generator) {
  11177. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11178. if (meshIndex !== -1) {
  11179. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11180. }
  11181. }
  11182. });
  11183. // Edges
  11184. if (this._edgesRenderer) {
  11185. this._edgesRenderer.dispose();
  11186. this._edgesRenderer = null;
  11187. }
  11188. // SubMeshes
  11189. this.releaseSubMeshes();
  11190. // Engine
  11191. this.getScene().getEngine().unbindAllAttributes();
  11192. // Remove from scene
  11193. this.getScene().removeMesh(this);
  11194. if (!doNotRecurse) {
  11195. // Particles
  11196. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11197. if (this.getScene().particleSystems[index].emitter === this) {
  11198. this.getScene().particleSystems[index].dispose();
  11199. index--;
  11200. }
  11201. }
  11202. // Children
  11203. var objects = this.getDescendants(true);
  11204. for (index = 0; index < objects.length; index++) {
  11205. objects[index].dispose();
  11206. }
  11207. }
  11208. else {
  11209. var childMeshes = this.getChildMeshes(true);
  11210. for (index = 0; index < childMeshes.length; index++) {
  11211. var child = childMeshes[index];
  11212. child.parent = null;
  11213. child.computeWorldMatrix(true);
  11214. }
  11215. }
  11216. this.onAfterWorldMatrixUpdateObservable.clear();
  11217. this.onCollideObservable.clear();
  11218. this.onCollisionPositionChangeObservable.clear();
  11219. this._isDisposed = true;
  11220. _super.prototype.dispose.call(this);
  11221. };
  11222. AbstractMesh.prototype.getDirection = function (localAxis) {
  11223. var result = BABYLON.Vector3.Zero();
  11224. this.getDirectionToRef(localAxis, result);
  11225. return result;
  11226. };
  11227. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  11228. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  11229. };
  11230. AbstractMesh.prototype.setPivotPoint = function (point) {
  11231. BABYLON.Vector3.TransformCoordinatesToRef(point, this.getWorldMatrix(), this.position);
  11232. this._pivotMatrix.m[12] = -point.x;
  11233. this._pivotMatrix.m[13] = -point.y;
  11234. this._pivotMatrix.m[14] = -point.z;
  11235. this._cache.pivotMatrixUpdated = true;
  11236. };
  11237. AbstractMesh.prototype.getPivotPoint = function () {
  11238. var point = BABYLON.Vector3.Zero();
  11239. this.getPivotPointToRef(point);
  11240. return point;
  11241. };
  11242. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  11243. result.x = -this._pivotMatrix.m[12];
  11244. result.y = -this._pivotMatrix.m[13];
  11245. result.z = -this._pivotMatrix.m[14];
  11246. };
  11247. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  11248. var point = BABYLON.Vector3.Zero();
  11249. this.getAbsolutePivotPointToRef(point);
  11250. return point;
  11251. };
  11252. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  11253. result.x = this._pivotMatrix.m[12];
  11254. result.y = this._pivotMatrix.m[13];
  11255. result.z = this._pivotMatrix.m[14];
  11256. this.getPivotPointToRef(result);
  11257. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  11258. };
  11259. // Statics
  11260. AbstractMesh._BILLBOARDMODE_NONE = 0;
  11261. AbstractMesh._BILLBOARDMODE_X = 1;
  11262. AbstractMesh._BILLBOARDMODE_Y = 2;
  11263. AbstractMesh._BILLBOARDMODE_Z = 4;
  11264. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11265. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11266. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11267. return AbstractMesh;
  11268. }(BABYLON.Node));
  11269. BABYLON.AbstractMesh = AbstractMesh;
  11270. })(BABYLON || (BABYLON = {}));
  11271. //# sourceMappingURL=../Mesh/babylon.abstractMesh.js.map
  11272. var BABYLON;
  11273. (function (BABYLON) {
  11274. var Light = (function (_super) {
  11275. __extends(Light, _super);
  11276. function Light(name, scene) {
  11277. _super.call(this, name, scene);
  11278. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  11279. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  11280. this.intensity = 1.0;
  11281. this.range = Number.MAX_VALUE;
  11282. this.includeOnlyWithLayerMask = 0;
  11283. this.includedOnlyMeshes = new Array();
  11284. this.excludedMeshes = new Array();
  11285. this.excludeWithLayerMask = 0;
  11286. this.lightmapMode = 0;
  11287. // PBR Properties.
  11288. this.radius = 0.00001;
  11289. this._excludedMeshesIds = new Array();
  11290. this._includedOnlyMeshesIds = new Array();
  11291. scene.addLight(this);
  11292. }
  11293. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  11294. /**
  11295. * If every light affecting the material is in this lightmapMode,
  11296. * material.lightmapTexture adds or multiplies
  11297. * (depends on material.useLightmapAsShadowmap)
  11298. * after every other light calculations.
  11299. */
  11300. get: function () {
  11301. return Light._LIGHTMAP_DEFAULT;
  11302. },
  11303. enumerable: true,
  11304. configurable: true
  11305. });
  11306. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  11307. /**
  11308. * material.lightmapTexture as only diffuse lighting from this light
  11309. * adds pnly specular lighting from this light
  11310. * adds dynamic shadows
  11311. */
  11312. get: function () {
  11313. return Light._LIGHTMAP_SPECULAR;
  11314. },
  11315. enumerable: true,
  11316. configurable: true
  11317. });
  11318. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  11319. /**
  11320. * material.lightmapTexture as only lighting
  11321. * no light calculation from this light
  11322. * only adds dynamic shadows from this light
  11323. */
  11324. get: function () {
  11325. return Light._LIGHTMAP_SHADOWSONLY;
  11326. },
  11327. enumerable: true,
  11328. configurable: true
  11329. });
  11330. /**
  11331. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11332. */
  11333. Light.prototype.toString = function (fullDetails) {
  11334. var ret = "Name: " + this.name;
  11335. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  11336. if (this.animations) {
  11337. for (var i = 0; i < this.animations.length; i++) {
  11338. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11339. }
  11340. }
  11341. if (fullDetails) {
  11342. }
  11343. return ret;
  11344. };
  11345. Light.prototype.getShadowGenerator = function () {
  11346. return this._shadowGenerator;
  11347. };
  11348. Light.prototype.getAbsolutePosition = function () {
  11349. return BABYLON.Vector3.Zero();
  11350. };
  11351. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  11352. };
  11353. Light.prototype._getWorldMatrix = function () {
  11354. return BABYLON.Matrix.Identity();
  11355. };
  11356. Light.prototype.canAffectMesh = function (mesh) {
  11357. if (!mesh) {
  11358. return true;
  11359. }
  11360. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  11361. return false;
  11362. }
  11363. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  11364. return false;
  11365. }
  11366. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  11367. return false;
  11368. }
  11369. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  11370. return false;
  11371. }
  11372. return true;
  11373. };
  11374. Light.prototype.getWorldMatrix = function () {
  11375. this._currentRenderId = this.getScene().getRenderId();
  11376. var worldMatrix = this._getWorldMatrix();
  11377. if (this.parent && this.parent.getWorldMatrix) {
  11378. if (!this._parentedWorldMatrix) {
  11379. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  11380. }
  11381. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  11382. this._markSyncedWithParent();
  11383. return this._parentedWorldMatrix;
  11384. }
  11385. return worldMatrix;
  11386. };
  11387. Light.prototype.dispose = function () {
  11388. if (this._shadowGenerator) {
  11389. this._shadowGenerator.dispose();
  11390. this._shadowGenerator = null;
  11391. }
  11392. // Animations
  11393. this.getScene().stopAnimation(this);
  11394. // Remove from scene
  11395. this.getScene().removeLight(this);
  11396. _super.prototype.dispose.call(this);
  11397. };
  11398. Light.prototype.getTypeID = function () {
  11399. return 0;
  11400. };
  11401. Light.prototype.clone = function (name) {
  11402. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  11403. };
  11404. Light.prototype.serialize = function () {
  11405. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11406. // Type
  11407. serializationObject.type = this.getTypeID();
  11408. // Parent
  11409. if (this.parent) {
  11410. serializationObject.parentId = this.parent.id;
  11411. }
  11412. // Inclusion / exclusions
  11413. if (this.excludedMeshes.length > 0) {
  11414. serializationObject.excludedMeshesIds = [];
  11415. this.excludedMeshes.forEach(function (mesh) {
  11416. serializationObject.excludedMeshesIds.push(mesh.id);
  11417. });
  11418. }
  11419. if (this.includedOnlyMeshes.length > 0) {
  11420. serializationObject.includedOnlyMeshesIds = [];
  11421. this.includedOnlyMeshes.forEach(function (mesh) {
  11422. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  11423. });
  11424. }
  11425. // Animations
  11426. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11427. serializationObject.ranges = this.serializeAnimationRanges();
  11428. return serializationObject;
  11429. };
  11430. Light.GetConstructorFromName = function (type, name, scene) {
  11431. switch (type) {
  11432. case 0:
  11433. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11434. case 1:
  11435. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11436. case 2:
  11437. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11438. case 3:
  11439. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11440. }
  11441. };
  11442. Light.Parse = function (parsedLight, scene) {
  11443. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11444. // Inclusion / exclusions
  11445. if (parsedLight.excludedMeshesIds) {
  11446. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11447. }
  11448. if (parsedLight.includedOnlyMeshesIds) {
  11449. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11450. }
  11451. // Parent
  11452. if (parsedLight.parentId) {
  11453. light._waitingParentId = parsedLight.parentId;
  11454. }
  11455. // Animations
  11456. if (parsedLight.animations) {
  11457. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11458. var parsedAnimation = parsedLight.animations[animationIndex];
  11459. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11460. }
  11461. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11462. }
  11463. if (parsedLight.autoAnimate) {
  11464. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11465. }
  11466. return light;
  11467. };
  11468. //lightmapMode Consts
  11469. Light._LIGHTMAP_DEFAULT = 0;
  11470. Light._LIGHTMAP_SPECULAR = 1;
  11471. Light._LIGHTMAP_SHADOWSONLY = 2;
  11472. __decorate([
  11473. BABYLON.serializeAsColor3()
  11474. ], Light.prototype, "diffuse", void 0);
  11475. __decorate([
  11476. BABYLON.serializeAsColor3()
  11477. ], Light.prototype, "specular", void 0);
  11478. __decorate([
  11479. BABYLON.serialize()
  11480. ], Light.prototype, "intensity", void 0);
  11481. __decorate([
  11482. BABYLON.serialize()
  11483. ], Light.prototype, "range", void 0);
  11484. __decorate([
  11485. BABYLON.serialize()
  11486. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11487. __decorate([
  11488. BABYLON.serialize()
  11489. ], Light.prototype, "excludeWithLayerMask", void 0);
  11490. __decorate([
  11491. BABYLON.serialize()
  11492. ], Light.prototype, "lightmapMode", void 0);
  11493. __decorate([
  11494. BABYLON.serialize()
  11495. ], Light.prototype, "radius", void 0);
  11496. return Light;
  11497. }(BABYLON.Node));
  11498. BABYLON.Light = Light;
  11499. })(BABYLON || (BABYLON = {}));
  11500. //# sourceMappingURL=../Lights/babylon.light.js.map
  11501. var BABYLON;
  11502. (function (BABYLON) {
  11503. var PointLight = (function (_super) {
  11504. __extends(PointLight, _super);
  11505. function PointLight(name, position, scene) {
  11506. _super.call(this, name, scene);
  11507. this.position = position;
  11508. }
  11509. PointLight.prototype.getAbsolutePosition = function () {
  11510. return this.transformedPosition ? this.transformedPosition : this.position;
  11511. };
  11512. PointLight.prototype.computeTransformedPosition = function () {
  11513. if (this.parent && this.parent.getWorldMatrix) {
  11514. if (!this.transformedPosition) {
  11515. this.transformedPosition = BABYLON.Vector3.Zero();
  11516. }
  11517. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11518. return true;
  11519. }
  11520. return false;
  11521. };
  11522. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11523. if (this.parent && this.parent.getWorldMatrix) {
  11524. this.computeTransformedPosition();
  11525. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11526. return;
  11527. }
  11528. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11529. };
  11530. PointLight.prototype.needCube = function () {
  11531. return true;
  11532. };
  11533. PointLight.prototype.supportsVSM = function () {
  11534. return false;
  11535. };
  11536. PointLight.prototype.needRefreshPerFrame = function () {
  11537. return false;
  11538. };
  11539. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11540. switch (faceIndex) {
  11541. case 0:
  11542. return new BABYLON.Vector3(1, 0, 0);
  11543. case 1:
  11544. return new BABYLON.Vector3(-1, 0, 0);
  11545. case 2:
  11546. return new BABYLON.Vector3(0, -1, 0);
  11547. case 3:
  11548. return new BABYLON.Vector3(0, 1, 0);
  11549. case 4:
  11550. return new BABYLON.Vector3(0, 0, 1);
  11551. case 5:
  11552. return new BABYLON.Vector3(0, 0, -1);
  11553. }
  11554. return BABYLON.Vector3.Zero();
  11555. };
  11556. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11557. var activeCamera = this.getScene().activeCamera;
  11558. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11559. };
  11560. PointLight.prototype._getWorldMatrix = function () {
  11561. if (!this._worldMatrix) {
  11562. this._worldMatrix = BABYLON.Matrix.Identity();
  11563. }
  11564. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11565. return this._worldMatrix;
  11566. };
  11567. PointLight.prototype.getTypeID = function () {
  11568. return 0;
  11569. };
  11570. __decorate([
  11571. BABYLON.serializeAsVector3()
  11572. ], PointLight.prototype, "position", void 0);
  11573. return PointLight;
  11574. }(BABYLON.Light));
  11575. BABYLON.PointLight = PointLight;
  11576. })(BABYLON || (BABYLON = {}));
  11577. //# sourceMappingURL=../Lights/babylon.pointLight.js.map
  11578. var BABYLON;
  11579. (function (BABYLON) {
  11580. var SpotLight = (function (_super) {
  11581. __extends(SpotLight, _super);
  11582. function SpotLight(name, position, direction, angle, exponent, scene) {
  11583. _super.call(this, name, scene);
  11584. this.position = position;
  11585. this.direction = direction;
  11586. this.angle = angle;
  11587. this.exponent = exponent;
  11588. }
  11589. SpotLight.prototype.getAbsolutePosition = function () {
  11590. return this.transformedPosition ? this.transformedPosition : this.position;
  11591. };
  11592. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11593. var activeCamera = this.getScene().activeCamera;
  11594. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11595. };
  11596. SpotLight.prototype.needCube = function () {
  11597. return false;
  11598. };
  11599. SpotLight.prototype.supportsVSM = function () {
  11600. return true;
  11601. };
  11602. SpotLight.prototype.needRefreshPerFrame = function () {
  11603. return false;
  11604. };
  11605. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11606. return this.direction;
  11607. };
  11608. SpotLight.prototype.setDirectionToTarget = function (target) {
  11609. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11610. return this.direction;
  11611. };
  11612. SpotLight.prototype.computeTransformedPosition = function () {
  11613. if (this.parent && this.parent.getWorldMatrix) {
  11614. if (!this.transformedPosition) {
  11615. this.transformedPosition = BABYLON.Vector3.Zero();
  11616. }
  11617. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11618. return true;
  11619. }
  11620. return false;
  11621. };
  11622. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11623. var normalizeDirection;
  11624. if (this.parent && this.parent.getWorldMatrix) {
  11625. if (!this._transformedDirection) {
  11626. this._transformedDirection = BABYLON.Vector3.Zero();
  11627. }
  11628. this.computeTransformedPosition();
  11629. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11630. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11631. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11632. }
  11633. else {
  11634. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11635. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11636. }
  11637. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11638. };
  11639. SpotLight.prototype._getWorldMatrix = function () {
  11640. if (!this._worldMatrix) {
  11641. this._worldMatrix = BABYLON.Matrix.Identity();
  11642. }
  11643. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11644. return this._worldMatrix;
  11645. };
  11646. SpotLight.prototype.getTypeID = function () {
  11647. return 2;
  11648. };
  11649. SpotLight.prototype.getRotation = function () {
  11650. this.direction.normalize();
  11651. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  11652. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  11653. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  11654. };
  11655. __decorate([
  11656. BABYLON.serializeAsVector3()
  11657. ], SpotLight.prototype, "position", void 0);
  11658. __decorate([
  11659. BABYLON.serializeAsVector3()
  11660. ], SpotLight.prototype, "direction", void 0);
  11661. __decorate([
  11662. BABYLON.serialize()
  11663. ], SpotLight.prototype, "angle", void 0);
  11664. __decorate([
  11665. BABYLON.serialize()
  11666. ], SpotLight.prototype, "exponent", void 0);
  11667. return SpotLight;
  11668. }(BABYLON.Light));
  11669. BABYLON.SpotLight = SpotLight;
  11670. })(BABYLON || (BABYLON = {}));
  11671. //# sourceMappingURL=../Lights/babylon.spotLight.js.map
  11672. var BABYLON;
  11673. (function (BABYLON) {
  11674. var HemisphericLight = (function (_super) {
  11675. __extends(HemisphericLight, _super);
  11676. function HemisphericLight(name, direction, scene) {
  11677. _super.call(this, name, scene);
  11678. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11679. this.direction = direction;
  11680. }
  11681. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11682. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11683. return this.direction;
  11684. };
  11685. HemisphericLight.prototype.getShadowGenerator = function () {
  11686. return null;
  11687. };
  11688. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11689. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11690. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11691. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11692. };
  11693. HemisphericLight.prototype._getWorldMatrix = function () {
  11694. if (!this._worldMatrix) {
  11695. this._worldMatrix = BABYLON.Matrix.Identity();
  11696. }
  11697. return this._worldMatrix;
  11698. };
  11699. HemisphericLight.prototype.getTypeID = function () {
  11700. return 3;
  11701. };
  11702. __decorate([
  11703. BABYLON.serializeAsColor3()
  11704. ], HemisphericLight.prototype, "groundColor", void 0);
  11705. __decorate([
  11706. BABYLON.serializeAsVector3()
  11707. ], HemisphericLight.prototype, "direction", void 0);
  11708. return HemisphericLight;
  11709. }(BABYLON.Light));
  11710. BABYLON.HemisphericLight = HemisphericLight;
  11711. })(BABYLON || (BABYLON = {}));
  11712. //# sourceMappingURL=../Lights/babylon.hemisphericLight.js.map
  11713. var BABYLON;
  11714. (function (BABYLON) {
  11715. var DirectionalLight = (function (_super) {
  11716. __extends(DirectionalLight, _super);
  11717. function DirectionalLight(name, direction, scene) {
  11718. _super.call(this, name, scene);
  11719. this.shadowOrthoScale = 0.5;
  11720. this.autoUpdateExtends = true;
  11721. // Cache
  11722. this._orthoLeft = Number.MAX_VALUE;
  11723. this._orthoRight = Number.MIN_VALUE;
  11724. this._orthoTop = Number.MIN_VALUE;
  11725. this._orthoBottom = Number.MAX_VALUE;
  11726. this.position = direction.scale(-1);
  11727. this.direction = direction;
  11728. }
  11729. DirectionalLight.prototype.getAbsolutePosition = function () {
  11730. return this.transformedPosition ? this.transformedPosition : this.position;
  11731. };
  11732. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11733. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11734. return this.direction;
  11735. };
  11736. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11737. var activeCamera = this.getScene().activeCamera;
  11738. // Check extends
  11739. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11740. var tempVector3 = BABYLON.Vector3.Zero();
  11741. this._orthoLeft = Number.MAX_VALUE;
  11742. this._orthoRight = Number.MIN_VALUE;
  11743. this._orthoTop = Number.MIN_VALUE;
  11744. this._orthoBottom = Number.MAX_VALUE;
  11745. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11746. var mesh = renderList[meshIndex];
  11747. if (!mesh) {
  11748. continue;
  11749. }
  11750. var boundingInfo = mesh.getBoundingInfo();
  11751. if (!boundingInfo) {
  11752. continue;
  11753. }
  11754. var boundingBox = boundingInfo.boundingBox;
  11755. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11756. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11757. if (tempVector3.x < this._orthoLeft)
  11758. this._orthoLeft = tempVector3.x;
  11759. if (tempVector3.y < this._orthoBottom)
  11760. this._orthoBottom = tempVector3.y;
  11761. if (tempVector3.x > this._orthoRight)
  11762. this._orthoRight = tempVector3.x;
  11763. if (tempVector3.y > this._orthoTop)
  11764. this._orthoTop = tempVector3.y;
  11765. }
  11766. }
  11767. }
  11768. var xOffset = this._orthoRight - this._orthoLeft;
  11769. var yOffset = this._orthoTop - this._orthoBottom;
  11770. 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);
  11771. };
  11772. DirectionalLight.prototype.supportsVSM = function () {
  11773. return true;
  11774. };
  11775. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11776. return true;
  11777. };
  11778. DirectionalLight.prototype.needCube = function () {
  11779. return false;
  11780. };
  11781. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11782. return this.direction;
  11783. };
  11784. DirectionalLight.prototype.computeTransformedPosition = function () {
  11785. if (this.parent && this.parent.getWorldMatrix) {
  11786. if (!this.transformedPosition) {
  11787. this.transformedPosition = BABYLON.Vector3.Zero();
  11788. }
  11789. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11790. return true;
  11791. }
  11792. return false;
  11793. };
  11794. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11795. if (this.parent && this.parent.getWorldMatrix) {
  11796. if (!this._transformedDirection) {
  11797. this._transformedDirection = BABYLON.Vector3.Zero();
  11798. }
  11799. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11800. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11801. return;
  11802. }
  11803. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11804. };
  11805. DirectionalLight.prototype._getWorldMatrix = function () {
  11806. if (!this._worldMatrix) {
  11807. this._worldMatrix = BABYLON.Matrix.Identity();
  11808. }
  11809. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11810. return this._worldMatrix;
  11811. };
  11812. DirectionalLight.prototype.getTypeID = function () {
  11813. return 1;
  11814. };
  11815. __decorate([
  11816. BABYLON.serializeAsVector3()
  11817. ], DirectionalLight.prototype, "position", void 0);
  11818. __decorate([
  11819. BABYLON.serializeAsVector3()
  11820. ], DirectionalLight.prototype, "direction", void 0);
  11821. __decorate([
  11822. BABYLON.serialize()
  11823. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11824. __decorate([
  11825. BABYLON.serialize()
  11826. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11827. return DirectionalLight;
  11828. }(BABYLON.Light));
  11829. BABYLON.DirectionalLight = DirectionalLight;
  11830. })(BABYLON || (BABYLON = {}));
  11831. //# sourceMappingURL=../Lights/babylon.directionalLight.js.map
  11832. var BABYLON;
  11833. (function (BABYLON) {
  11834. var ShadowGenerator = (function () {
  11835. function ShadowGenerator(mapSize, light) {
  11836. var _this = this;
  11837. // Members
  11838. this._filter = ShadowGenerator.FILTER_NONE;
  11839. this.blurScale = 2;
  11840. this._blurBoxOffset = 0;
  11841. this._bias = 0.00005;
  11842. this._lightDirection = BABYLON.Vector3.Zero();
  11843. this.forceBackFacesOnly = false;
  11844. this._darkness = 0;
  11845. this._transparencyShadow = false;
  11846. this._viewMatrix = BABYLON.Matrix.Zero();
  11847. this._projectionMatrix = BABYLON.Matrix.Zero();
  11848. this._transformMatrix = BABYLON.Matrix.Zero();
  11849. this._worldViewProjection = BABYLON.Matrix.Zero();
  11850. this._currentFaceIndex = 0;
  11851. this._currentFaceIndexCache = 0;
  11852. this._useFullFloat = true;
  11853. this._light = light;
  11854. this._scene = light.getScene();
  11855. this._mapSize = mapSize;
  11856. light._shadowGenerator = this;
  11857. // Texture type fallback from float to int if not supported.
  11858. var textureType;
  11859. var caps = this._scene.getEngine().getCaps();
  11860. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  11861. this._useFullFloat = true;
  11862. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  11863. }
  11864. else {
  11865. this._useFullFloat = false;
  11866. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  11867. }
  11868. // Render target
  11869. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  11870. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11871. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11872. this._shadowMap.anisotropicFilteringLevel = 1;
  11873. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11874. this._shadowMap.renderParticles = false;
  11875. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  11876. _this._currentFaceIndex = faceIndex;
  11877. });
  11878. this._shadowMap.onAfterUnbindObservable.add(function () {
  11879. if (!_this.useBlurVarianceShadowMap) {
  11880. return;
  11881. }
  11882. if (!_this._shadowMap2) {
  11883. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  11884. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11885. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11886. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  11887. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  11888. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  11889. effect.setTexture("textureSampler", _this._shadowMap);
  11890. });
  11891. _this.blurBoxOffset = 1;
  11892. }
  11893. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  11894. });
  11895. // Custom render function
  11896. var renderSubMesh = function (subMesh) {
  11897. var mesh = subMesh.getRenderingMesh();
  11898. var scene = _this._scene;
  11899. var engine = scene.getEngine();
  11900. // Culling
  11901. engine.setState(subMesh.getMaterial().backFaceCulling);
  11902. // Managing instances
  11903. var batch = mesh._getInstancesRenderList(subMesh._id);
  11904. if (batch.mustReturn) {
  11905. return;
  11906. }
  11907. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11908. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  11909. engine.enableEffect(_this._effect);
  11910. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  11911. var material = subMesh.getMaterial();
  11912. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  11913. _this._effect.setVector3("lightPosition", _this.getLight().position);
  11914. if (_this.getLight().needCube()) {
  11915. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  11916. }
  11917. // Alpha test
  11918. if (material && material.needAlphaTesting()) {
  11919. var alphaTexture = material.getAlphaTestTexture();
  11920. _this._effect.setTexture("diffuseSampler", alphaTexture);
  11921. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  11922. }
  11923. // Bones
  11924. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11925. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  11926. }
  11927. if (_this.forceBackFacesOnly) {
  11928. engine.setState(true, 0, false, true);
  11929. }
  11930. // Draw
  11931. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  11932. if (_this.forceBackFacesOnly) {
  11933. engine.setState(true, 0, false, false);
  11934. }
  11935. }
  11936. else {
  11937. // Need to reset refresh rate of the shadowMap
  11938. _this._shadowMap.resetRefreshCounter();
  11939. }
  11940. };
  11941. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  11942. var index;
  11943. for (index = 0; index < opaqueSubMeshes.length; index++) {
  11944. renderSubMesh(opaqueSubMeshes.data[index]);
  11945. }
  11946. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  11947. renderSubMesh(alphaTestSubMeshes.data[index]);
  11948. }
  11949. if (_this._transparencyShadow) {
  11950. for (index = 0; index < transparentSubMeshes.length; index++) {
  11951. renderSubMesh(transparentSubMeshes.data[index]);
  11952. }
  11953. }
  11954. };
  11955. this._shadowMap.onClearObservable.add(function (engine) {
  11956. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  11957. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  11958. }
  11959. else {
  11960. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  11961. }
  11962. });
  11963. }
  11964. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  11965. // Static
  11966. get: function () {
  11967. return ShadowGenerator._FILTER_NONE;
  11968. },
  11969. enumerable: true,
  11970. configurable: true
  11971. });
  11972. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  11973. get: function () {
  11974. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  11975. },
  11976. enumerable: true,
  11977. configurable: true
  11978. });
  11979. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  11980. get: function () {
  11981. return ShadowGenerator._FILTER_POISSONSAMPLING;
  11982. },
  11983. enumerable: true,
  11984. configurable: true
  11985. });
  11986. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  11987. get: function () {
  11988. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  11989. },
  11990. enumerable: true,
  11991. configurable: true
  11992. });
  11993. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  11994. get: function () {
  11995. return this._bias;
  11996. },
  11997. set: function (bias) {
  11998. this._bias = bias;
  11999. },
  12000. enumerable: true,
  12001. configurable: true
  12002. });
  12003. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  12004. get: function () {
  12005. return this._blurBoxOffset;
  12006. },
  12007. set: function (value) {
  12008. var _this = this;
  12009. if (this._blurBoxOffset === value) {
  12010. return;
  12011. }
  12012. this._blurBoxOffset = value;
  12013. if (this._boxBlurPostprocess) {
  12014. this._boxBlurPostprocess.dispose();
  12015. }
  12016. 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);
  12017. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  12018. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  12019. });
  12020. },
  12021. enumerable: true,
  12022. configurable: true
  12023. });
  12024. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  12025. get: function () {
  12026. return this._filter;
  12027. },
  12028. set: function (value) {
  12029. if (this._filter === value) {
  12030. return;
  12031. }
  12032. this._filter = value;
  12033. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  12034. this._shadowMap.anisotropicFilteringLevel = 16;
  12035. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  12036. }
  12037. else {
  12038. this._shadowMap.anisotropicFilteringLevel = 1;
  12039. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12040. }
  12041. },
  12042. enumerable: true,
  12043. configurable: true
  12044. });
  12045. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  12046. get: function () {
  12047. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  12048. },
  12049. set: function (value) {
  12050. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12051. },
  12052. enumerable: true,
  12053. configurable: true
  12054. });
  12055. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  12056. get: function () {
  12057. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  12058. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  12059. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  12060. },
  12061. set: function (value) {
  12062. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  12063. },
  12064. enumerable: true,
  12065. configurable: true
  12066. });
  12067. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  12068. get: function () {
  12069. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  12070. },
  12071. set: function (value) {
  12072. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12073. },
  12074. enumerable: true,
  12075. configurable: true
  12076. });
  12077. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  12078. var defines = [];
  12079. if (this._useFullFloat) {
  12080. defines.push("#define FULLFLOAT");
  12081. }
  12082. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  12083. defines.push("#define VSM");
  12084. }
  12085. if (this.getLight().needCube()) {
  12086. defines.push("#define CUBEMAP");
  12087. }
  12088. var attribs = [BABYLON.VertexBuffer.PositionKind];
  12089. var mesh = subMesh.getMesh();
  12090. var material = subMesh.getMaterial();
  12091. // Alpha test
  12092. if (material && material.needAlphaTesting()) {
  12093. defines.push("#define ALPHATEST");
  12094. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12095. attribs.push(BABYLON.VertexBuffer.UVKind);
  12096. defines.push("#define UV1");
  12097. }
  12098. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12099. var alphaTexture = material.getAlphaTestTexture();
  12100. if (alphaTexture.coordinatesIndex === 1) {
  12101. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12102. defines.push("#define UV2");
  12103. }
  12104. }
  12105. }
  12106. // Bones
  12107. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12108. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12109. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12110. if (mesh.numBoneInfluencers > 4) {
  12111. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  12112. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  12113. }
  12114. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  12115. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12116. }
  12117. else {
  12118. defines.push("#define NUM_BONE_INFLUENCERS 0");
  12119. }
  12120. // Instances
  12121. if (useInstances) {
  12122. defines.push("#define INSTANCES");
  12123. attribs.push("world0");
  12124. attribs.push("world1");
  12125. attribs.push("world2");
  12126. attribs.push("world3");
  12127. }
  12128. // Get correct effect
  12129. var join = defines.join("\n");
  12130. if (this._cachedDefines !== join) {
  12131. this._cachedDefines = join;
  12132. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  12133. }
  12134. return this._effect.isReady();
  12135. };
  12136. ShadowGenerator.prototype.getShadowMap = function () {
  12137. return this._shadowMap;
  12138. };
  12139. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  12140. if (this._shadowMap2) {
  12141. return this._shadowMap2;
  12142. }
  12143. return this._shadowMap;
  12144. };
  12145. ShadowGenerator.prototype.getLight = function () {
  12146. return this._light;
  12147. };
  12148. // Methods
  12149. ShadowGenerator.prototype.getTransformMatrix = function () {
  12150. var scene = this._scene;
  12151. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  12152. return this._transformMatrix;
  12153. }
  12154. this._currentRenderID = scene.getRenderId();
  12155. this._currentFaceIndexCache = this._currentFaceIndex;
  12156. var lightPosition = this._light.position;
  12157. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  12158. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  12159. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  12160. }
  12161. if (this._light.computeTransformedPosition()) {
  12162. lightPosition = this._light.transformedPosition;
  12163. }
  12164. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  12165. this._cachedPosition = lightPosition.clone();
  12166. this._cachedDirection = this._lightDirection.clone();
  12167. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  12168. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  12169. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12170. }
  12171. return this._transformMatrix;
  12172. };
  12173. ShadowGenerator.prototype.getDarkness = function () {
  12174. return this._darkness;
  12175. };
  12176. ShadowGenerator.prototype.setDarkness = function (darkness) {
  12177. if (darkness >= 1.0)
  12178. this._darkness = 1.0;
  12179. else if (darkness <= 0.0)
  12180. this._darkness = 0.0;
  12181. else
  12182. this._darkness = darkness;
  12183. };
  12184. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  12185. this._transparencyShadow = hasShadow;
  12186. };
  12187. ShadowGenerator.prototype._packHalf = function (depth) {
  12188. var scale = depth * 255.0;
  12189. var fract = scale - Math.floor(scale);
  12190. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  12191. };
  12192. ShadowGenerator.prototype.dispose = function () {
  12193. this._shadowMap.dispose();
  12194. if (this._shadowMap2) {
  12195. this._shadowMap2.dispose();
  12196. }
  12197. if (this._downSamplePostprocess) {
  12198. this._downSamplePostprocess.dispose();
  12199. }
  12200. if (this._boxBlurPostprocess) {
  12201. this._boxBlurPostprocess.dispose();
  12202. }
  12203. };
  12204. ShadowGenerator.prototype.serialize = function () {
  12205. var serializationObject = {};
  12206. serializationObject.lightId = this._light.id;
  12207. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  12208. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  12209. serializationObject.usePoissonSampling = this.usePoissonSampling;
  12210. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  12211. serializationObject.renderList = [];
  12212. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  12213. var mesh = this.getShadowMap().renderList[meshIndex];
  12214. serializationObject.renderList.push(mesh.id);
  12215. }
  12216. return serializationObject;
  12217. };
  12218. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  12219. //casting to point light, as light is missing the position attr and typescript complains.
  12220. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  12221. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  12222. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  12223. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  12224. meshes.forEach(function (mesh) {
  12225. shadowGenerator.getShadowMap().renderList.push(mesh);
  12226. });
  12227. }
  12228. if (parsedShadowGenerator.usePoissonSampling) {
  12229. shadowGenerator.usePoissonSampling = true;
  12230. }
  12231. else if (parsedShadowGenerator.useVarianceShadowMap) {
  12232. shadowGenerator.useVarianceShadowMap = true;
  12233. }
  12234. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  12235. shadowGenerator.useBlurVarianceShadowMap = true;
  12236. if (parsedShadowGenerator.blurScale) {
  12237. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  12238. }
  12239. if (parsedShadowGenerator.blurBoxOffset) {
  12240. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  12241. }
  12242. }
  12243. if (parsedShadowGenerator.bias !== undefined) {
  12244. shadowGenerator.bias = parsedShadowGenerator.bias;
  12245. }
  12246. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  12247. return shadowGenerator;
  12248. };
  12249. ShadowGenerator._FILTER_NONE = 0;
  12250. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  12251. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  12252. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  12253. return ShadowGenerator;
  12254. }());
  12255. BABYLON.ShadowGenerator = ShadowGenerator;
  12256. })(BABYLON || (BABYLON = {}));
  12257. //# sourceMappingURL=../../Lights/Shadows/babylon.shadowGenerator.js.map
  12258. var BABYLON;
  12259. (function (BABYLON) {
  12260. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  12261. if (boxMin.x > sphereCenter.x + sphereRadius)
  12262. return false;
  12263. if (sphereCenter.x - sphereRadius > boxMax.x)
  12264. return false;
  12265. if (boxMin.y > sphereCenter.y + sphereRadius)
  12266. return false;
  12267. if (sphereCenter.y - sphereRadius > boxMax.y)
  12268. return false;
  12269. if (boxMin.z > sphereCenter.z + sphereRadius)
  12270. return false;
  12271. if (sphereCenter.z - sphereRadius > boxMax.z)
  12272. return false;
  12273. return true;
  12274. };
  12275. var getLowestRoot = (function () {
  12276. var result = { root: 0, found: false };
  12277. return function (a, b, c, maxR) {
  12278. result.root = 0;
  12279. result.found = false;
  12280. var determinant = b * b - 4.0 * a * c;
  12281. if (determinant < 0)
  12282. return result;
  12283. var sqrtD = Math.sqrt(determinant);
  12284. var r1 = (-b - sqrtD) / (2.0 * a);
  12285. var r2 = (-b + sqrtD) / (2.0 * a);
  12286. if (r1 > r2) {
  12287. var temp = r2;
  12288. r2 = r1;
  12289. r1 = temp;
  12290. }
  12291. if (r1 > 0 && r1 < maxR) {
  12292. result.root = r1;
  12293. result.found = true;
  12294. return result;
  12295. }
  12296. if (r2 > 0 && r2 < maxR) {
  12297. result.root = r2;
  12298. result.found = true;
  12299. return result;
  12300. }
  12301. return result;
  12302. };
  12303. })();
  12304. var Collider = (function () {
  12305. function Collider() {
  12306. this.radius = new BABYLON.Vector3(1, 1, 1);
  12307. this.retry = 0;
  12308. this.basePointWorld = BABYLON.Vector3.Zero();
  12309. this.velocityWorld = BABYLON.Vector3.Zero();
  12310. this.normalizedVelocity = BABYLON.Vector3.Zero();
  12311. this._collisionPoint = BABYLON.Vector3.Zero();
  12312. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  12313. this._tempVector = BABYLON.Vector3.Zero();
  12314. this._tempVector2 = BABYLON.Vector3.Zero();
  12315. this._tempVector3 = BABYLON.Vector3.Zero();
  12316. this._tempVector4 = BABYLON.Vector3.Zero();
  12317. this._edge = BABYLON.Vector3.Zero();
  12318. this._baseToVertex = BABYLON.Vector3.Zero();
  12319. this._destinationPoint = BABYLON.Vector3.Zero();
  12320. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  12321. this._displacementVector = BABYLON.Vector3.Zero();
  12322. }
  12323. // Methods
  12324. Collider.prototype._initialize = function (source, dir, e) {
  12325. this.velocity = dir;
  12326. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  12327. this.basePoint = source;
  12328. source.multiplyToRef(this.radius, this.basePointWorld);
  12329. dir.multiplyToRef(this.radius, this.velocityWorld);
  12330. this.velocityWorldLength = this.velocityWorld.length();
  12331. this.epsilon = e;
  12332. this.collisionFound = false;
  12333. };
  12334. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  12335. pa.subtractToRef(point, this._tempVector);
  12336. pb.subtractToRef(point, this._tempVector2);
  12337. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  12338. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12339. if (d < 0)
  12340. return false;
  12341. pc.subtractToRef(point, this._tempVector3);
  12342. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  12343. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12344. if (d < 0)
  12345. return false;
  12346. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  12347. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12348. return d >= 0;
  12349. };
  12350. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  12351. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  12352. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  12353. if (distance > this.velocityWorldLength + max + sphereRadius) {
  12354. return false;
  12355. }
  12356. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  12357. return false;
  12358. return true;
  12359. };
  12360. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  12361. var t0;
  12362. var embeddedInPlane = false;
  12363. //defensive programming, actually not needed.
  12364. if (!trianglePlaneArray) {
  12365. trianglePlaneArray = [];
  12366. }
  12367. if (!trianglePlaneArray[faceIndex]) {
  12368. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  12369. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  12370. }
  12371. var trianglePlane = trianglePlaneArray[faceIndex];
  12372. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  12373. return;
  12374. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  12375. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  12376. if (normalDotVelocity == 0) {
  12377. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  12378. return;
  12379. embeddedInPlane = true;
  12380. t0 = 0;
  12381. }
  12382. else {
  12383. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12384. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12385. if (t0 > t1) {
  12386. var temp = t1;
  12387. t1 = t0;
  12388. t0 = temp;
  12389. }
  12390. if (t0 > 1.0 || t1 < 0.0)
  12391. return;
  12392. if (t0 < 0)
  12393. t0 = 0;
  12394. if (t0 > 1.0)
  12395. t0 = 1.0;
  12396. }
  12397. this._collisionPoint.copyFromFloats(0, 0, 0);
  12398. var found = false;
  12399. var t = 1.0;
  12400. if (!embeddedInPlane) {
  12401. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  12402. this.velocity.scaleToRef(t0, this._tempVector);
  12403. this._planeIntersectionPoint.addInPlace(this._tempVector);
  12404. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  12405. found = true;
  12406. t = t0;
  12407. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  12408. }
  12409. }
  12410. if (!found) {
  12411. var velocitySquaredLength = this.velocity.lengthSquared();
  12412. var a = velocitySquaredLength;
  12413. this.basePoint.subtractToRef(p1, this._tempVector);
  12414. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12415. var c = this._tempVector.lengthSquared() - 1.0;
  12416. var lowestRoot = getLowestRoot(a, b, c, t);
  12417. if (lowestRoot.found) {
  12418. t = lowestRoot.root;
  12419. found = true;
  12420. this._collisionPoint.copyFrom(p1);
  12421. }
  12422. this.basePoint.subtractToRef(p2, this._tempVector);
  12423. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12424. c = this._tempVector.lengthSquared() - 1.0;
  12425. lowestRoot = getLowestRoot(a, b, c, t);
  12426. if (lowestRoot.found) {
  12427. t = lowestRoot.root;
  12428. found = true;
  12429. this._collisionPoint.copyFrom(p2);
  12430. }
  12431. this.basePoint.subtractToRef(p3, this._tempVector);
  12432. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12433. c = this._tempVector.lengthSquared() - 1.0;
  12434. lowestRoot = getLowestRoot(a, b, c, t);
  12435. if (lowestRoot.found) {
  12436. t = lowestRoot.root;
  12437. found = true;
  12438. this._collisionPoint.copyFrom(p3);
  12439. }
  12440. p2.subtractToRef(p1, this._edge);
  12441. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12442. var edgeSquaredLength = this._edge.lengthSquared();
  12443. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12444. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12445. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12446. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12447. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12448. lowestRoot = getLowestRoot(a, b, c, t);
  12449. if (lowestRoot.found) {
  12450. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12451. if (f >= 0.0 && f <= 1.0) {
  12452. t = lowestRoot.root;
  12453. found = true;
  12454. this._edge.scaleInPlace(f);
  12455. p1.addToRef(this._edge, this._collisionPoint);
  12456. }
  12457. }
  12458. p3.subtractToRef(p2, this._edge);
  12459. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12460. edgeSquaredLength = this._edge.lengthSquared();
  12461. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12462. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12463. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12464. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12465. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12466. lowestRoot = getLowestRoot(a, b, c, t);
  12467. if (lowestRoot.found) {
  12468. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12469. if (f >= 0.0 && f <= 1.0) {
  12470. t = lowestRoot.root;
  12471. found = true;
  12472. this._edge.scaleInPlace(f);
  12473. p2.addToRef(this._edge, this._collisionPoint);
  12474. }
  12475. }
  12476. p1.subtractToRef(p3, this._edge);
  12477. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12478. edgeSquaredLength = this._edge.lengthSquared();
  12479. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12480. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12481. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12482. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12483. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12484. lowestRoot = getLowestRoot(a, b, c, t);
  12485. if (lowestRoot.found) {
  12486. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12487. if (f >= 0.0 && f <= 1.0) {
  12488. t = lowestRoot.root;
  12489. found = true;
  12490. this._edge.scaleInPlace(f);
  12491. p3.addToRef(this._edge, this._collisionPoint);
  12492. }
  12493. }
  12494. }
  12495. if (found) {
  12496. var distToCollision = t * this.velocity.length();
  12497. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12498. if (!this.intersectionPoint) {
  12499. this.intersectionPoint = this._collisionPoint.clone();
  12500. }
  12501. else {
  12502. this.intersectionPoint.copyFrom(this._collisionPoint);
  12503. }
  12504. this.nearestDistance = distToCollision;
  12505. this.collisionFound = true;
  12506. }
  12507. }
  12508. };
  12509. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12510. for (var i = indexStart; i < indexEnd; i += 3) {
  12511. var p1 = pts[indices[i] - decal];
  12512. var p2 = pts[indices[i + 1] - decal];
  12513. var p3 = pts[indices[i + 2] - decal];
  12514. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12515. }
  12516. };
  12517. Collider.prototype._getResponse = function (pos, vel) {
  12518. pos.addToRef(vel, this._destinationPoint);
  12519. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12520. this.basePoint.addToRef(vel, pos);
  12521. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12522. this._slidePlaneNormal.normalize();
  12523. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12524. pos.addInPlace(this._displacementVector);
  12525. this.intersectionPoint.addInPlace(this._displacementVector);
  12526. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12527. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12528. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12529. };
  12530. return Collider;
  12531. }());
  12532. BABYLON.Collider = Collider;
  12533. })(BABYLON || (BABYLON = {}));
  12534. //# sourceMappingURL=../Collisions/babylon.collider.js.map
  12535. var BABYLON;
  12536. (function (BABYLON) {
  12537. //WebWorker code will be inserted to this variable.
  12538. BABYLON.CollisionWorker = "";
  12539. (function (WorkerTaskType) {
  12540. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12541. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12542. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12543. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12544. var WorkerTaskType = BABYLON.WorkerTaskType;
  12545. (function (WorkerReplyType) {
  12546. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12547. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12548. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12549. var WorkerReplyType = BABYLON.WorkerReplyType;
  12550. var CollisionCoordinatorWorker = (function () {
  12551. function CollisionCoordinatorWorker() {
  12552. var _this = this;
  12553. this._scaledPosition = BABYLON.Vector3.Zero();
  12554. this._scaledVelocity = BABYLON.Vector3.Zero();
  12555. this.onMeshUpdated = function (mesh) {
  12556. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12557. };
  12558. this.onGeometryUpdated = function (geometry) {
  12559. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12560. };
  12561. this._afterRender = function () {
  12562. if (!_this._init)
  12563. return;
  12564. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12565. return;
  12566. }
  12567. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12568. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12569. if (_this._runningUpdated > 4) {
  12570. return;
  12571. }
  12572. ++_this._runningUpdated;
  12573. var payload = {
  12574. updatedMeshes: _this._addUpdateMeshesList,
  12575. updatedGeometries: _this._addUpdateGeometriesList,
  12576. removedGeometries: _this._toRemoveGeometryArray,
  12577. removedMeshes: _this._toRemoveMeshesArray
  12578. };
  12579. var message = {
  12580. payload: payload,
  12581. taskType: WorkerTaskType.UPDATE
  12582. };
  12583. var serializable = [];
  12584. for (var id in payload.updatedGeometries) {
  12585. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12586. //prepare transferables
  12587. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12588. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12589. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12590. }
  12591. }
  12592. _this._worker.postMessage(message, serializable);
  12593. _this._addUpdateMeshesList = {};
  12594. _this._addUpdateGeometriesList = {};
  12595. _this._toRemoveGeometryArray = [];
  12596. _this._toRemoveMeshesArray = [];
  12597. };
  12598. this._onMessageFromWorker = function (e) {
  12599. var returnData = e.data;
  12600. if (returnData.error != WorkerReplyType.SUCCESS) {
  12601. //TODO what errors can be returned from the worker?
  12602. BABYLON.Tools.Warn("error returned from worker!");
  12603. return;
  12604. }
  12605. switch (returnData.taskType) {
  12606. case WorkerTaskType.INIT:
  12607. _this._init = true;
  12608. //Update the worked with ALL of the scene's current state
  12609. _this._scene.meshes.forEach(function (mesh) {
  12610. _this.onMeshAdded(mesh);
  12611. });
  12612. _this._scene.getGeometries().forEach(function (geometry) {
  12613. _this.onGeometryAdded(geometry);
  12614. });
  12615. break;
  12616. case WorkerTaskType.UPDATE:
  12617. _this._runningUpdated--;
  12618. break;
  12619. case WorkerTaskType.COLLIDE:
  12620. _this._runningCollisionTask = false;
  12621. var returnPayload = returnData.payload;
  12622. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12623. return;
  12624. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12625. //cleanup
  12626. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12627. break;
  12628. }
  12629. };
  12630. this._collisionsCallbackArray = [];
  12631. this._init = false;
  12632. this._runningUpdated = 0;
  12633. this._runningCollisionTask = false;
  12634. this._addUpdateMeshesList = {};
  12635. this._addUpdateGeometriesList = {};
  12636. this._toRemoveGeometryArray = [];
  12637. this._toRemoveMeshesArray = [];
  12638. }
  12639. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12640. if (!this._init)
  12641. return;
  12642. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12643. return;
  12644. position.divideToRef(collider.radius, this._scaledPosition);
  12645. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12646. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12647. var payload = {
  12648. collider: {
  12649. position: this._scaledPosition.asArray(),
  12650. velocity: this._scaledVelocity.asArray(),
  12651. radius: collider.radius.asArray()
  12652. },
  12653. collisionId: collisionIndex,
  12654. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12655. maximumRetry: maximumRetry
  12656. };
  12657. var message = {
  12658. payload: payload,
  12659. taskType: WorkerTaskType.COLLIDE
  12660. };
  12661. this._worker.postMessage(message);
  12662. };
  12663. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12664. this._scene = scene;
  12665. this._scene.registerAfterRender(this._afterRender);
  12666. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12667. this._worker = new Worker(workerUrl);
  12668. this._worker.onmessage = this._onMessageFromWorker;
  12669. var message = {
  12670. payload: {},
  12671. taskType: WorkerTaskType.INIT
  12672. };
  12673. this._worker.postMessage(message);
  12674. };
  12675. CollisionCoordinatorWorker.prototype.destroy = function () {
  12676. this._scene.unregisterAfterRender(this._afterRender);
  12677. this._worker.terminate();
  12678. };
  12679. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12680. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12681. this.onMeshUpdated(mesh);
  12682. };
  12683. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12684. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12685. };
  12686. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12687. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12688. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12689. this.onGeometryUpdated(geometry);
  12690. };
  12691. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12692. this._toRemoveGeometryArray.push(geometry.id);
  12693. };
  12694. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12695. var submeshes = [];
  12696. if (mesh.subMeshes) {
  12697. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12698. return {
  12699. position: idx,
  12700. verticesStart: sm.verticesStart,
  12701. verticesCount: sm.verticesCount,
  12702. indexStart: sm.indexStart,
  12703. indexCount: sm.indexCount,
  12704. hasMaterial: !!sm.getMaterial(),
  12705. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12706. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12707. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12708. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12709. };
  12710. });
  12711. }
  12712. var geometryId = null;
  12713. if (mesh instanceof BABYLON.Mesh) {
  12714. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12715. }
  12716. else if (mesh instanceof BABYLON.InstancedMesh) {
  12717. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12718. }
  12719. return {
  12720. uniqueId: mesh.uniqueId,
  12721. id: mesh.id,
  12722. name: mesh.name,
  12723. geometryId: geometryId,
  12724. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12725. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12726. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12727. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12728. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12729. subMeshes: submeshes,
  12730. checkCollisions: mesh.checkCollisions
  12731. };
  12732. };
  12733. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12734. return {
  12735. id: geometry.id,
  12736. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12737. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12738. indices: new Int32Array(geometry.getIndices() || []),
  12739. };
  12740. };
  12741. return CollisionCoordinatorWorker;
  12742. }());
  12743. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12744. var CollisionCoordinatorLegacy = (function () {
  12745. function CollisionCoordinatorLegacy() {
  12746. this._scaledPosition = BABYLON.Vector3.Zero();
  12747. this._scaledVelocity = BABYLON.Vector3.Zero();
  12748. this._finalPosition = BABYLON.Vector3.Zero();
  12749. }
  12750. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12751. position.divideToRef(collider.radius, this._scaledPosition);
  12752. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12753. collider.collidedMesh = null;
  12754. collider.retry = 0;
  12755. collider.initialVelocity = this._scaledVelocity;
  12756. collider.initialPosition = this._scaledPosition;
  12757. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12758. this._finalPosition.multiplyInPlace(collider.radius);
  12759. //run the callback
  12760. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12761. };
  12762. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12763. this._scene = scene;
  12764. };
  12765. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12766. //Legacy need no destruction method.
  12767. };
  12768. //No update in legacy mode
  12769. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12770. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12771. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12772. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12773. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12774. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12775. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12776. if (excludedMesh === void 0) { excludedMesh = null; }
  12777. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12778. if (collider.retry >= maximumRetry) {
  12779. finalPosition.copyFrom(position);
  12780. return;
  12781. }
  12782. collider._initialize(position, velocity, closeDistance);
  12783. // Check all meshes
  12784. for (var index = 0; index < this._scene.meshes.length; index++) {
  12785. var mesh = this._scene.meshes[index];
  12786. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12787. mesh._checkCollision(collider);
  12788. }
  12789. }
  12790. if (!collider.collisionFound) {
  12791. position.addToRef(velocity, finalPosition);
  12792. return;
  12793. }
  12794. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12795. collider._getResponse(position, velocity);
  12796. }
  12797. if (velocity.length() <= closeDistance) {
  12798. finalPosition.copyFrom(position);
  12799. return;
  12800. }
  12801. collider.retry++;
  12802. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12803. };
  12804. return CollisionCoordinatorLegacy;
  12805. }());
  12806. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12807. })(BABYLON || (BABYLON = {}));
  12808. //# sourceMappingURL=../Collisions/babylon.collisionCoordinator.js.map
  12809. var BABYLON;
  12810. (function (BABYLON) {
  12811. var Camera = (function (_super) {
  12812. __extends(Camera, _super);
  12813. function Camera(name, position, scene) {
  12814. _super.call(this, name, scene);
  12815. this.upVector = BABYLON.Vector3.Up();
  12816. this.orthoLeft = null;
  12817. this.orthoRight = null;
  12818. this.orthoBottom = null;
  12819. this.orthoTop = null;
  12820. this.fov = 0.8;
  12821. this.minZ = 1.0;
  12822. this.maxZ = 10000.0;
  12823. this.inertia = 0.9;
  12824. this.mode = Camera.PERSPECTIVE_CAMERA;
  12825. this.isIntermediate = false;
  12826. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12827. this.layerMask = 0x0FFFFFFF;
  12828. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12829. // Camera rig members
  12830. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12831. this._rigCameras = new Array();
  12832. // Cache
  12833. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12834. this._projectionMatrix = new BABYLON.Matrix();
  12835. this._doNotComputeProjectionMatrix = false;
  12836. this._postProcesses = new Array();
  12837. this._transformMatrix = BABYLON.Matrix.Zero();
  12838. this._webvrViewMatrix = BABYLON.Matrix.Identity();
  12839. this._activeMeshes = new BABYLON.SmartArray(256);
  12840. this._globalPosition = BABYLON.Vector3.Zero();
  12841. this._refreshFrustumPlanes = true;
  12842. scene.addCamera(this);
  12843. if (!scene.activeCamera) {
  12844. scene.activeCamera = this;
  12845. }
  12846. this.position = position;
  12847. }
  12848. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  12849. get: function () {
  12850. return Camera._PERSPECTIVE_CAMERA;
  12851. },
  12852. enumerable: true,
  12853. configurable: true
  12854. });
  12855. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  12856. get: function () {
  12857. return Camera._ORTHOGRAPHIC_CAMERA;
  12858. },
  12859. enumerable: true,
  12860. configurable: true
  12861. });
  12862. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  12863. get: function () {
  12864. return Camera._FOVMODE_VERTICAL_FIXED;
  12865. },
  12866. enumerable: true,
  12867. configurable: true
  12868. });
  12869. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  12870. get: function () {
  12871. return Camera._FOVMODE_HORIZONTAL_FIXED;
  12872. },
  12873. enumerable: true,
  12874. configurable: true
  12875. });
  12876. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  12877. get: function () {
  12878. return Camera._RIG_MODE_NONE;
  12879. },
  12880. enumerable: true,
  12881. configurable: true
  12882. });
  12883. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  12884. get: function () {
  12885. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  12886. },
  12887. enumerable: true,
  12888. configurable: true
  12889. });
  12890. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  12891. get: function () {
  12892. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  12893. },
  12894. enumerable: true,
  12895. configurable: true
  12896. });
  12897. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  12898. get: function () {
  12899. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12900. },
  12901. enumerable: true,
  12902. configurable: true
  12903. });
  12904. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  12905. get: function () {
  12906. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  12907. },
  12908. enumerable: true,
  12909. configurable: true
  12910. });
  12911. Object.defineProperty(Camera, "RIG_MODE_VR", {
  12912. get: function () {
  12913. return Camera._RIG_MODE_VR;
  12914. },
  12915. enumerable: true,
  12916. configurable: true
  12917. });
  12918. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  12919. get: function () {
  12920. return Camera._RIG_MODE_WEBVR;
  12921. },
  12922. enumerable: true,
  12923. configurable: true
  12924. });
  12925. /**
  12926. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12927. */
  12928. Camera.prototype.toString = function (fullDetails) {
  12929. var ret = "Name: " + this.name;
  12930. ret += ", type: " + this.getTypeName();
  12931. if (this.animations) {
  12932. for (var i = 0; i < this.animations.length; i++) {
  12933. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12934. }
  12935. }
  12936. if (fullDetails) {
  12937. }
  12938. return ret;
  12939. };
  12940. Object.defineProperty(Camera.prototype, "globalPosition", {
  12941. get: function () {
  12942. return this._globalPosition;
  12943. },
  12944. enumerable: true,
  12945. configurable: true
  12946. });
  12947. Camera.prototype.getActiveMeshes = function () {
  12948. return this._activeMeshes;
  12949. };
  12950. Camera.prototype.isActiveMesh = function (mesh) {
  12951. return (this._activeMeshes.indexOf(mesh) !== -1);
  12952. };
  12953. //Cache
  12954. Camera.prototype._initCache = function () {
  12955. _super.prototype._initCache.call(this);
  12956. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12957. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12958. this._cache.mode = undefined;
  12959. this._cache.minZ = undefined;
  12960. this._cache.maxZ = undefined;
  12961. this._cache.fov = undefined;
  12962. this._cache.fovMode = undefined;
  12963. this._cache.aspectRatio = undefined;
  12964. this._cache.orthoLeft = undefined;
  12965. this._cache.orthoRight = undefined;
  12966. this._cache.orthoBottom = undefined;
  12967. this._cache.orthoTop = undefined;
  12968. this._cache.renderWidth = undefined;
  12969. this._cache.renderHeight = undefined;
  12970. };
  12971. Camera.prototype._updateCache = function (ignoreParentClass) {
  12972. if (!ignoreParentClass) {
  12973. _super.prototype._updateCache.call(this);
  12974. }
  12975. var engine = this.getEngine();
  12976. this._cache.position.copyFrom(this.position);
  12977. this._cache.upVector.copyFrom(this.upVector);
  12978. this._cache.mode = this.mode;
  12979. this._cache.minZ = this.minZ;
  12980. this._cache.maxZ = this.maxZ;
  12981. this._cache.fov = this.fov;
  12982. this._cache.fovMode = this.fovMode;
  12983. this._cache.aspectRatio = engine.getAspectRatio(this);
  12984. this._cache.orthoLeft = this.orthoLeft;
  12985. this._cache.orthoRight = this.orthoRight;
  12986. this._cache.orthoBottom = this.orthoBottom;
  12987. this._cache.orthoTop = this.orthoTop;
  12988. this._cache.renderWidth = engine.getRenderWidth();
  12989. this._cache.renderHeight = engine.getRenderHeight();
  12990. };
  12991. Camera.prototype._updateFromScene = function () {
  12992. this.updateCache();
  12993. this.update();
  12994. };
  12995. // Synchronized
  12996. Camera.prototype._isSynchronized = function () {
  12997. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  12998. };
  12999. Camera.prototype._isSynchronizedViewMatrix = function () {
  13000. if (!_super.prototype._isSynchronized.call(this))
  13001. return false;
  13002. return this._cache.position.equals(this.position)
  13003. && this._cache.upVector.equals(this.upVector)
  13004. && this.isSynchronizedWithParent();
  13005. };
  13006. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13007. var check = this._cache.mode === this.mode
  13008. && this._cache.minZ === this.minZ
  13009. && this._cache.maxZ === this.maxZ;
  13010. if (!check) {
  13011. return false;
  13012. }
  13013. var engine = this.getEngine();
  13014. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13015. check = this._cache.fov === this.fov
  13016. && this._cache.fovMode === this.fovMode
  13017. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13018. }
  13019. else {
  13020. check = this._cache.orthoLeft === this.orthoLeft
  13021. && this._cache.orthoRight === this.orthoRight
  13022. && this._cache.orthoBottom === this.orthoBottom
  13023. && this._cache.orthoTop === this.orthoTop
  13024. && this._cache.renderWidth === engine.getRenderWidth()
  13025. && this._cache.renderHeight === engine.getRenderHeight();
  13026. }
  13027. return check;
  13028. };
  13029. // Controls
  13030. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13031. };
  13032. Camera.prototype.detachControl = function (element) {
  13033. };
  13034. Camera.prototype.update = function () {
  13035. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13036. this._updateRigCameras();
  13037. }
  13038. this._checkInputs();
  13039. };
  13040. Camera.prototype._checkInputs = function () {
  13041. };
  13042. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13043. // invalidate framebuffer
  13044. if (this._postProcesses.length > 0) {
  13045. this._postProcesses[0].markTextureDirty();
  13046. }
  13047. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13048. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13049. var cam = this._rigCameras[i];
  13050. var rigPostProcess = cam._rigPostProcess;
  13051. // for VR rig, there does not have to be a post process
  13052. if (rigPostProcess) {
  13053. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13054. if (isPass) {
  13055. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13056. cam.isIntermediate = this._postProcesses.length === 0;
  13057. }
  13058. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13059. rigPostProcess.markTextureDirty();
  13060. }
  13061. else {
  13062. cam._postProcesses = this._postProcesses.slice(0);
  13063. }
  13064. }
  13065. };
  13066. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13067. if (insertAt === void 0) { insertAt = null; }
  13068. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13069. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13070. return 0;
  13071. }
  13072. if (insertAt == null || insertAt < 0) {
  13073. this._postProcesses.push(postProcess);
  13074. }
  13075. else {
  13076. this._postProcesses.splice(insertAt, 0, postProcess);
  13077. }
  13078. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13079. return this._postProcesses.indexOf(postProcess);
  13080. };
  13081. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13082. if (atIndices === void 0) { atIndices = null; }
  13083. var result = [];
  13084. var i;
  13085. var index;
  13086. if (!atIndices) {
  13087. var idx = this._postProcesses.indexOf(postProcess);
  13088. if (idx !== -1) {
  13089. this._postProcesses.splice(idx, 1);
  13090. }
  13091. }
  13092. else {
  13093. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13094. // iterate descending, so can just splice as we go
  13095. for (i = atIndices.length - 1; i >= 0; i--) {
  13096. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13097. result.push(i);
  13098. continue;
  13099. }
  13100. this._postProcesses.splice(index, 1);
  13101. }
  13102. }
  13103. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13104. return result;
  13105. };
  13106. Camera.prototype.getWorldMatrix = function () {
  13107. if (!this._worldMatrix) {
  13108. this._worldMatrix = BABYLON.Matrix.Identity();
  13109. }
  13110. var viewMatrix = this.getViewMatrix();
  13111. viewMatrix.invertToRef(this._worldMatrix);
  13112. return this._worldMatrix;
  13113. };
  13114. Camera.prototype._getViewMatrix = function () {
  13115. return BABYLON.Matrix.Identity();
  13116. };
  13117. Camera.prototype.getViewMatrix = function (force) {
  13118. this._computedViewMatrix = this._computeViewMatrix(force);
  13119. if (!force && this._isSynchronizedViewMatrix()) {
  13120. return this._computedViewMatrix;
  13121. }
  13122. this._refreshFrustumPlanes = true;
  13123. if (!this.parent || !this.parent.getWorldMatrix) {
  13124. this._globalPosition.copyFrom(this.position);
  13125. }
  13126. else {
  13127. if (!this._worldMatrix) {
  13128. this._worldMatrix = BABYLON.Matrix.Identity();
  13129. }
  13130. this._computedViewMatrix.invertToRef(this._worldMatrix);
  13131. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  13132. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  13133. this._computedViewMatrix.invert();
  13134. this._markSyncedWithParent();
  13135. }
  13136. this._currentRenderId = this.getScene().getRenderId();
  13137. return this._computedViewMatrix;
  13138. };
  13139. Camera.prototype._computeViewMatrix = function (force) {
  13140. if (!force && this._isSynchronizedViewMatrix()) {
  13141. return this._computedViewMatrix;
  13142. }
  13143. this._computedViewMatrix = this._getViewMatrix();
  13144. this._currentRenderId = this.getScene().getRenderId();
  13145. return this._computedViewMatrix;
  13146. };
  13147. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13148. this._doNotComputeProjectionMatrix = true;
  13149. if (projection !== undefined) {
  13150. this._projectionMatrix = projection;
  13151. }
  13152. };
  13153. ;
  13154. Camera.prototype.unfreezeProjectionMatrix = function () {
  13155. this._doNotComputeProjectionMatrix = false;
  13156. };
  13157. ;
  13158. Camera.prototype.getProjectionMatrix = function (force) {
  13159. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13160. return this._projectionMatrix;
  13161. }
  13162. this._refreshFrustumPlanes = true;
  13163. var engine = this.getEngine();
  13164. var scene = this.getScene();
  13165. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13166. if (this.minZ <= 0) {
  13167. this.minZ = 0.1;
  13168. }
  13169. if (scene.useRightHandedSystem) {
  13170. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13171. }
  13172. else {
  13173. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13174. }
  13175. return this._projectionMatrix;
  13176. }
  13177. var halfWidth = engine.getRenderWidth() / 2.0;
  13178. var halfHeight = engine.getRenderHeight() / 2.0;
  13179. if (scene.useRightHandedSystem) {
  13180. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13181. }
  13182. else {
  13183. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13184. }
  13185. return this._projectionMatrix;
  13186. };
  13187. Camera.prototype.getTranformationMatrix = function () {
  13188. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13189. return this._transformMatrix;
  13190. };
  13191. Camera.prototype.updateFrustumPlanes = function () {
  13192. if (!this._refreshFrustumPlanes) {
  13193. return;
  13194. }
  13195. this.getTranformationMatrix();
  13196. if (!this._frustumPlanes) {
  13197. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13198. }
  13199. else {
  13200. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13201. }
  13202. this._refreshFrustumPlanes = false;
  13203. };
  13204. Camera.prototype.isInFrustum = function (target) {
  13205. this.updateFrustumPlanes();
  13206. return target.isInFrustum(this._frustumPlanes);
  13207. };
  13208. Camera.prototype.isCompletelyInFrustum = function (target) {
  13209. this.updateFrustumPlanes();
  13210. return target.isCompletelyInFrustum(this._frustumPlanes);
  13211. };
  13212. Camera.prototype.dispose = function () {
  13213. // Animations
  13214. this.getScene().stopAnimation(this);
  13215. // Remove from scene
  13216. this.getScene().removeCamera(this);
  13217. while (this._rigCameras.length > 0) {
  13218. this._rigCameras.pop().dispose();
  13219. }
  13220. // Postprocesses
  13221. for (var i = 0; i < this._postProcesses.length; ++i) {
  13222. this._postProcesses[i].dispose(this);
  13223. }
  13224. _super.prototype.dispose.call(this);
  13225. };
  13226. // ---- Camera rigs section ----
  13227. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13228. while (this._rigCameras.length > 0) {
  13229. this._rigCameras.pop().dispose();
  13230. }
  13231. this.cameraRigMode = mode;
  13232. this._cameraRigParams = {};
  13233. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13234. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13235. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13236. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13237. // create the rig cameras, unless none
  13238. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13239. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13240. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13241. }
  13242. switch (this.cameraRigMode) {
  13243. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13244. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13245. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13246. break;
  13247. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13248. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13249. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13250. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13251. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13252. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13253. break;
  13254. case Camera.RIG_MODE_VR:
  13255. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13256. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13257. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13258. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13259. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13260. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13261. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13262. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13263. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13264. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13265. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13266. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13267. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13268. if (metrics.compensateDistortion) {
  13269. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13270. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13271. }
  13272. break;
  13273. case Camera.RIG_MODE_WEBVR:
  13274. if (rigParams.vrDisplay) {
  13275. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13276. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13277. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13278. this._rigCameras[0].setCameraRigParameter("left", true);
  13279. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13280. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  13281. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13282. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13283. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13284. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13285. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13286. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  13287. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13288. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13289. }
  13290. break;
  13291. }
  13292. this._cascadePostProcessesToRigCams();
  13293. this.
  13294. update();
  13295. };
  13296. Camera.prototype._getVRProjectionMatrix = function () {
  13297. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13298. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13299. return this._projectionMatrix;
  13300. };
  13301. Camera.prototype._getWebVRProjectionMatrix = function () {
  13302. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  13303. //babylon compatible matrix
  13304. [8, 9, 10, 11].forEach(function (num) {
  13305. projectionArray[num] *= -1;
  13306. });
  13307. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  13308. return this._projectionMatrix;
  13309. };
  13310. //Can be used, but we'll use the free camera's view matrix calculation
  13311. Camera.prototype._getWebVRViewMatrix = function () {
  13312. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  13313. //babylon compatible matrix
  13314. [8, 9, 10, 11].forEach(function (num) {
  13315. projectionArray[num] *= -1;
  13316. });
  13317. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  13318. return this._webvrViewMatrix;
  13319. };
  13320. Camera.prototype.setCameraRigParameter = function (name, value) {
  13321. if (!this._cameraRigParams) {
  13322. this._cameraRigParams = {};
  13323. }
  13324. this._cameraRigParams[name] = value;
  13325. //provisionnally:
  13326. if (name === "interaxialDistance") {
  13327. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13328. }
  13329. };
  13330. /**
  13331. * needs to be overridden by children so sub has required properties to be copied
  13332. */
  13333. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13334. return null;
  13335. };
  13336. /**
  13337. * May need to be overridden by children
  13338. */
  13339. Camera.prototype._updateRigCameras = function () {
  13340. for (var i = 0; i < this._rigCameras.length; i++) {
  13341. this._rigCameras[i].minZ = this.minZ;
  13342. this._rigCameras[i].maxZ = this.maxZ;
  13343. this._rigCameras[i].fov = this.fov;
  13344. }
  13345. // only update viewport when ANAGLYPH
  13346. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13347. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13348. }
  13349. };
  13350. Camera.prototype._setupInputs = function () {
  13351. };
  13352. Camera.prototype.serialize = function () {
  13353. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13354. // Type
  13355. serializationObject.type = this.getTypeName();
  13356. // Parent
  13357. if (this.parent) {
  13358. serializationObject.parentId = this.parent.id;
  13359. }
  13360. if (this.inputs) {
  13361. this.inputs.serialize(serializationObject);
  13362. }
  13363. // Animations
  13364. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13365. serializationObject.ranges = this.serializeAnimationRanges();
  13366. return serializationObject;
  13367. };
  13368. Camera.prototype.getTypeName = function () {
  13369. return "Camera";
  13370. };
  13371. Camera.prototype.clone = function (name) {
  13372. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13373. };
  13374. Camera.prototype.getDirection = function (localAxis) {
  13375. var result = BABYLON.Vector3.Zero();
  13376. this.getDirectionToRef(localAxis, result);
  13377. return result;
  13378. };
  13379. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  13380. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13381. };
  13382. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13383. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13384. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13385. switch (type) {
  13386. case "ArcRotateCamera":
  13387. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13388. case "DeviceOrientationCamera":
  13389. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13390. case "FollowCamera":
  13391. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13392. case "ArcFollowCamera":
  13393. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13394. case "GamepadCamera":
  13395. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13396. case "TouchCamera":
  13397. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13398. case "VirtualJoysticksCamera":
  13399. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13400. case "WebVRFreeCamera":
  13401. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13402. case "VRDeviceOrientationFreeCamera":
  13403. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13404. case "AnaglyphArcRotateCamera":
  13405. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13406. case "AnaglyphFreeCamera":
  13407. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13408. case "AnaglyphGamepadCamera":
  13409. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13410. case "AnaglyphUniversalCamera":
  13411. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13412. case "StereoscopicArcRotateCamera":
  13413. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13414. case "StereoscopicFreeCamera":
  13415. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13416. case "StereoscopicGamepadCamera":
  13417. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13418. case "StereoscopicUniversalCamera":
  13419. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13420. case "FreeCamera":
  13421. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13422. default:
  13423. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13424. }
  13425. };
  13426. Camera.Parse = function (parsedCamera, scene) {
  13427. var type = parsedCamera.type;
  13428. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13429. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13430. // Parent
  13431. if (parsedCamera.parentId) {
  13432. camera._waitingParentId = parsedCamera.parentId;
  13433. }
  13434. //If camera has an input manager, let it parse inputs settings
  13435. if (camera.inputs) {
  13436. camera.inputs.parse(parsedCamera);
  13437. camera._setupInputs();
  13438. }
  13439. // Target
  13440. if (parsedCamera.target) {
  13441. if (camera.setTarget) {
  13442. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13443. }
  13444. }
  13445. // Apply 3d rig, when found
  13446. if (parsedCamera.cameraRigMode) {
  13447. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13448. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13449. }
  13450. // Animations
  13451. if (parsedCamera.animations) {
  13452. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13453. var parsedAnimation = parsedCamera.animations[animationIndex];
  13454. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13455. }
  13456. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13457. }
  13458. if (parsedCamera.autoAnimate) {
  13459. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13460. }
  13461. return camera;
  13462. };
  13463. // Statics
  13464. Camera._PERSPECTIVE_CAMERA = 0;
  13465. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13466. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13467. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13468. Camera._RIG_MODE_NONE = 0;
  13469. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13470. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13471. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13472. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13473. Camera._RIG_MODE_VR = 20;
  13474. Camera._RIG_MODE_WEBVR = 21;
  13475. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13476. __decorate([
  13477. BABYLON.serializeAsVector3()
  13478. ], Camera.prototype, "position", void 0);
  13479. __decorate([
  13480. BABYLON.serializeAsVector3()
  13481. ], Camera.prototype, "upVector", void 0);
  13482. __decorate([
  13483. BABYLON.serialize()
  13484. ], Camera.prototype, "orthoLeft", void 0);
  13485. __decorate([
  13486. BABYLON.serialize()
  13487. ], Camera.prototype, "orthoRight", void 0);
  13488. __decorate([
  13489. BABYLON.serialize()
  13490. ], Camera.prototype, "orthoBottom", void 0);
  13491. __decorate([
  13492. BABYLON.serialize()
  13493. ], Camera.prototype, "orthoTop", void 0);
  13494. __decorate([
  13495. BABYLON.serialize()
  13496. ], Camera.prototype, "fov", void 0);
  13497. __decorate([
  13498. BABYLON.serialize()
  13499. ], Camera.prototype, "minZ", void 0);
  13500. __decorate([
  13501. BABYLON.serialize()
  13502. ], Camera.prototype, "maxZ", void 0);
  13503. __decorate([
  13504. BABYLON.serialize()
  13505. ], Camera.prototype, "inertia", void 0);
  13506. __decorate([
  13507. BABYLON.serialize()
  13508. ], Camera.prototype, "mode", void 0);
  13509. __decorate([
  13510. BABYLON.serialize()
  13511. ], Camera.prototype, "layerMask", void 0);
  13512. __decorate([
  13513. BABYLON.serialize()
  13514. ], Camera.prototype, "fovMode", void 0);
  13515. __decorate([
  13516. BABYLON.serialize()
  13517. ], Camera.prototype, "cameraRigMode", void 0);
  13518. __decorate([
  13519. BABYLON.serialize()
  13520. ], Camera.prototype, "interaxialDistance", void 0);
  13521. __decorate([
  13522. BABYLON.serialize()
  13523. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13524. return Camera;
  13525. }(BABYLON.Node));
  13526. BABYLON.Camera = Camera;
  13527. })(BABYLON || (BABYLON = {}));
  13528. //# sourceMappingURL=../Cameras/babylon.camera.js.map
  13529. var BABYLON;
  13530. (function (BABYLON) {
  13531. BABYLON.CameraInputTypes = {};
  13532. var CameraInputsManager = (function () {
  13533. function CameraInputsManager(camera) {
  13534. this.attached = {};
  13535. this.camera = camera;
  13536. this.checkInputs = function () { };
  13537. }
  13538. CameraInputsManager.prototype.add = function (input) {
  13539. var type = input.getSimpleName();
  13540. if (this.attached[type]) {
  13541. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13542. return;
  13543. }
  13544. this.attached[type] = input;
  13545. input.camera = this.camera;
  13546. //for checkInputs, we are dynamically creating a function
  13547. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13548. if (input.checkInputs) {
  13549. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13550. }
  13551. if (this.attachedElement) {
  13552. input.attachControl(this.attachedElement);
  13553. }
  13554. };
  13555. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13556. for (var cam in this.attached) {
  13557. var input = this.attached[cam];
  13558. if (input === inputToRemove) {
  13559. input.detachControl(this.attachedElement);
  13560. delete this.attached[cam];
  13561. this.rebuildInputCheck();
  13562. }
  13563. }
  13564. };
  13565. CameraInputsManager.prototype.removeByType = function (inputType) {
  13566. for (var cam in this.attached) {
  13567. var input = this.attached[cam];
  13568. if (input.getTypeName() === inputType) {
  13569. input.detachControl(this.attachedElement);
  13570. delete this.attached[cam];
  13571. this.rebuildInputCheck();
  13572. }
  13573. }
  13574. };
  13575. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  13576. var current = this.checkInputs;
  13577. return function () {
  13578. current();
  13579. fn();
  13580. };
  13581. };
  13582. CameraInputsManager.prototype.attachInput = function (input) {
  13583. input.attachControl(this.attachedElement, this.noPreventDefault);
  13584. };
  13585. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  13586. if (this.attachedElement) {
  13587. return;
  13588. }
  13589. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13590. this.attachedElement = element;
  13591. this.noPreventDefault = noPreventDefault;
  13592. for (var cam in this.attached) {
  13593. var input = this.attached[cam];
  13594. this.attached[cam].attachControl(element, noPreventDefault);
  13595. }
  13596. };
  13597. CameraInputsManager.prototype.detachElement = function (element) {
  13598. if (this.attachedElement !== element) {
  13599. return;
  13600. }
  13601. for (var cam in this.attached) {
  13602. var input = this.attached[cam];
  13603. this.attached[cam].detachControl(element);
  13604. }
  13605. this.attachedElement = null;
  13606. };
  13607. CameraInputsManager.prototype.rebuildInputCheck = function () {
  13608. this.checkInputs = function () { };
  13609. for (var cam in this.attached) {
  13610. var input = this.attached[cam];
  13611. if (input.checkInputs) {
  13612. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13613. }
  13614. }
  13615. };
  13616. CameraInputsManager.prototype.clear = function () {
  13617. if (this.attachedElement) {
  13618. this.detachElement(this.attachedElement);
  13619. }
  13620. this.attached = {};
  13621. this.attachedElement = null;
  13622. this.checkInputs = function () { };
  13623. };
  13624. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13625. var inputs = {};
  13626. for (var cam in this.attached) {
  13627. var input = this.attached[cam];
  13628. var res = BABYLON.SerializationHelper.Serialize(input);
  13629. inputs[input.getTypeName()] = res;
  13630. }
  13631. serializedCamera.inputsmgr = inputs;
  13632. };
  13633. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13634. var parsedInputs = parsedCamera.inputsmgr;
  13635. if (parsedInputs) {
  13636. this.clear();
  13637. for (var n in parsedInputs) {
  13638. var construct = BABYLON.CameraInputTypes[n];
  13639. if (construct) {
  13640. var parsedinput = parsedInputs[n];
  13641. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13642. this.add(input);
  13643. }
  13644. }
  13645. }
  13646. else {
  13647. //2016-03-08 this part is for managing backward compatibility
  13648. for (var n in this.attached) {
  13649. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13650. if (construct) {
  13651. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13652. this.remove(this.attached[n]);
  13653. this.add(input);
  13654. }
  13655. }
  13656. }
  13657. };
  13658. return CameraInputsManager;
  13659. }());
  13660. BABYLON.CameraInputsManager = CameraInputsManager;
  13661. })(BABYLON || (BABYLON = {}));
  13662. //# sourceMappingURL=../Cameras/babylon.cameraInputsManager.js.map
  13663. var BABYLON;
  13664. (function (BABYLON) {
  13665. var FreeCameraMouseInput = (function () {
  13666. function FreeCameraMouseInput(touchEnabled) {
  13667. if (touchEnabled === void 0) { touchEnabled = true; }
  13668. this.touchEnabled = touchEnabled;
  13669. this.buttons = [0, 1, 2];
  13670. this.angularSensibility = 2000.0;
  13671. }
  13672. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13673. var _this = this;
  13674. var engine = this.camera.getEngine();
  13675. if (!this._pointerInput) {
  13676. this._pointerInput = function (p, s) {
  13677. var evt = p.event;
  13678. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13679. return;
  13680. }
  13681. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  13682. return;
  13683. }
  13684. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13685. try {
  13686. evt.srcElement.setPointerCapture(evt.pointerId);
  13687. }
  13688. catch (e) {
  13689. }
  13690. _this.previousPosition = {
  13691. x: evt.clientX,
  13692. y: evt.clientY
  13693. };
  13694. if (!noPreventDefault) {
  13695. evt.preventDefault();
  13696. element.focus();
  13697. }
  13698. }
  13699. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13700. try {
  13701. evt.srcElement.releasePointerCapture(evt.pointerId);
  13702. }
  13703. catch (e) {
  13704. }
  13705. _this.previousPosition = null;
  13706. if (!noPreventDefault) {
  13707. evt.preventDefault();
  13708. }
  13709. }
  13710. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13711. if (!_this.previousPosition || engine.isPointerLock) {
  13712. return;
  13713. }
  13714. var offsetX = evt.clientX - _this.previousPosition.x;
  13715. var offsetY = evt.clientY - _this.previousPosition.y;
  13716. if (_this.camera.getScene().useRightHandedSystem) {
  13717. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13718. }
  13719. else {
  13720. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13721. }
  13722. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13723. _this.previousPosition = {
  13724. x: evt.clientX,
  13725. y: evt.clientY
  13726. };
  13727. if (!noPreventDefault) {
  13728. evt.preventDefault();
  13729. }
  13730. }
  13731. };
  13732. }
  13733. this._onMouseMove = function (evt) {
  13734. if (!engine.isPointerLock) {
  13735. return;
  13736. }
  13737. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13738. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13739. if (_this.camera.getScene().useRightHandedSystem) {
  13740. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13741. }
  13742. else {
  13743. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13744. }
  13745. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13746. _this.previousPosition = null;
  13747. if (!noPreventDefault) {
  13748. evt.preventDefault();
  13749. }
  13750. };
  13751. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13752. element.addEventListener("mousemove", this._onMouseMove, false);
  13753. };
  13754. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13755. if (this._observer && element) {
  13756. this.camera.getScene().onPointerObservable.remove(this._observer);
  13757. element.removeEventListener("mousemove", this._onMouseMove);
  13758. this._observer = null;
  13759. this._onMouseMove = null;
  13760. this.previousPosition = null;
  13761. }
  13762. };
  13763. FreeCameraMouseInput.prototype.getTypeName = function () {
  13764. return "FreeCameraMouseInput";
  13765. };
  13766. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13767. return "mouse";
  13768. };
  13769. __decorate([
  13770. BABYLON.serialize()
  13771. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  13772. __decorate([
  13773. BABYLON.serialize()
  13774. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13775. return FreeCameraMouseInput;
  13776. }());
  13777. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13778. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13779. })(BABYLON || (BABYLON = {}));
  13780. //# sourceMappingURL=../../Cameras/Inputs/babylon.freecamera.input.mouse.js.map
  13781. var BABYLON;
  13782. (function (BABYLON) {
  13783. var FreeCameraKeyboardMoveInput = (function () {
  13784. function FreeCameraKeyboardMoveInput() {
  13785. this._keys = [];
  13786. this.keysUp = [38];
  13787. this.keysDown = [40];
  13788. this.keysLeft = [37];
  13789. this.keysRight = [39];
  13790. }
  13791. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13792. var _this = this;
  13793. if (!this._onKeyDown) {
  13794. element.tabIndex = 1;
  13795. this._onKeyDown = function (evt) {
  13796. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13797. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13798. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13799. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13800. var index = _this._keys.indexOf(evt.keyCode);
  13801. if (index === -1) {
  13802. _this._keys.push(evt.keyCode);
  13803. }
  13804. if (!noPreventDefault) {
  13805. evt.preventDefault();
  13806. }
  13807. }
  13808. };
  13809. this._onKeyUp = function (evt) {
  13810. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13811. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13812. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13813. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13814. var index = _this._keys.indexOf(evt.keyCode);
  13815. if (index >= 0) {
  13816. _this._keys.splice(index, 1);
  13817. }
  13818. if (!noPreventDefault) {
  13819. evt.preventDefault();
  13820. }
  13821. }
  13822. };
  13823. element.addEventListener("keydown", this._onKeyDown, false);
  13824. element.addEventListener("keyup", this._onKeyUp, false);
  13825. BABYLON.Tools.RegisterTopRootEvents([
  13826. { name: "blur", handler: this._onLostFocus }
  13827. ]);
  13828. }
  13829. };
  13830. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13831. if (this._onKeyDown) {
  13832. element.removeEventListener("keydown", this._onKeyDown);
  13833. element.removeEventListener("keyup", this._onKeyUp);
  13834. BABYLON.Tools.UnregisterTopRootEvents([
  13835. { name: "blur", handler: this._onLostFocus }
  13836. ]);
  13837. this._keys = [];
  13838. this._onKeyDown = null;
  13839. this._onKeyUp = null;
  13840. }
  13841. };
  13842. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13843. if (this._onKeyDown) {
  13844. var camera = this.camera;
  13845. // Keyboard
  13846. for (var index = 0; index < this._keys.length; index++) {
  13847. var keyCode = this._keys[index];
  13848. var speed = camera._computeLocalCameraSpeed();
  13849. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13850. camera._localDirection.copyFromFloats(-speed, 0, 0);
  13851. }
  13852. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13853. camera._localDirection.copyFromFloats(0, 0, speed);
  13854. }
  13855. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13856. camera._localDirection.copyFromFloats(speed, 0, 0);
  13857. }
  13858. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13859. camera._localDirection.copyFromFloats(0, 0, -speed);
  13860. }
  13861. if (camera.getScene().useRightHandedSystem) {
  13862. camera._localDirection.z *= -1;
  13863. }
  13864. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  13865. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  13866. camera.cameraDirection.addInPlace(camera._transformedDirection);
  13867. }
  13868. }
  13869. };
  13870. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13871. return "FreeCameraKeyboardMoveInput";
  13872. };
  13873. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  13874. this._keys = [];
  13875. };
  13876. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13877. return "keyboard";
  13878. };
  13879. __decorate([
  13880. BABYLON.serialize()
  13881. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13882. __decorate([
  13883. BABYLON.serialize()
  13884. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13885. __decorate([
  13886. BABYLON.serialize()
  13887. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13888. __decorate([
  13889. BABYLON.serialize()
  13890. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13891. return FreeCameraKeyboardMoveInput;
  13892. }());
  13893. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  13894. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  13895. })(BABYLON || (BABYLON = {}));
  13896. //# sourceMappingURL=../../Cameras/Inputs/babylon.freecamera.input.keyboard.js.map
  13897. var BABYLON;
  13898. (function (BABYLON) {
  13899. var FreeCameraTouchInput = (function () {
  13900. function FreeCameraTouchInput() {
  13901. this._offsetX = null;
  13902. this._offsetY = null;
  13903. this._pointerCount = 0;
  13904. this._pointerPressed = [];
  13905. this.touchAngularSensibility = 200000.0;
  13906. this.touchMoveSensibility = 250.0;
  13907. }
  13908. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  13909. var _this = this;
  13910. var previousPosition;
  13911. if (this._pointerInput === undefined) {
  13912. this._onLostFocus = function (evt) {
  13913. _this._offsetX = null;
  13914. _this._offsetY = null;
  13915. };
  13916. this._pointerInput = function (p, s) {
  13917. var evt = p.event;
  13918. if (evt.pointerType === "mouse") {
  13919. return;
  13920. }
  13921. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13922. if (!noPreventDefault) {
  13923. evt.preventDefault();
  13924. }
  13925. _this._pointerPressed.push(evt.pointerId);
  13926. if (_this._pointerPressed.length !== 1) {
  13927. return;
  13928. }
  13929. previousPosition = {
  13930. x: evt.clientX,
  13931. y: evt.clientY
  13932. };
  13933. }
  13934. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13935. if (!noPreventDefault) {
  13936. evt.preventDefault();
  13937. }
  13938. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13939. if (index === -1) {
  13940. return;
  13941. }
  13942. _this._pointerPressed.splice(index, 1);
  13943. if (index != 0) {
  13944. return;
  13945. }
  13946. previousPosition = null;
  13947. _this._offsetX = null;
  13948. _this._offsetY = null;
  13949. }
  13950. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13951. if (!noPreventDefault) {
  13952. evt.preventDefault();
  13953. }
  13954. if (!previousPosition) {
  13955. return;
  13956. }
  13957. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13958. if (index != 0) {
  13959. return;
  13960. }
  13961. _this._offsetX = evt.clientX - previousPosition.x;
  13962. _this._offsetY = -(evt.clientY - previousPosition.y);
  13963. }
  13964. };
  13965. }
  13966. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13967. element.addEventListener("blur", this._onLostFocus);
  13968. };
  13969. FreeCameraTouchInput.prototype.detachControl = function (element) {
  13970. if (this._pointerInput && element) {
  13971. this.camera.getScene().onPointerObservable.remove(this._observer);
  13972. this._observer = null;
  13973. element.removeEventListener("blur", this._onLostFocus);
  13974. this._onLostFocus = null;
  13975. this._pointerPressed = [];
  13976. this._offsetX = null;
  13977. this._offsetY = null;
  13978. this._pointerCount = 0;
  13979. }
  13980. };
  13981. FreeCameraTouchInput.prototype.checkInputs = function () {
  13982. if (this._offsetX) {
  13983. var camera = this.camera;
  13984. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  13985. if (this._pointerPressed.length > 1) {
  13986. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  13987. }
  13988. else {
  13989. var speed = camera._computeLocalCameraSpeed();
  13990. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  13991. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  13992. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  13993. }
  13994. }
  13995. };
  13996. FreeCameraTouchInput.prototype.getTypeName = function () {
  13997. return "FreeCameraTouchInput";
  13998. };
  13999. FreeCameraTouchInput.prototype.getSimpleName = function () {
  14000. return "touch";
  14001. };
  14002. __decorate([
  14003. BABYLON.serialize()
  14004. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  14005. __decorate([
  14006. BABYLON.serialize()
  14007. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  14008. return FreeCameraTouchInput;
  14009. }());
  14010. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  14011. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  14012. })(BABYLON || (BABYLON = {}));
  14013. //# sourceMappingURL=../../Cameras/Inputs/babylon.freecamera.input.touch.js.map
  14014. var BABYLON;
  14015. (function (BABYLON) {
  14016. var FreeCameraDeviceOrientationInput = (function () {
  14017. function FreeCameraDeviceOrientationInput() {
  14018. var _this = this;
  14019. this._screenOrientationAngle = 0;
  14020. this._screenQuaternion = new BABYLON.Quaternion();
  14021. this._alpha = 0;
  14022. this._beta = 0;
  14023. this._gamma = 0;
  14024. this._orientationChanged = function () {
  14025. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  14026. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  14027. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  14028. };
  14029. this._deviceOrientation = function (evt) {
  14030. _this._alpha = evt.alpha;
  14031. _this._beta = evt.beta;
  14032. _this._gamma = evt.gamma;
  14033. };
  14034. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  14035. this._orientationChanged();
  14036. }
  14037. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  14038. get: function () {
  14039. return this._camera;
  14040. },
  14041. set: function (camera) {
  14042. this._camera = camera;
  14043. if (!this._camera.rotationQuaternion)
  14044. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  14045. },
  14046. enumerable: true,
  14047. configurable: true
  14048. });
  14049. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14050. window.addEventListener("orientationchange", this._orientationChanged);
  14051. window.addEventListener("deviceorientation", this._deviceOrientation);
  14052. //In certain cases, the attach control is called AFTER orientation was changed,
  14053. //So this is needed.
  14054. this._orientationChanged();
  14055. };
  14056. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  14057. window.removeEventListener("orientationchange", this._orientationChanged);
  14058. window.removeEventListener("deviceorientation", this._deviceOrientation);
  14059. };
  14060. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  14061. //if no device orientation provided, don't update the rotation.
  14062. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  14063. if (!this._alpha)
  14064. return;
  14065. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  14066. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  14067. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  14068. //Mirror on XY Plane
  14069. this._camera.rotationQuaternion.z *= -1;
  14070. this._camera.rotationQuaternion.w *= -1;
  14071. };
  14072. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  14073. return "FreeCameraDeviceOrientationInput";
  14074. };
  14075. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  14076. return "deviceOrientation";
  14077. };
  14078. return FreeCameraDeviceOrientationInput;
  14079. }());
  14080. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  14081. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  14082. })(BABYLON || (BABYLON = {}));
  14083. //# sourceMappingURL=../../Cameras/Inputs/babylon.freecamera.input.deviceorientation.js.map
  14084. var BABYLON;
  14085. (function (BABYLON) {
  14086. var FreeCameraGamepadInput = (function () {
  14087. function FreeCameraGamepadInput() {
  14088. this.gamepadAngularSensibility = 200;
  14089. this.gamepadMoveSensibility = 40;
  14090. }
  14091. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14092. var _this = this;
  14093. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14094. };
  14095. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  14096. if (this._gamepads) {
  14097. this._gamepads.dispose();
  14098. }
  14099. this.gamepad = null;
  14100. };
  14101. FreeCameraGamepadInput.prototype.checkInputs = function () {
  14102. if (this.gamepad) {
  14103. var camera = this.camera;
  14104. var LSValues = this.gamepad.leftStick;
  14105. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  14106. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14107. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  14108. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  14109. var RSValues = this.gamepad.rightStick;
  14110. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  14111. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  14112. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  14113. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  14114. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  14115. var speed = camera._computeLocalCameraSpeed() * 50.0;
  14116. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  14117. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  14118. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  14119. }
  14120. };
  14121. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14122. // Only the first gamepad can control the camera
  14123. if (gamepad.index === 0) {
  14124. this.gamepad = gamepad;
  14125. }
  14126. };
  14127. FreeCameraGamepadInput.prototype.getTypeName = function () {
  14128. return "FreeCameraGamepadInput";
  14129. };
  14130. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  14131. return "gamepad";
  14132. };
  14133. __decorate([
  14134. BABYLON.serialize()
  14135. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  14136. __decorate([
  14137. BABYLON.serialize()
  14138. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14139. return FreeCameraGamepadInput;
  14140. }());
  14141. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  14142. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  14143. })(BABYLON || (BABYLON = {}));
  14144. //# sourceMappingURL=../../Cameras/Inputs/babylon.freecamera.input.gamepad.js.map
  14145. var BABYLON;
  14146. (function (BABYLON) {
  14147. var ArcRotateCameraKeyboardMoveInput = (function () {
  14148. function ArcRotateCameraKeyboardMoveInput() {
  14149. this._keys = [];
  14150. this.keysUp = [38];
  14151. this.keysDown = [40];
  14152. this.keysLeft = [37];
  14153. this.keysRight = [39];
  14154. }
  14155. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  14156. var _this = this;
  14157. element.tabIndex = 1;
  14158. this._onKeyDown = function (evt) {
  14159. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14160. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14161. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14162. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14163. var index = _this._keys.indexOf(evt.keyCode);
  14164. if (index === -1) {
  14165. _this._keys.push(evt.keyCode);
  14166. }
  14167. if (evt.preventDefault) {
  14168. if (!noPreventDefault) {
  14169. evt.preventDefault();
  14170. }
  14171. }
  14172. }
  14173. };
  14174. this._onKeyUp = function (evt) {
  14175. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14176. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14177. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14178. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14179. var index = _this._keys.indexOf(evt.keyCode);
  14180. if (index >= 0) {
  14181. _this._keys.splice(index, 1);
  14182. }
  14183. if (evt.preventDefault) {
  14184. if (!noPreventDefault) {
  14185. evt.preventDefault();
  14186. }
  14187. }
  14188. }
  14189. };
  14190. this._onLostFocus = function () {
  14191. _this._keys = [];
  14192. };
  14193. element.addEventListener("keydown", this._onKeyDown, false);
  14194. element.addEventListener("keyup", this._onKeyUp, false);
  14195. BABYLON.Tools.RegisterTopRootEvents([
  14196. { name: "blur", handler: this._onLostFocus }
  14197. ]);
  14198. };
  14199. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14200. if (element) {
  14201. element.removeEventListener("keydown", this._onKeyDown);
  14202. element.removeEventListener("keyup", this._onKeyUp);
  14203. }
  14204. BABYLON.Tools.UnregisterTopRootEvents([
  14205. { name: "blur", handler: this._onLostFocus }
  14206. ]);
  14207. this._keys = [];
  14208. this._onKeyDown = null;
  14209. this._onKeyUp = null;
  14210. this._onLostFocus = null;
  14211. };
  14212. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14213. if (this._onKeyDown) {
  14214. var camera = this.camera;
  14215. for (var index = 0; index < this._keys.length; index++) {
  14216. var keyCode = this._keys[index];
  14217. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14218. camera.inertialAlphaOffset -= 0.01;
  14219. }
  14220. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14221. camera.inertialBetaOffset -= 0.01;
  14222. }
  14223. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14224. camera.inertialAlphaOffset += 0.01;
  14225. }
  14226. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14227. camera.inertialBetaOffset += 0.01;
  14228. }
  14229. }
  14230. }
  14231. };
  14232. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14233. return "ArcRotateCameraKeyboardMoveInput";
  14234. };
  14235. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14236. return "keyboard";
  14237. };
  14238. __decorate([
  14239. BABYLON.serialize()
  14240. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14241. __decorate([
  14242. BABYLON.serialize()
  14243. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14244. __decorate([
  14245. BABYLON.serialize()
  14246. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14247. __decorate([
  14248. BABYLON.serialize()
  14249. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14250. return ArcRotateCameraKeyboardMoveInput;
  14251. }());
  14252. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  14253. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  14254. })(BABYLON || (BABYLON = {}));
  14255. //# sourceMappingURL=../../Cameras/Inputs/babylon.arcrotatecamera.input.keyboard.js.map
  14256. var BABYLON;
  14257. (function (BABYLON) {
  14258. var ArcRotateCameraMouseWheelInput = (function () {
  14259. function ArcRotateCameraMouseWheelInput() {
  14260. this.wheelPrecision = 3.0;
  14261. }
  14262. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  14263. var _this = this;
  14264. this._wheel = function (p, s) {
  14265. //sanity check - this should be a PointerWheel event.
  14266. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  14267. return;
  14268. var event = p.event;
  14269. var delta = 0;
  14270. if (event.wheelDelta) {
  14271. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  14272. }
  14273. else if (event.detail) {
  14274. delta = -event.detail / _this.wheelPrecision;
  14275. }
  14276. if (delta)
  14277. _this.camera.inertialRadiusOffset += delta;
  14278. if (event.preventDefault) {
  14279. if (!noPreventDefault) {
  14280. event.preventDefault();
  14281. }
  14282. }
  14283. };
  14284. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  14285. };
  14286. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  14287. if (this._observer && element) {
  14288. this.camera.getScene().onPointerObservable.remove(this._observer);
  14289. this._observer = null;
  14290. this._wheel = null;
  14291. }
  14292. };
  14293. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  14294. return "ArcRotateCameraMouseWheelInput";
  14295. };
  14296. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  14297. return "mousewheel";
  14298. };
  14299. __decorate([
  14300. BABYLON.serialize()
  14301. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  14302. return ArcRotateCameraMouseWheelInput;
  14303. }());
  14304. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  14305. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  14306. })(BABYLON || (BABYLON = {}));
  14307. //# sourceMappingURL=../../Cameras/Inputs/babylon.arcrotatecamera.input.mousewheel.js.map
  14308. var BABYLON;
  14309. (function (BABYLON) {
  14310. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14311. var ArcRotateCameraPointersInput = (function () {
  14312. function ArcRotateCameraPointersInput() {
  14313. this.buttons = [0, 1, 2];
  14314. this.angularSensibilityX = 1000.0;
  14315. this.angularSensibilityY = 1000.0;
  14316. this.pinchPrecision = 6.0;
  14317. this.panningSensibility = 50.0;
  14318. this._isPanClick = false;
  14319. this.pinchInwards = true;
  14320. }
  14321. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  14322. var _this = this;
  14323. var engine = this.camera.getEngine();
  14324. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  14325. var pointA, pointB;
  14326. var previousPinchDistance = 0;
  14327. this._pointerInput = function (p, s) {
  14328. var evt = p.event;
  14329. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  14330. return;
  14331. }
  14332. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14333. try {
  14334. evt.srcElement.setPointerCapture(evt.pointerId);
  14335. }
  14336. catch (e) {
  14337. }
  14338. // Manage panning with pan button click
  14339. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  14340. // manage pointers
  14341. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  14342. if (pointA === undefined) {
  14343. pointA = cacheSoloPointer;
  14344. }
  14345. else if (pointB === undefined) {
  14346. pointB = cacheSoloPointer;
  14347. }
  14348. if (!noPreventDefault) {
  14349. evt.preventDefault();
  14350. element.focus();
  14351. }
  14352. }
  14353. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14354. try {
  14355. evt.srcElement.releasePointerCapture(evt.pointerId);
  14356. }
  14357. catch (e) {
  14358. }
  14359. cacheSoloPointer = null;
  14360. previousPinchDistance = 0;
  14361. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  14362. //but emptying completly pointers collection is required to fix a bug on iPhone :
  14363. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  14364. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  14365. pointA = pointB = undefined;
  14366. if (!noPreventDefault) {
  14367. evt.preventDefault();
  14368. }
  14369. }
  14370. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14371. if (!noPreventDefault) {
  14372. evt.preventDefault();
  14373. }
  14374. // One button down
  14375. if (pointA && pointB === undefined) {
  14376. if (_this.panningSensibility !== 0 &&
  14377. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  14378. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  14379. _this.camera
  14380. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  14381. _this.camera
  14382. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  14383. }
  14384. else {
  14385. var offsetX = evt.clientX - cacheSoloPointer.x;
  14386. var offsetY = evt.clientY - cacheSoloPointer.y;
  14387. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14388. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14389. }
  14390. cacheSoloPointer.x = evt.clientX;
  14391. cacheSoloPointer.y = evt.clientY;
  14392. }
  14393. else if (pointA && pointB) {
  14394. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  14395. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  14396. ed.x = evt.clientX;
  14397. ed.y = evt.clientY;
  14398. var direction = _this.pinchInwards ? 1 : -1;
  14399. var distX = pointA.x - pointB.x;
  14400. var distY = pointA.y - pointB.y;
  14401. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  14402. if (previousPinchDistance === 0) {
  14403. previousPinchDistance = pinchSquaredDistance;
  14404. return;
  14405. }
  14406. if (pinchSquaredDistance !== previousPinchDistance) {
  14407. _this.camera
  14408. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  14409. (_this.pinchPrecision *
  14410. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  14411. direction);
  14412. previousPinchDistance = pinchSquaredDistance;
  14413. }
  14414. }
  14415. }
  14416. };
  14417. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14418. this._onContextMenu = function (evt) {
  14419. evt.preventDefault();
  14420. };
  14421. if (!this.camera._useCtrlForPanning) {
  14422. element.addEventListener("contextmenu", this._onContextMenu, false);
  14423. }
  14424. this._onLostFocus = function () {
  14425. //this._keys = [];
  14426. pointA = pointB = undefined;
  14427. previousPinchDistance = 0;
  14428. cacheSoloPointer = null;
  14429. };
  14430. this._onMouseMove = function (evt) {
  14431. if (!engine.isPointerLock) {
  14432. return;
  14433. }
  14434. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14435. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14436. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14437. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14438. if (!noPreventDefault) {
  14439. evt.preventDefault();
  14440. }
  14441. };
  14442. this._onGestureStart = function (e) {
  14443. if (window.MSGesture === undefined) {
  14444. return;
  14445. }
  14446. if (!_this._MSGestureHandler) {
  14447. _this._MSGestureHandler = new MSGesture();
  14448. _this._MSGestureHandler.target = element;
  14449. }
  14450. _this._MSGestureHandler.addPointer(e.pointerId);
  14451. };
  14452. this._onGesture = function (e) {
  14453. _this.camera.radius *= e.scale;
  14454. if (e.preventDefault) {
  14455. if (!noPreventDefault) {
  14456. e.stopPropagation();
  14457. e.preventDefault();
  14458. }
  14459. }
  14460. };
  14461. element.addEventListener("mousemove", this._onMouseMove, false);
  14462. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  14463. element.addEventListener("MSGestureChange", this._onGesture, false);
  14464. element.addEventListener("keydown", this._onKeyDown, false);
  14465. element.addEventListener("keyup", this._onKeyUp, false);
  14466. BABYLON.Tools.RegisterTopRootEvents([
  14467. { name: "blur", handler: this._onLostFocus }
  14468. ]);
  14469. };
  14470. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  14471. if (element && this._observer) {
  14472. this.camera.getScene().onPointerObservable.remove(this._observer);
  14473. this._observer = null;
  14474. element.removeEventListener("contextmenu", this._onContextMenu);
  14475. element.removeEventListener("mousemove", this._onMouseMove);
  14476. element.removeEventListener("MSPointerDown", this._onGestureStart);
  14477. element.removeEventListener("MSGestureChange", this._onGesture);
  14478. element.removeEventListener("keydown", this._onKeyDown);
  14479. element.removeEventListener("keyup", this._onKeyUp);
  14480. this._isPanClick = false;
  14481. this.pinchInwards = true;
  14482. this._onKeyDown = null;
  14483. this._onKeyUp = null;
  14484. this._onMouseMove = null;
  14485. this._onGestureStart = null;
  14486. this._onGesture = null;
  14487. this._MSGestureHandler = null;
  14488. this._onLostFocus = null;
  14489. this._onContextMenu = null;
  14490. }
  14491. BABYLON.Tools.UnregisterTopRootEvents([
  14492. { name: "blur", handler: this._onLostFocus }
  14493. ]);
  14494. };
  14495. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14496. return "ArcRotateCameraPointersInput";
  14497. };
  14498. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14499. return "pointers";
  14500. };
  14501. __decorate([
  14502. BABYLON.serialize()
  14503. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  14504. __decorate([
  14505. BABYLON.serialize()
  14506. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14507. __decorate([
  14508. BABYLON.serialize()
  14509. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14510. __decorate([
  14511. BABYLON.serialize()
  14512. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14513. __decorate([
  14514. BABYLON.serialize()
  14515. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14516. return ArcRotateCameraPointersInput;
  14517. }());
  14518. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14519. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14520. })(BABYLON || (BABYLON = {}));
  14521. //# sourceMappingURL=../../Cameras/Inputs/babylon.arcrotatecamera.input.pointers.js.map
  14522. var BABYLON;
  14523. (function (BABYLON) {
  14524. var ArcRotateCameraGamepadInput = (function () {
  14525. function ArcRotateCameraGamepadInput() {
  14526. this.gamepadRotationSensibility = 80;
  14527. this.gamepadMoveSensibility = 40;
  14528. }
  14529. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14530. var _this = this;
  14531. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14532. };
  14533. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14534. if (this._gamepads) {
  14535. this._gamepads.dispose();
  14536. }
  14537. this.gamepad = null;
  14538. };
  14539. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14540. if (this.gamepad) {
  14541. var camera = this.camera;
  14542. var RSValues = this.gamepad.rightStick;
  14543. if (RSValues.x != 0) {
  14544. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14545. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14546. camera.inertialAlphaOffset += normalizedRX;
  14547. }
  14548. }
  14549. if (RSValues.y != 0) {
  14550. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14551. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14552. camera.inertialBetaOffset += normalizedRY;
  14553. }
  14554. }
  14555. var LSValues = this.gamepad.leftStick;
  14556. if (LSValues.y != 0) {
  14557. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14558. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14559. this.camera.inertialRadiusOffset -= normalizedLY;
  14560. }
  14561. }
  14562. }
  14563. };
  14564. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14565. // Only the first gamepad can control the camera
  14566. if (gamepad.index === 0) {
  14567. this.gamepad = gamepad;
  14568. }
  14569. };
  14570. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  14571. return "ArcRotateCameraGamepadInput";
  14572. };
  14573. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  14574. return "gamepad";
  14575. };
  14576. __decorate([
  14577. BABYLON.serialize()
  14578. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  14579. __decorate([
  14580. BABYLON.serialize()
  14581. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14582. return ArcRotateCameraGamepadInput;
  14583. }());
  14584. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  14585. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  14586. })(BABYLON || (BABYLON = {}));
  14587. //# sourceMappingURL=../../Cameras/Inputs/babylon.arcrotatecamera.input.gamepad.js.map
  14588. var BABYLON;
  14589. (function (BABYLON) {
  14590. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  14591. function ArcRotateCameraVRDeviceOrientationInput() {
  14592. this.alphaCorrection = 1;
  14593. this.betaCorrection = 1;
  14594. this.gammaCorrection = 1;
  14595. this._alpha = 0;
  14596. this._beta = 0;
  14597. this._gamma = 0;
  14598. this._dirty = false;
  14599. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14600. }
  14601. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14602. this.camera.attachControl(element, noPreventDefault);
  14603. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  14604. };
  14605. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  14606. var camera = this.camera;
  14607. this._alpha = +evt.alpha | 0;
  14608. this._beta = +evt.beta | 0;
  14609. this._gamma = +evt.gamma | 0;
  14610. this._dirty = true;
  14611. };
  14612. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  14613. if (this._dirty) {
  14614. this._dirty = false;
  14615. if (this._gamma < 0) {
  14616. this._gamma = 180 + this._gamma;
  14617. }
  14618. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  14619. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  14620. }
  14621. };
  14622. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  14623. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  14624. };
  14625. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  14626. return "ArcRotateCameraVRDeviceOrientationInput";
  14627. };
  14628. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  14629. return "VRDeviceOrientation";
  14630. };
  14631. return ArcRotateCameraVRDeviceOrientationInput;
  14632. }());
  14633. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  14634. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  14635. })(BABYLON || (BABYLON = {}));
  14636. //# sourceMappingURL=../../Cameras/Inputs/babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  14637. var BABYLON;
  14638. (function (BABYLON) {
  14639. var TargetCamera = (function (_super) {
  14640. __extends(TargetCamera, _super);
  14641. function TargetCamera(name, position, scene) {
  14642. _super.call(this, name, position, scene);
  14643. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14644. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14645. this.rotation = new BABYLON.Vector3(0, 0, 0);
  14646. this.speed = 2.0;
  14647. this.noRotationConstraint = false;
  14648. this.lockedTarget = null;
  14649. this._currentTarget = BABYLON.Vector3.Zero();
  14650. this._viewMatrix = BABYLON.Matrix.Zero();
  14651. this._camMatrix = BABYLON.Matrix.Zero();
  14652. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  14653. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  14654. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  14655. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  14656. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  14657. this._lookAtTemp = BABYLON.Matrix.Zero();
  14658. this._tempMatrix = BABYLON.Matrix.Zero();
  14659. }
  14660. TargetCamera.prototype.getFrontPosition = function (distance) {
  14661. var direction = this.getTarget().subtract(this.position);
  14662. direction.normalize();
  14663. direction.scaleInPlace(distance);
  14664. return this.globalPosition.add(direction);
  14665. };
  14666. TargetCamera.prototype._getLockedTargetPosition = function () {
  14667. if (!this.lockedTarget) {
  14668. return null;
  14669. }
  14670. return this.lockedTarget.absolutePosition || this.lockedTarget;
  14671. };
  14672. // Cache
  14673. TargetCamera.prototype._initCache = function () {
  14674. _super.prototype._initCache.call(this);
  14675. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14676. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14677. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14678. };
  14679. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14680. if (!ignoreParentClass) {
  14681. _super.prototype._updateCache.call(this);
  14682. }
  14683. var lockedTargetPosition = this._getLockedTargetPosition();
  14684. if (!lockedTargetPosition) {
  14685. this._cache.lockedTarget = null;
  14686. }
  14687. else {
  14688. if (!this._cache.lockedTarget) {
  14689. this._cache.lockedTarget = lockedTargetPosition.clone();
  14690. }
  14691. else {
  14692. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14693. }
  14694. }
  14695. this._cache.rotation.copyFrom(this.rotation);
  14696. if (this.rotationQuaternion)
  14697. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14698. };
  14699. // Synchronized
  14700. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14701. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14702. return false;
  14703. }
  14704. var lockedTargetPosition = this._getLockedTargetPosition();
  14705. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14706. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14707. };
  14708. // Methods
  14709. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14710. var engine = this.getEngine();
  14711. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14712. };
  14713. // Target
  14714. TargetCamera.prototype.setTarget = function (target) {
  14715. this.upVector.normalize();
  14716. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14717. this._camMatrix.invert();
  14718. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14719. var vDir = target.subtract(this.position);
  14720. if (vDir.x >= 0.0) {
  14721. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14722. }
  14723. else {
  14724. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14725. }
  14726. this.rotation.z = 0;
  14727. if (isNaN(this.rotation.x)) {
  14728. this.rotation.x = 0;
  14729. }
  14730. if (isNaN(this.rotation.y)) {
  14731. this.rotation.y = 0;
  14732. }
  14733. if (isNaN(this.rotation.z)) {
  14734. this.rotation.z = 0;
  14735. }
  14736. if (this.rotationQuaternion) {
  14737. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14738. }
  14739. };
  14740. TargetCamera.prototype.getTarget = function () {
  14741. return this._currentTarget;
  14742. };
  14743. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14744. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14745. };
  14746. TargetCamera.prototype._updatePosition = function () {
  14747. this.position.addInPlace(this.cameraDirection);
  14748. };
  14749. TargetCamera.prototype._checkInputs = function () {
  14750. var needToMove = this._decideIfNeedsToMove();
  14751. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14752. // Move
  14753. if (needToMove) {
  14754. this._updatePosition();
  14755. }
  14756. // Rotate
  14757. if (needToRotate) {
  14758. this.rotation.x += this.cameraRotation.x;
  14759. this.rotation.y += this.cameraRotation.y;
  14760. if (!this.noRotationConstraint) {
  14761. var limit = (Math.PI / 2) * 0.95;
  14762. if (this.rotation.x > limit)
  14763. this.rotation.x = limit;
  14764. if (this.rotation.x < -limit)
  14765. this.rotation.x = -limit;
  14766. }
  14767. }
  14768. // Inertia
  14769. if (needToMove) {
  14770. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14771. this.cameraDirection.x = 0;
  14772. }
  14773. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14774. this.cameraDirection.y = 0;
  14775. }
  14776. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14777. this.cameraDirection.z = 0;
  14778. }
  14779. this.cameraDirection.scaleInPlace(this.inertia);
  14780. }
  14781. if (needToRotate) {
  14782. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14783. this.cameraRotation.x = 0;
  14784. }
  14785. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14786. this.cameraRotation.y = 0;
  14787. }
  14788. this.cameraRotation.scaleInPlace(this.inertia);
  14789. }
  14790. _super.prototype._checkInputs.call(this);
  14791. };
  14792. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14793. if (this.rotationQuaternion) {
  14794. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14795. //update the up vector!
  14796. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14797. }
  14798. else {
  14799. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14800. }
  14801. };
  14802. TargetCamera.prototype._getViewMatrix = function () {
  14803. if (!this.lockedTarget) {
  14804. // Compute
  14805. this._updateCameraRotationMatrix();
  14806. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14807. // Computing target and final matrix
  14808. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14809. }
  14810. else {
  14811. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14812. }
  14813. if (this.getScene().useRightHandedSystem) {
  14814. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14815. }
  14816. else {
  14817. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14818. }
  14819. return this._viewMatrix;
  14820. };
  14821. /**
  14822. * @override
  14823. * Override Camera.createRigCamera
  14824. */
  14825. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14826. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14827. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14828. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14829. if (!this.rotationQuaternion) {
  14830. this.rotationQuaternion = new BABYLON.Quaternion();
  14831. }
  14832. rigCamera._cameraRigParams = {};
  14833. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14834. }
  14835. return rigCamera;
  14836. }
  14837. return null;
  14838. };
  14839. /**
  14840. * @override
  14841. * Override Camera._updateRigCameras
  14842. */
  14843. TargetCamera.prototype._updateRigCameras = function () {
  14844. var camLeft = this._rigCameras[0];
  14845. var camRight = this._rigCameras[1];
  14846. switch (this.cameraRigMode) {
  14847. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14848. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14849. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14850. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14851. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  14852. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  14853. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  14854. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  14855. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  14856. camLeft.setTarget(this.getTarget());
  14857. camRight.setTarget(this.getTarget());
  14858. break;
  14859. case BABYLON.Camera.RIG_MODE_VR:
  14860. case BABYLON.Camera.RIG_MODE_WEBVR:
  14861. if (camLeft.rotationQuaternion) {
  14862. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14863. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14864. }
  14865. else {
  14866. camLeft.rotation.copyFrom(this.rotation);
  14867. camRight.rotation.copyFrom(this.rotation);
  14868. }
  14869. camLeft.position.copyFrom(this.position);
  14870. camRight.position.copyFrom(this.position);
  14871. break;
  14872. }
  14873. _super.prototype._updateRigCameras.call(this);
  14874. };
  14875. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  14876. if (!this._rigCamTransformMatrix) {
  14877. this._rigCamTransformMatrix = new BABYLON.Matrix();
  14878. }
  14879. var target = this.getTarget();
  14880. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  14881. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  14882. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  14883. };
  14884. TargetCamera.prototype.getTypeName = function () {
  14885. return "TargetCamera";
  14886. };
  14887. __decorate([
  14888. BABYLON.serializeAsVector3()
  14889. ], TargetCamera.prototype, "rotation", void 0);
  14890. __decorate([
  14891. BABYLON.serialize()
  14892. ], TargetCamera.prototype, "speed", void 0);
  14893. __decorate([
  14894. BABYLON.serializeAsMeshReference("lockedTargetId")
  14895. ], TargetCamera.prototype, "lockedTarget", void 0);
  14896. return TargetCamera;
  14897. }(BABYLON.Camera));
  14898. BABYLON.TargetCamera = TargetCamera;
  14899. })(BABYLON || (BABYLON = {}));
  14900. //# sourceMappingURL=../Cameras/babylon.targetCamera.js.map
  14901. var BABYLON;
  14902. (function (BABYLON) {
  14903. var FreeCamera = (function (_super) {
  14904. __extends(FreeCamera, _super);
  14905. function FreeCamera(name, position, scene) {
  14906. var _this = this;
  14907. _super.call(this, name, position, scene);
  14908. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14909. this.checkCollisions = false;
  14910. this.applyGravity = false;
  14911. this._collider = new BABYLON.Collider();
  14912. this._needMoveForGravity = false;
  14913. this._oldPosition = BABYLON.Vector3.Zero();
  14914. this._diffPosition = BABYLON.Vector3.Zero();
  14915. this._newPosition = BABYLON.Vector3.Zero();
  14916. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14917. if (collidedMesh === void 0) { collidedMesh = null; }
  14918. //TODO move this to the collision coordinator!
  14919. if (_this.getScene().workerCollisions)
  14920. newPosition.multiplyInPlace(_this._collider.radius);
  14921. var updatePosition = function (newPos) {
  14922. _this._newPosition.copyFrom(newPos);
  14923. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  14924. var oldPosition = _this.position.clone();
  14925. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  14926. _this.position.addInPlace(_this._diffPosition);
  14927. if (_this.onCollide && collidedMesh) {
  14928. _this.onCollide(collidedMesh);
  14929. }
  14930. }
  14931. };
  14932. updatePosition(newPosition);
  14933. };
  14934. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  14935. this.inputs.addKeyboard().addMouse();
  14936. }
  14937. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  14938. //-- begin properties for backward compatibility for inputs
  14939. get: function () {
  14940. var mouse = this.inputs.attached["mouse"];
  14941. if (mouse)
  14942. return mouse.angularSensibility;
  14943. },
  14944. set: function (value) {
  14945. var mouse = this.inputs.attached["mouse"];
  14946. if (mouse)
  14947. mouse.angularSensibility = value;
  14948. },
  14949. enumerable: true,
  14950. configurable: true
  14951. });
  14952. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  14953. get: function () {
  14954. var keyboard = this.inputs.attached["keyboard"];
  14955. if (keyboard)
  14956. return keyboard.keysUp;
  14957. },
  14958. set: function (value) {
  14959. var keyboard = this.inputs.attached["keyboard"];
  14960. if (keyboard)
  14961. keyboard.keysUp = value;
  14962. },
  14963. enumerable: true,
  14964. configurable: true
  14965. });
  14966. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  14967. get: function () {
  14968. var keyboard = this.inputs.attached["keyboard"];
  14969. if (keyboard)
  14970. return keyboard.keysDown;
  14971. },
  14972. set: function (value) {
  14973. var keyboard = this.inputs.attached["keyboard"];
  14974. if (keyboard)
  14975. keyboard.keysDown = value;
  14976. },
  14977. enumerable: true,
  14978. configurable: true
  14979. });
  14980. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  14981. get: function () {
  14982. var keyboard = this.inputs.attached["keyboard"];
  14983. if (keyboard)
  14984. return keyboard.keysLeft;
  14985. },
  14986. set: function (value) {
  14987. var keyboard = this.inputs.attached["keyboard"];
  14988. if (keyboard)
  14989. keyboard.keysLeft = value;
  14990. },
  14991. enumerable: true,
  14992. configurable: true
  14993. });
  14994. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  14995. get: function () {
  14996. var keyboard = this.inputs.attached["keyboard"];
  14997. if (keyboard)
  14998. return keyboard.keysRight;
  14999. },
  15000. set: function (value) {
  15001. var keyboard = this.inputs.attached["keyboard"];
  15002. if (keyboard)
  15003. keyboard.keysRight = value;
  15004. },
  15005. enumerable: true,
  15006. configurable: true
  15007. });
  15008. // Controls
  15009. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  15010. this.inputs.attachElement(element, noPreventDefault);
  15011. };
  15012. FreeCamera.prototype.detachControl = function (element) {
  15013. this.inputs.detachElement(element);
  15014. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  15015. this.cameraRotation = new BABYLON.Vector2(0, 0);
  15016. };
  15017. FreeCamera.prototype._collideWithWorld = function (velocity) {
  15018. var globalPosition;
  15019. if (this.parent) {
  15020. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  15021. }
  15022. else {
  15023. globalPosition = this.position;
  15024. }
  15025. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  15026. this._collider.radius = this.ellipsoid;
  15027. //no need for clone, as long as gravity is not on.
  15028. var actualVelocity = velocity;
  15029. //add gravity to the velocity to prevent the dual-collision checking
  15030. if (this.applyGravity) {
  15031. //this prevents mending with cameraDirection, a global variable of the free camera class.
  15032. actualVelocity = velocity.add(this.getScene().gravity);
  15033. }
  15034. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15035. };
  15036. FreeCamera.prototype._checkInputs = function () {
  15037. if (!this._localDirection) {
  15038. this._localDirection = BABYLON.Vector3.Zero();
  15039. this._transformedDirection = BABYLON.Vector3.Zero();
  15040. }
  15041. this.inputs.checkInputs();
  15042. _super.prototype._checkInputs.call(this);
  15043. };
  15044. FreeCamera.prototype._decideIfNeedsToMove = function () {
  15045. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  15046. };
  15047. FreeCamera.prototype._updatePosition = function () {
  15048. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  15049. this._collideWithWorld(this.cameraDirection);
  15050. }
  15051. else {
  15052. this.position.addInPlace(this.cameraDirection);
  15053. }
  15054. };
  15055. FreeCamera.prototype.dispose = function () {
  15056. this.inputs.clear();
  15057. _super.prototype.dispose.call(this);
  15058. };
  15059. FreeCamera.prototype.getTypeName = function () {
  15060. return "FreeCamera";
  15061. };
  15062. __decorate([
  15063. BABYLON.serializeAsVector3()
  15064. ], FreeCamera.prototype, "ellipsoid", void 0);
  15065. __decorate([
  15066. BABYLON.serialize()
  15067. ], FreeCamera.prototype, "checkCollisions", void 0);
  15068. __decorate([
  15069. BABYLON.serialize()
  15070. ], FreeCamera.prototype, "applyGravity", void 0);
  15071. return FreeCamera;
  15072. }(BABYLON.TargetCamera));
  15073. BABYLON.FreeCamera = FreeCamera;
  15074. })(BABYLON || (BABYLON = {}));
  15075. //# sourceMappingURL=../Cameras/babylon.freeCamera.js.map
  15076. var BABYLON;
  15077. (function (BABYLON) {
  15078. var FreeCameraInputsManager = (function (_super) {
  15079. __extends(FreeCameraInputsManager, _super);
  15080. function FreeCameraInputsManager(camera) {
  15081. _super.call(this, camera);
  15082. }
  15083. FreeCameraInputsManager.prototype.addKeyboard = function () {
  15084. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  15085. return this;
  15086. };
  15087. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  15088. if (touchEnabled === void 0) { touchEnabled = true; }
  15089. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  15090. return this;
  15091. };
  15092. FreeCameraInputsManager.prototype.addGamepad = function () {
  15093. this.add(new BABYLON.FreeCameraGamepadInput());
  15094. return this;
  15095. };
  15096. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  15097. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  15098. return this;
  15099. };
  15100. FreeCameraInputsManager.prototype.addTouch = function () {
  15101. this.add(new BABYLON.FreeCameraTouchInput());
  15102. return this;
  15103. };
  15104. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  15105. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  15106. return this;
  15107. };
  15108. return FreeCameraInputsManager;
  15109. }(BABYLON.CameraInputsManager));
  15110. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  15111. })(BABYLON || (BABYLON = {}));
  15112. //# sourceMappingURL=../Cameras/babylon.freeCameraInputsManager.js.map
  15113. var BABYLON;
  15114. (function (BABYLON) {
  15115. var FollowCamera = (function (_super) {
  15116. __extends(FollowCamera, _super);
  15117. function FollowCamera(name, position, scene, target) {
  15118. _super.call(this, name, position, scene);
  15119. this.radius = 12;
  15120. this.rotationOffset = 0;
  15121. this.heightOffset = 4;
  15122. this.cameraAcceleration = 0.05;
  15123. this.maxCameraSpeed = 20;
  15124. this.target = target;
  15125. }
  15126. FollowCamera.prototype.getRadians = function (degrees) {
  15127. return degrees * Math.PI / 180;
  15128. };
  15129. FollowCamera.prototype.follow = function (cameraTarget) {
  15130. if (!cameraTarget)
  15131. return;
  15132. var yRotation;
  15133. if (cameraTarget.rotationQuaternion) {
  15134. var rotMatrix = new BABYLON.Matrix();
  15135. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  15136. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  15137. }
  15138. else {
  15139. yRotation = cameraTarget.rotation.y;
  15140. }
  15141. var radians = this.getRadians(this.rotationOffset) + yRotation;
  15142. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  15143. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  15144. var dx = targetX - this.position.x;
  15145. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  15146. var dz = (targetZ) - this.position.z;
  15147. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  15148. var vy = dy * this.cameraAcceleration;
  15149. var vz = dz * this.cameraAcceleration * 2;
  15150. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  15151. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15152. }
  15153. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  15154. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15155. }
  15156. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  15157. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15158. }
  15159. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  15160. this.setTarget(cameraTarget.position);
  15161. };
  15162. FollowCamera.prototype._checkInputs = function () {
  15163. _super.prototype._checkInputs.call(this);
  15164. this.follow(this.target);
  15165. };
  15166. FollowCamera.prototype.getTypeName = function () {
  15167. return "FollowCamera";
  15168. };
  15169. __decorate([
  15170. BABYLON.serialize()
  15171. ], FollowCamera.prototype, "radius", void 0);
  15172. __decorate([
  15173. BABYLON.serialize()
  15174. ], FollowCamera.prototype, "rotationOffset", void 0);
  15175. __decorate([
  15176. BABYLON.serialize()
  15177. ], FollowCamera.prototype, "heightOffset", void 0);
  15178. __decorate([
  15179. BABYLON.serialize()
  15180. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  15181. __decorate([
  15182. BABYLON.serialize()
  15183. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  15184. __decorate([
  15185. BABYLON.serializeAsMeshReference("lockedTargetId")
  15186. ], FollowCamera.prototype, "target", void 0);
  15187. return FollowCamera;
  15188. }(BABYLON.TargetCamera));
  15189. BABYLON.FollowCamera = FollowCamera;
  15190. var ArcFollowCamera = (function (_super) {
  15191. __extends(ArcFollowCamera, _super);
  15192. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  15193. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  15194. this.alpha = alpha;
  15195. this.beta = beta;
  15196. this.radius = radius;
  15197. this.target = target;
  15198. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  15199. this.follow();
  15200. }
  15201. ArcFollowCamera.prototype.follow = function () {
  15202. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  15203. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  15204. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  15205. this.position = this.target.position.add(this._cartesianCoordinates);
  15206. this.setTarget(this.target.position);
  15207. };
  15208. ArcFollowCamera.prototype._checkInputs = function () {
  15209. _super.prototype._checkInputs.call(this);
  15210. this.follow();
  15211. };
  15212. ArcFollowCamera.prototype.getTypeName = function () {
  15213. return "ArcFollowCamera";
  15214. };
  15215. return ArcFollowCamera;
  15216. }(BABYLON.TargetCamera));
  15217. BABYLON.ArcFollowCamera = ArcFollowCamera;
  15218. })(BABYLON || (BABYLON = {}));
  15219. //# sourceMappingURL=../Cameras/babylon.followCamera.js.map
  15220. var BABYLON;
  15221. (function (BABYLON) {
  15222. // We're mainly based on the logic defined into the FreeCamera code
  15223. var TouchCamera = (function (_super) {
  15224. __extends(TouchCamera, _super);
  15225. //-- end properties for backward compatibility for inputs
  15226. function TouchCamera(name, position, scene) {
  15227. _super.call(this, name, position, scene);
  15228. this.inputs.addTouch();
  15229. this._setupInputs();
  15230. }
  15231. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  15232. //-- Begin properties for backward compatibility for inputs
  15233. get: function () {
  15234. var touch = this.inputs.attached["touch"];
  15235. if (touch)
  15236. return touch.touchAngularSensibility;
  15237. },
  15238. set: function (value) {
  15239. var touch = this.inputs.attached["touch"];
  15240. if (touch)
  15241. touch.touchAngularSensibility = value;
  15242. },
  15243. enumerable: true,
  15244. configurable: true
  15245. });
  15246. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  15247. get: function () {
  15248. var touch = this.inputs.attached["touch"];
  15249. if (touch)
  15250. return touch.touchMoveSensibility;
  15251. },
  15252. set: function (value) {
  15253. var touch = this.inputs.attached["touch"];
  15254. if (touch)
  15255. touch.touchMoveSensibility = value;
  15256. },
  15257. enumerable: true,
  15258. configurable: true
  15259. });
  15260. TouchCamera.prototype.getTypeName = function () {
  15261. return "TouchCamera";
  15262. };
  15263. TouchCamera.prototype._setupInputs = function () {
  15264. var mouse = this.inputs.attached["mouse"];
  15265. if (mouse) {
  15266. mouse.touchEnabled = false;
  15267. }
  15268. };
  15269. return TouchCamera;
  15270. }(BABYLON.FreeCamera));
  15271. BABYLON.TouchCamera = TouchCamera;
  15272. })(BABYLON || (BABYLON = {}));
  15273. //# sourceMappingURL=../Cameras/babylon.touchCamera.js.map
  15274. var BABYLON;
  15275. (function (BABYLON) {
  15276. var ArcRotateCamera = (function (_super) {
  15277. __extends(ArcRotateCamera, _super);
  15278. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  15279. var _this = this;
  15280. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  15281. this.inertialAlphaOffset = 0;
  15282. this.inertialBetaOffset = 0;
  15283. this.inertialRadiusOffset = 0;
  15284. this.lowerAlphaLimit = null;
  15285. this.upperAlphaLimit = null;
  15286. this.lowerBetaLimit = 0.01;
  15287. this.upperBetaLimit = Math.PI;
  15288. this.lowerRadiusLimit = null;
  15289. this.upperRadiusLimit = null;
  15290. this.inertialPanningX = 0;
  15291. this.inertialPanningY = 0;
  15292. //-- end properties for backward compatibility for inputs
  15293. this.zoomOnFactor = 1;
  15294. this.targetScreenOffset = BABYLON.Vector2.Zero();
  15295. this.allowUpsideDown = true;
  15296. this._viewMatrix = new BABYLON.Matrix();
  15297. // Panning
  15298. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  15299. this.checkCollisions = false;
  15300. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15301. this._collider = new BABYLON.Collider();
  15302. this._previousPosition = BABYLON.Vector3.Zero();
  15303. this._collisionVelocity = BABYLON.Vector3.Zero();
  15304. this._newPosition = BABYLON.Vector3.Zero();
  15305. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15306. if (collidedMesh === void 0) { collidedMesh = null; }
  15307. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  15308. newPosition.multiplyInPlace(_this._collider.radius);
  15309. }
  15310. if (!collidedMesh) {
  15311. _this._previousPosition.copyFrom(_this.position);
  15312. }
  15313. else {
  15314. _this.setPosition(newPosition);
  15315. if (_this.onCollide) {
  15316. _this.onCollide(collidedMesh);
  15317. }
  15318. }
  15319. // Recompute because of constraints
  15320. var cosa = Math.cos(_this.alpha);
  15321. var sina = Math.sin(_this.alpha);
  15322. var cosb = Math.cos(_this.beta);
  15323. var sinb = Math.sin(_this.beta);
  15324. if (sinb === 0) {
  15325. sinb = 0.0001;
  15326. }
  15327. var target = _this._getTargetPosition();
  15328. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  15329. _this.position.copyFrom(_this._newPosition);
  15330. var up = _this.upVector;
  15331. if (_this.allowUpsideDown && _this.beta < 0) {
  15332. up = up.clone();
  15333. up = up.negate();
  15334. }
  15335. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  15336. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  15337. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  15338. _this._collisionTriggered = false;
  15339. };
  15340. if (!target) {
  15341. this.target = BABYLON.Vector3.Zero();
  15342. }
  15343. else {
  15344. this.target = target;
  15345. }
  15346. this.alpha = alpha;
  15347. this.beta = beta;
  15348. this.radius = radius;
  15349. this.getViewMatrix();
  15350. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  15351. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  15352. }
  15353. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  15354. //-- begin properties for backward compatibility for inputs
  15355. get: function () {
  15356. var pointers = this.inputs.attached["pointers"];
  15357. if (pointers)
  15358. return pointers.angularSensibilityX;
  15359. },
  15360. set: function (value) {
  15361. var pointers = this.inputs.attached["pointers"];
  15362. if (pointers) {
  15363. pointers.angularSensibilityX = value;
  15364. }
  15365. },
  15366. enumerable: true,
  15367. configurable: true
  15368. });
  15369. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  15370. get: function () {
  15371. var pointers = this.inputs.attached["pointers"];
  15372. if (pointers)
  15373. return pointers.angularSensibilityY;
  15374. },
  15375. set: function (value) {
  15376. var pointers = this.inputs.attached["pointers"];
  15377. if (pointers) {
  15378. pointers.angularSensibilityY = value;
  15379. }
  15380. },
  15381. enumerable: true,
  15382. configurable: true
  15383. });
  15384. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  15385. get: function () {
  15386. var pointers = this.inputs.attached["pointers"];
  15387. if (pointers)
  15388. return pointers.pinchPrecision;
  15389. },
  15390. set: function (value) {
  15391. var pointers = this.inputs.attached["pointers"];
  15392. if (pointers) {
  15393. pointers.pinchPrecision = value;
  15394. }
  15395. },
  15396. enumerable: true,
  15397. configurable: true
  15398. });
  15399. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  15400. get: function () {
  15401. var pointers = this.inputs.attached["pointers"];
  15402. if (pointers)
  15403. return pointers.panningSensibility;
  15404. },
  15405. set: function (value) {
  15406. var pointers = this.inputs.attached["pointers"];
  15407. if (pointers) {
  15408. pointers.panningSensibility = value;
  15409. }
  15410. },
  15411. enumerable: true,
  15412. configurable: true
  15413. });
  15414. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  15415. get: function () {
  15416. var keyboard = this.inputs.attached["keyboard"];
  15417. if (keyboard)
  15418. return keyboard.keysUp;
  15419. },
  15420. set: function (value) {
  15421. var keyboard = this.inputs.attached["keyboard"];
  15422. if (keyboard)
  15423. keyboard.keysUp = value;
  15424. },
  15425. enumerable: true,
  15426. configurable: true
  15427. });
  15428. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  15429. get: function () {
  15430. var keyboard = this.inputs.attached["keyboard"];
  15431. if (keyboard)
  15432. return keyboard.keysDown;
  15433. },
  15434. set: function (value) {
  15435. var keyboard = this.inputs.attached["keyboard"];
  15436. if (keyboard)
  15437. keyboard.keysDown = value;
  15438. },
  15439. enumerable: true,
  15440. configurable: true
  15441. });
  15442. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  15443. get: function () {
  15444. var keyboard = this.inputs.attached["keyboard"];
  15445. if (keyboard)
  15446. return keyboard.keysLeft;
  15447. },
  15448. set: function (value) {
  15449. var keyboard = this.inputs.attached["keyboard"];
  15450. if (keyboard)
  15451. keyboard.keysLeft = value;
  15452. },
  15453. enumerable: true,
  15454. configurable: true
  15455. });
  15456. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  15457. get: function () {
  15458. var keyboard = this.inputs.attached["keyboard"];
  15459. if (keyboard)
  15460. return keyboard.keysRight;
  15461. },
  15462. set: function (value) {
  15463. var keyboard = this.inputs.attached["keyboard"];
  15464. if (keyboard)
  15465. keyboard.keysRight = value;
  15466. },
  15467. enumerable: true,
  15468. configurable: true
  15469. });
  15470. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  15471. get: function () {
  15472. var mousewheel = this.inputs.attached["mousewheel"];
  15473. if (mousewheel)
  15474. return mousewheel.wheelPrecision;
  15475. },
  15476. set: function (value) {
  15477. var mousewheel = this.inputs.attached["mousewheel"];
  15478. if (mousewheel)
  15479. mousewheel.wheelPrecision = value;
  15480. },
  15481. enumerable: true,
  15482. configurable: true
  15483. });
  15484. // Cache
  15485. ArcRotateCamera.prototype._initCache = function () {
  15486. _super.prototype._initCache.call(this);
  15487. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15488. this._cache.alpha = undefined;
  15489. this._cache.beta = undefined;
  15490. this._cache.radius = undefined;
  15491. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  15492. };
  15493. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  15494. if (!ignoreParentClass) {
  15495. _super.prototype._updateCache.call(this);
  15496. }
  15497. this._cache.target.copyFrom(this._getTargetPosition());
  15498. this._cache.alpha = this.alpha;
  15499. this._cache.beta = this.beta;
  15500. this._cache.radius = this.radius;
  15501. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15502. };
  15503. ArcRotateCamera.prototype._getTargetPosition = function () {
  15504. if (this.target.getAbsolutePosition) {
  15505. var pos = this.target.getAbsolutePosition();
  15506. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  15507. }
  15508. return this.target;
  15509. };
  15510. // Synchronized
  15511. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15512. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15513. return false;
  15514. return this._cache.target.equals(this.target)
  15515. && this._cache.alpha === this.alpha
  15516. && this._cache.beta === this.beta
  15517. && this._cache.radius === this.radius
  15518. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15519. };
  15520. // Methods
  15521. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15522. var _this = this;
  15523. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15524. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15525. this._useCtrlForPanning = useCtrlForPanning;
  15526. this._panningMouseButton = panningMouseButton;
  15527. this.inputs.attachElement(element, noPreventDefault);
  15528. this._reset = function () {
  15529. _this.inertialAlphaOffset = 0;
  15530. _this.inertialBetaOffset = 0;
  15531. _this.inertialRadiusOffset = 0;
  15532. };
  15533. };
  15534. ArcRotateCamera.prototype.detachControl = function (element) {
  15535. this.inputs.detachElement(element);
  15536. if (this._reset) {
  15537. this._reset();
  15538. }
  15539. };
  15540. ArcRotateCamera.prototype._checkInputs = function () {
  15541. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15542. if (this._collisionTriggered) {
  15543. return;
  15544. }
  15545. this.inputs.checkInputs();
  15546. // Inertia
  15547. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15548. this.beta += this.inertialBetaOffset;
  15549. if (this.getScene().useRightHandedSystem) {
  15550. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15551. }
  15552. else {
  15553. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15554. }
  15555. this.radius -= this.inertialRadiusOffset;
  15556. this.inertialAlphaOffset *= this.inertia;
  15557. this.inertialBetaOffset *= this.inertia;
  15558. this.inertialRadiusOffset *= this.inertia;
  15559. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  15560. this.inertialAlphaOffset = 0;
  15561. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  15562. this.inertialBetaOffset = 0;
  15563. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  15564. this.inertialRadiusOffset = 0;
  15565. }
  15566. // Panning inertia
  15567. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  15568. if (!this._localDirection) {
  15569. this._localDirection = BABYLON.Vector3.Zero();
  15570. this._transformedDirection = BABYLON.Vector3.Zero();
  15571. }
  15572. this.inertialPanningX *= this.inertia;
  15573. this.inertialPanningY *= this.inertia;
  15574. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  15575. this.inertialPanningX = 0;
  15576. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  15577. this.inertialPanningY = 0;
  15578. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  15579. this._localDirection.multiplyInPlace(this.panningAxis);
  15580. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  15581. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  15582. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  15583. if (!this.panningAxis.y) {
  15584. this._transformedDirection.y = 0;
  15585. }
  15586. if (!this.target.getAbsolutePosition) {
  15587. this.target.addInPlace(this._transformedDirection);
  15588. }
  15589. }
  15590. // Limits
  15591. this._checkLimits();
  15592. _super.prototype._checkInputs.call(this);
  15593. };
  15594. ArcRotateCamera.prototype._checkLimits = function () {
  15595. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  15596. if (this.allowUpsideDown && this.beta > Math.PI) {
  15597. this.beta = this.beta - (2 * Math.PI);
  15598. }
  15599. }
  15600. else {
  15601. if (this.beta < this.lowerBetaLimit) {
  15602. this.beta = this.lowerBetaLimit;
  15603. }
  15604. }
  15605. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  15606. if (this.allowUpsideDown && this.beta < -Math.PI) {
  15607. this.beta = this.beta + (2 * Math.PI);
  15608. }
  15609. }
  15610. else {
  15611. if (this.beta > this.upperBetaLimit) {
  15612. this.beta = this.upperBetaLimit;
  15613. }
  15614. }
  15615. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  15616. this.alpha = this.lowerAlphaLimit;
  15617. }
  15618. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  15619. this.alpha = this.upperAlphaLimit;
  15620. }
  15621. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  15622. this.radius = this.lowerRadiusLimit;
  15623. }
  15624. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  15625. this.radius = this.upperRadiusLimit;
  15626. }
  15627. };
  15628. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  15629. var radiusv3 = this.position.subtract(this._getTargetPosition());
  15630. this.radius = radiusv3.length();
  15631. // Alpha
  15632. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  15633. if (radiusv3.z < 0) {
  15634. this.alpha = 2 * Math.PI - this.alpha;
  15635. }
  15636. // Beta
  15637. this.beta = Math.acos(radiusv3.y / this.radius);
  15638. this._checkLimits();
  15639. };
  15640. ArcRotateCamera.prototype.setPosition = function (position) {
  15641. if (this.position.equals(position)) {
  15642. return;
  15643. }
  15644. this.position.copyFrom(position);
  15645. this.rebuildAnglesAndRadius();
  15646. };
  15647. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  15648. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  15649. if (this._getTargetPosition().equals(target)) {
  15650. return;
  15651. }
  15652. if (toBoundingCenter && target.getBoundingInfo) {
  15653. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  15654. }
  15655. else {
  15656. this._targetBoundingCenter = null;
  15657. }
  15658. this.target = target;
  15659. this.rebuildAnglesAndRadius();
  15660. };
  15661. ArcRotateCamera.prototype._getViewMatrix = function () {
  15662. // Compute
  15663. var cosa = Math.cos(this.alpha);
  15664. var sina = Math.sin(this.alpha);
  15665. var cosb = Math.cos(this.beta);
  15666. var sinb = Math.sin(this.beta);
  15667. if (sinb === 0) {
  15668. sinb = 0.0001;
  15669. }
  15670. var target = this._getTargetPosition();
  15671. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  15672. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  15673. this._collider.radius = this.collisionRadius;
  15674. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  15675. this._collisionTriggered = true;
  15676. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15677. }
  15678. else {
  15679. this.position.copyFrom(this._newPosition);
  15680. var up = this.upVector;
  15681. if (this.allowUpsideDown && this.beta < 0) {
  15682. up = up.clone();
  15683. up = up.negate();
  15684. }
  15685. if (this.getScene().useRightHandedSystem) {
  15686. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  15687. }
  15688. else {
  15689. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  15690. }
  15691. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  15692. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  15693. }
  15694. this._currentTarget = target;
  15695. return this._viewMatrix;
  15696. };
  15697. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  15698. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15699. meshes = meshes || this.getScene().meshes;
  15700. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  15701. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  15702. this.radius = distance * this.zoomOnFactor;
  15703. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15704. };
  15705. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15706. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15707. var meshesOrMinMaxVector;
  15708. var distance;
  15709. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15710. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15711. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15712. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15713. }
  15714. else {
  15715. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15716. distance = meshesOrMinMaxVectorAndDistance.distance;
  15717. }
  15718. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15719. if (!doNotUpdateMaxZ) {
  15720. this.maxZ = distance * 2;
  15721. }
  15722. };
  15723. /**
  15724. * @override
  15725. * Override Camera.createRigCamera
  15726. */
  15727. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15728. var alphaShift;
  15729. switch (this.cameraRigMode) {
  15730. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15731. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15732. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15733. case BABYLON.Camera.RIG_MODE_VR:
  15734. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15735. break;
  15736. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15737. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15738. break;
  15739. }
  15740. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15741. rigCam._cameraRigParams = {};
  15742. return rigCam;
  15743. };
  15744. /**
  15745. * @override
  15746. * Override Camera._updateRigCameras
  15747. */
  15748. ArcRotateCamera.prototype._updateRigCameras = function () {
  15749. var camLeft = this._rigCameras[0];
  15750. var camRight = this._rigCameras[1];
  15751. camLeft.beta = camRight.beta = this.beta;
  15752. camLeft.radius = camRight.radius = this.radius;
  15753. switch (this.cameraRigMode) {
  15754. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15755. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15756. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15757. case BABYLON.Camera.RIG_MODE_VR:
  15758. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15759. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15760. break;
  15761. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15762. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15763. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15764. break;
  15765. }
  15766. _super.prototype._updateRigCameras.call(this);
  15767. };
  15768. ArcRotateCamera.prototype.dispose = function () {
  15769. this.inputs.clear();
  15770. _super.prototype.dispose.call(this);
  15771. };
  15772. ArcRotateCamera.prototype.getTypeName = function () {
  15773. return "ArcRotateCamera";
  15774. };
  15775. __decorate([
  15776. BABYLON.serialize()
  15777. ], ArcRotateCamera.prototype, "alpha", void 0);
  15778. __decorate([
  15779. BABYLON.serialize()
  15780. ], ArcRotateCamera.prototype, "beta", void 0);
  15781. __decorate([
  15782. BABYLON.serialize()
  15783. ], ArcRotateCamera.prototype, "radius", void 0);
  15784. __decorate([
  15785. BABYLON.serializeAsVector3()
  15786. ], ArcRotateCamera.prototype, "target", void 0);
  15787. __decorate([
  15788. BABYLON.serialize()
  15789. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15790. __decorate([
  15791. BABYLON.serialize()
  15792. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15793. __decorate([
  15794. BABYLON.serialize()
  15795. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15796. __decorate([
  15797. BABYLON.serialize()
  15798. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15799. __decorate([
  15800. BABYLON.serialize()
  15801. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15802. __decorate([
  15803. BABYLON.serialize()
  15804. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15805. __decorate([
  15806. BABYLON.serialize()
  15807. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15808. __decorate([
  15809. BABYLON.serialize()
  15810. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15811. __decorate([
  15812. BABYLON.serialize()
  15813. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15814. __decorate([
  15815. BABYLON.serialize()
  15816. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15817. __decorate([
  15818. BABYLON.serialize()
  15819. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15820. __decorate([
  15821. BABYLON.serialize()
  15822. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15823. __decorate([
  15824. BABYLON.serialize()
  15825. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  15826. return ArcRotateCamera;
  15827. }(BABYLON.TargetCamera));
  15828. BABYLON.ArcRotateCamera = ArcRotateCamera;
  15829. })(BABYLON || (BABYLON = {}));
  15830. //# sourceMappingURL=../Cameras/babylon.arcRotateCamera.js.map
  15831. var BABYLON;
  15832. (function (BABYLON) {
  15833. var ArcRotateCameraInputsManager = (function (_super) {
  15834. __extends(ArcRotateCameraInputsManager, _super);
  15835. function ArcRotateCameraInputsManager(camera) {
  15836. _super.call(this, camera);
  15837. }
  15838. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  15839. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  15840. return this;
  15841. };
  15842. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  15843. this.add(new BABYLON.ArcRotateCameraPointersInput());
  15844. return this;
  15845. };
  15846. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  15847. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  15848. return this;
  15849. };
  15850. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  15851. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  15852. return this;
  15853. };
  15854. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  15855. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  15856. return this;
  15857. };
  15858. return ArcRotateCameraInputsManager;
  15859. }(BABYLON.CameraInputsManager));
  15860. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  15861. })(BABYLON || (BABYLON = {}));
  15862. //# sourceMappingURL=../Cameras/babylon.arcRotateCameraInputsManager.js.map
  15863. var BABYLON;
  15864. (function (BABYLON) {
  15865. var RenderingManager = (function () {
  15866. function RenderingManager(scene) {
  15867. this._renderingGroups = new Array();
  15868. this._autoClearDepthStencil = {};
  15869. this._customOpaqueSortCompareFn = {};
  15870. this._customAlphaTestSortCompareFn = {};
  15871. this._customTransparentSortCompareFn = {};
  15872. this._renderinGroupInfo = null;
  15873. this._scene = scene;
  15874. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15875. this._autoClearDepthStencil[i] = true;
  15876. }
  15877. }
  15878. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  15879. if (this._scene._activeParticleSystems.length === 0) {
  15880. return;
  15881. }
  15882. // Particles
  15883. var activeCamera = this._scene.activeCamera;
  15884. this._scene._particlesDuration.beginMonitoring();
  15885. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15886. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15887. if (particleSystem.renderingGroupId !== index) {
  15888. continue;
  15889. }
  15890. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15891. continue;
  15892. }
  15893. this._clearDepthStencilBuffer();
  15894. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15895. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15896. }
  15897. }
  15898. this._scene._particlesDuration.endMonitoring(false);
  15899. };
  15900. RenderingManager.prototype._renderSprites = function (index) {
  15901. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  15902. return;
  15903. }
  15904. // Sprites
  15905. var activeCamera = this._scene.activeCamera;
  15906. this._scene._spritesDuration.beginMonitoring();
  15907. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  15908. var spriteManager = this._scene.spriteManagers[id];
  15909. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15910. this._clearDepthStencilBuffer();
  15911. spriteManager.render();
  15912. }
  15913. }
  15914. this._scene._spritesDuration.endMonitoring(false);
  15915. };
  15916. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  15917. if (this._depthStencilBufferAlreadyCleaned) {
  15918. return;
  15919. }
  15920. this._scene.getEngine().clear(0, false, true, true);
  15921. this._depthStencilBufferAlreadyCleaned = true;
  15922. };
  15923. RenderingManager.prototype._renderSpritesAndParticles = function () {
  15924. if (this._currentRenderSprites) {
  15925. this._renderSprites(this._currentIndex);
  15926. }
  15927. if (this._currentRenderParticles) {
  15928. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  15929. }
  15930. };
  15931. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15932. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15933. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15934. var info = null;
  15935. if (observable) {
  15936. if (!this._renderinGroupInfo) {
  15937. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15938. }
  15939. info = this._renderinGroupInfo;
  15940. info.scene = this._scene;
  15941. info.camera = this._scene.activeCamera;
  15942. }
  15943. this._currentActiveMeshes = activeMeshes;
  15944. this._currentRenderParticles = renderParticles;
  15945. this._currentRenderSprites = renderSprites;
  15946. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15947. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15948. var renderingGroup = this._renderingGroups[index];
  15949. var needToStepBack = false;
  15950. this._currentIndex = index;
  15951. if (renderingGroup) {
  15952. var renderingGroupMask = 0;
  15953. // Fire PRECLEAR stage
  15954. if (observable) {
  15955. renderingGroupMask = Math.pow(2, index);
  15956. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15957. info.renderingGroupId = index;
  15958. observable.notifyObservers(info, renderingGroupMask);
  15959. }
  15960. // Clear depth/stencil if needed
  15961. if (this._autoClearDepthStencil[index]) {
  15962. this._clearDepthStencilBuffer();
  15963. }
  15964. // Fire PREOPAQUE stage
  15965. if (observable) {
  15966. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15967. observable.notifyObservers(info, renderingGroupMask);
  15968. }
  15969. if (!renderingGroup.onBeforeTransparentRendering) {
  15970. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  15971. }
  15972. // Fire PRETRANSPARENT stage
  15973. if (observable) {
  15974. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15975. observable.notifyObservers(info, renderingGroupMask);
  15976. }
  15977. if (!renderingGroup.render(customRenderFunction)) {
  15978. this._renderingGroups.splice(index, 1);
  15979. needToStepBack = true;
  15980. this._renderSpritesAndParticles();
  15981. }
  15982. // Fire POSTTRANSPARENT stage
  15983. if (observable) {
  15984. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15985. observable.notifyObservers(info, renderingGroupMask);
  15986. }
  15987. }
  15988. else {
  15989. this._renderSpritesAndParticles();
  15990. if (observable) {
  15991. var renderingGroupMask = Math.pow(2, index);
  15992. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15993. info.renderingGroupId = index;
  15994. observable.notifyObservers(info, renderingGroupMask);
  15995. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15996. observable.notifyObservers(info, renderingGroupMask);
  15997. }
  15998. }
  15999. if (needToStepBack) {
  16000. index--;
  16001. }
  16002. }
  16003. };
  16004. RenderingManager.prototype.reset = function () {
  16005. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16006. var renderingGroup = this._renderingGroups[index];
  16007. if (renderingGroup) {
  16008. renderingGroup.prepare();
  16009. }
  16010. }
  16011. };
  16012. RenderingManager.prototype.dispatch = function (subMesh) {
  16013. var mesh = subMesh.getMesh();
  16014. var renderingGroupId = mesh.renderingGroupId || 0;
  16015. if (!this._renderingGroups[renderingGroupId]) {
  16016. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16017. }
  16018. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16019. };
  16020. /**
  16021. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16022. * This allowed control for front to back rendering or reversly depending of the special needs.
  16023. *
  16024. * @param renderingGroupId The rendering group id corresponding to its index
  16025. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16026. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16027. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16028. */
  16029. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16030. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16031. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16032. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16033. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16034. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16035. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16036. if (this._renderingGroups[renderingGroupId]) {
  16037. var group = this._renderingGroups[renderingGroupId];
  16038. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16039. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16040. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16041. }
  16042. };
  16043. /**
  16044. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16045. *
  16046. * @param renderingGroupId The rendering group id corresponding to its index
  16047. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16048. */
  16049. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  16050. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  16051. };
  16052. /**
  16053. * The max id used for rendering groups (not included)
  16054. */
  16055. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16056. /**
  16057. * The min id used for rendering groups (included)
  16058. */
  16059. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16060. return RenderingManager;
  16061. }());
  16062. BABYLON.RenderingManager = RenderingManager;
  16063. })(BABYLON || (BABYLON = {}));
  16064. //# sourceMappingURL=../Rendering/babylon.renderingManager.js.map
  16065. var BABYLON;
  16066. (function (BABYLON) {
  16067. var RenderingGroup = (function () {
  16068. /**
  16069. * Creates a new rendering group.
  16070. * @param index The rendering group index
  16071. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16072. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16073. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16074. */
  16075. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16076. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16077. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16078. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16079. this.index = index;
  16080. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16081. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16082. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16083. this._scene = scene;
  16084. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16085. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16086. this.transparentSortCompareFn = transparentSortCompareFn;
  16087. }
  16088. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16089. /**
  16090. * Set the opaque sort comparison function.
  16091. * If null the sub meshes will be render in the order they were created
  16092. */
  16093. set: function (value) {
  16094. this._opaqueSortCompareFn = value;
  16095. if (value) {
  16096. this._renderOpaque = this.renderOpaqueSorted;
  16097. }
  16098. else {
  16099. this._renderOpaque = RenderingGroup.renderUnsorted;
  16100. }
  16101. },
  16102. enumerable: true,
  16103. configurable: true
  16104. });
  16105. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16106. /**
  16107. * Set the alpha test sort comparison function.
  16108. * If null the sub meshes will be render in the order they were created
  16109. */
  16110. set: function (value) {
  16111. this._alphaTestSortCompareFn = value;
  16112. if (value) {
  16113. this._renderAlphaTest = this.renderAlphaTestSorted;
  16114. }
  16115. else {
  16116. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16117. }
  16118. },
  16119. enumerable: true,
  16120. configurable: true
  16121. });
  16122. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16123. /**
  16124. * Set the transparent sort comparison function.
  16125. * If null the sub meshes will be render in the order they were created
  16126. */
  16127. set: function (value) {
  16128. if (value) {
  16129. this._transparentSortCompareFn = value;
  16130. }
  16131. else {
  16132. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16133. }
  16134. this._renderTransparent = this.renderTransparentSorted;
  16135. },
  16136. enumerable: true,
  16137. configurable: true
  16138. });
  16139. /**
  16140. * Render all the sub meshes contained in the group.
  16141. * @param customRenderFunction Used to override the default render behaviour of the group.
  16142. * @returns true if rendered some submeshes.
  16143. */
  16144. RenderingGroup.prototype.render = function (customRenderFunction) {
  16145. if (customRenderFunction) {
  16146. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  16147. return true;
  16148. }
  16149. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  16150. if (this.onBeforeTransparentRendering) {
  16151. this.onBeforeTransparentRendering();
  16152. }
  16153. return false;
  16154. }
  16155. var engine = this._scene.getEngine();
  16156. // Opaque
  16157. this._renderOpaque(this._opaqueSubMeshes);
  16158. // Alpha test
  16159. engine.setAlphaTesting(true);
  16160. this._renderAlphaTest(this._alphaTestSubMeshes);
  16161. engine.setAlphaTesting(false);
  16162. if (this.onBeforeTransparentRendering) {
  16163. this.onBeforeTransparentRendering();
  16164. }
  16165. // Transparent
  16166. this._renderTransparent(this._transparentSubMeshes);
  16167. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16168. return true;
  16169. };
  16170. /**
  16171. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16172. * @param subMeshes The submeshes to render
  16173. */
  16174. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16175. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16176. };
  16177. /**
  16178. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16179. * @param subMeshes The submeshes to render
  16180. */
  16181. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16182. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16183. };
  16184. /**
  16185. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16186. * @param subMeshes The submeshes to render
  16187. */
  16188. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16189. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16190. };
  16191. /**
  16192. * Renders the submeshes in a specified order.
  16193. * @param subMeshes The submeshes to sort before render
  16194. * @param sortCompareFn The comparison function use to sort
  16195. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16196. * @param transparent Specifies to activate blending if true
  16197. */
  16198. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16199. var subIndex = 0;
  16200. var subMesh;
  16201. for (; subIndex < subMeshes.length; subIndex++) {
  16202. subMesh = subMeshes.data[subIndex];
  16203. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16204. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16205. }
  16206. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16207. sortedArray.sort(sortCompareFn);
  16208. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16209. subMesh = sortedArray[subIndex];
  16210. subMesh.render(transparent);
  16211. }
  16212. };
  16213. /**
  16214. * Renders the submeshes in the order they were dispatched (no sort applied).
  16215. * @param subMeshes The submeshes to render
  16216. */
  16217. RenderingGroup.renderUnsorted = function (subMeshes) {
  16218. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16219. var submesh = subMeshes.data[subIndex];
  16220. submesh.render(false);
  16221. }
  16222. };
  16223. /**
  16224. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16225. * are rendered back to front if in the same alpha index.
  16226. *
  16227. * @param a The first submesh
  16228. * @param b The second submesh
  16229. * @returns The result of the comparison
  16230. */
  16231. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16232. // Alpha index first
  16233. if (a._alphaIndex > b._alphaIndex) {
  16234. return 1;
  16235. }
  16236. if (a._alphaIndex < b._alphaIndex) {
  16237. return -1;
  16238. }
  16239. // Then distance to camera
  16240. return RenderingGroup.backToFrontSortCompare(a, b);
  16241. };
  16242. /**
  16243. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16244. * are rendered back to front.
  16245. *
  16246. * @param a The first submesh
  16247. * @param b The second submesh
  16248. * @returns The result of the comparison
  16249. */
  16250. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16251. // Then distance to camera
  16252. if (a._distanceToCamera < b._distanceToCamera) {
  16253. return 1;
  16254. }
  16255. if (a._distanceToCamera > b._distanceToCamera) {
  16256. return -1;
  16257. }
  16258. return 0;
  16259. };
  16260. /**
  16261. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16262. * are rendered front to back (prevent overdraw).
  16263. *
  16264. * @param a The first submesh
  16265. * @param b The second submesh
  16266. * @returns The result of the comparison
  16267. */
  16268. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16269. // Then distance to camera
  16270. if (a._distanceToCamera < b._distanceToCamera) {
  16271. return -1;
  16272. }
  16273. if (a._distanceToCamera > b._distanceToCamera) {
  16274. return 1;
  16275. }
  16276. return 0;
  16277. };
  16278. /**
  16279. * Resets the different lists of submeshes to prepare a new frame.
  16280. */
  16281. RenderingGroup.prototype.prepare = function () {
  16282. this._opaqueSubMeshes.reset();
  16283. this._transparentSubMeshes.reset();
  16284. this._alphaTestSubMeshes.reset();
  16285. };
  16286. /**
  16287. * Inserts the submesh in its correct queue depending on its material.
  16288. * @param subMesh The submesh to dispatch
  16289. */
  16290. RenderingGroup.prototype.dispatch = function (subMesh) {
  16291. var material = subMesh.getMaterial();
  16292. var mesh = subMesh.getMesh();
  16293. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16294. this._transparentSubMeshes.push(subMesh);
  16295. }
  16296. else if (material.needAlphaTesting()) {
  16297. this._alphaTestSubMeshes.push(subMesh);
  16298. }
  16299. else {
  16300. this._opaqueSubMeshes.push(subMesh); // Opaque
  16301. }
  16302. };
  16303. return RenderingGroup;
  16304. }());
  16305. BABYLON.RenderingGroup = RenderingGroup;
  16306. })(BABYLON || (BABYLON = {}));
  16307. //# sourceMappingURL=../Rendering/babylon.renderingGroup.js.map
  16308. var BABYLON;
  16309. (function (BABYLON) {
  16310. var PointerEventTypes = (function () {
  16311. function PointerEventTypes() {
  16312. }
  16313. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16314. get: function () {
  16315. return PointerEventTypes._POINTERDOWN;
  16316. },
  16317. enumerable: true,
  16318. configurable: true
  16319. });
  16320. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16321. get: function () {
  16322. return PointerEventTypes._POINTERUP;
  16323. },
  16324. enumerable: true,
  16325. configurable: true
  16326. });
  16327. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16328. get: function () {
  16329. return PointerEventTypes._POINTERMOVE;
  16330. },
  16331. enumerable: true,
  16332. configurable: true
  16333. });
  16334. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16335. get: function () {
  16336. return PointerEventTypes._POINTERWHEEL;
  16337. },
  16338. enumerable: true,
  16339. configurable: true
  16340. });
  16341. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16342. get: function () {
  16343. return PointerEventTypes._POINTERPICK;
  16344. },
  16345. enumerable: true,
  16346. configurable: true
  16347. });
  16348. PointerEventTypes._POINTERDOWN = 0x01;
  16349. PointerEventTypes._POINTERUP = 0x02;
  16350. PointerEventTypes._POINTERMOVE = 0x04;
  16351. PointerEventTypes._POINTERWHEEL = 0x08;
  16352. PointerEventTypes._POINTERPICK = 0x10;
  16353. return PointerEventTypes;
  16354. }());
  16355. BABYLON.PointerEventTypes = PointerEventTypes;
  16356. var PointerInfoBase = (function () {
  16357. function PointerInfoBase(type, event) {
  16358. this.type = type;
  16359. this.event = event;
  16360. }
  16361. return PointerInfoBase;
  16362. }());
  16363. BABYLON.PointerInfoBase = PointerInfoBase;
  16364. /**
  16365. * This class is used to store pointer related info for the onPrePointerObservable event.
  16366. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16367. */
  16368. var PointerInfoPre = (function (_super) {
  16369. __extends(PointerInfoPre, _super);
  16370. function PointerInfoPre(type, event, localX, localY) {
  16371. _super.call(this, type, event);
  16372. this.skipOnPointerObservable = false;
  16373. this.localPosition = new BABYLON.Vector2(localX, localY);
  16374. }
  16375. return PointerInfoPre;
  16376. }(PointerInfoBase));
  16377. BABYLON.PointerInfoPre = PointerInfoPre;
  16378. /**
  16379. * This type contains all the data related to a pointer event in Babylon.js.
  16380. * 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.
  16381. */
  16382. var PointerInfo = (function (_super) {
  16383. __extends(PointerInfo, _super);
  16384. function PointerInfo(type, event, pickInfo) {
  16385. _super.call(this, type, event);
  16386. this.pickInfo = pickInfo;
  16387. }
  16388. return PointerInfo;
  16389. }(PointerInfoBase));
  16390. BABYLON.PointerInfo = PointerInfo;
  16391. /**
  16392. * This class is used by the onRenderingGroupObservable
  16393. */
  16394. var RenderingGroupInfo = (function () {
  16395. function RenderingGroupInfo() {
  16396. }
  16397. /**
  16398. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16399. * This stage will be fired no matter what
  16400. */
  16401. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16402. /**
  16403. * Called before opaque object are rendered.
  16404. * This stage will be fired only if there's 3D Opaque content to render
  16405. */
  16406. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16407. /**
  16408. * Called after the opaque objects are rendered and before the transparent ones
  16409. * This stage will be fired only if there's 3D transparent content to render
  16410. */
  16411. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16412. /**
  16413. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16414. * This stage will be fired no matter what
  16415. */
  16416. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16417. return RenderingGroupInfo;
  16418. }());
  16419. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16420. /**
  16421. * Represents a scene to be rendered by the engine.
  16422. * @see http://doc.babylonjs.com/page.php?p=21911
  16423. */
  16424. var Scene = (function () {
  16425. /**
  16426. * @constructor
  16427. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16428. */
  16429. function Scene(engine) {
  16430. // Members
  16431. this.autoClear = true;
  16432. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16433. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16434. this.forceWireframe = false;
  16435. this.forcePointsCloud = false;
  16436. this.forceShowBoundingBoxes = false;
  16437. this.animationsEnabled = true;
  16438. this.constantlyUpdateMeshUnderPointer = false;
  16439. this.useRightHandedSystem = false;
  16440. this.hoverCursor = "pointer";
  16441. // Metadata
  16442. this.metadata = null;
  16443. // Events
  16444. /**
  16445. * An event triggered when the scene is disposed.
  16446. * @type {BABYLON.Observable}
  16447. */
  16448. this.onDisposeObservable = new BABYLON.Observable();
  16449. /**
  16450. * An event triggered before rendering the scene
  16451. * @type {BABYLON.Observable}
  16452. */
  16453. this.onBeforeRenderObservable = new BABYLON.Observable();
  16454. /**
  16455. * An event triggered after rendering the scene
  16456. * @type {BABYLON.Observable}
  16457. */
  16458. this.onAfterRenderObservable = new BABYLON.Observable();
  16459. /**
  16460. * An event triggered when the scene is ready
  16461. * @type {BABYLON.Observable}
  16462. */
  16463. this.onReadyObservable = new BABYLON.Observable();
  16464. /**
  16465. * An event triggered before rendering a camera
  16466. * @type {BABYLON.Observable}
  16467. */
  16468. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16469. /**
  16470. * An event triggered after rendering a camera
  16471. * @type {BABYLON.Observable}
  16472. */
  16473. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16474. /**
  16475. * An event triggered when a camera is created
  16476. * @type {BABYLON.Observable}
  16477. */
  16478. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16479. /**
  16480. * An event triggered when a camera is removed
  16481. * @type {BABYLON.Observable}
  16482. */
  16483. this.onCameraRemovedObservable = new BABYLON.Observable();
  16484. /**
  16485. * An event triggered when a light is created
  16486. * @type {BABYLON.Observable}
  16487. */
  16488. this.onNewLightAddedObservable = new BABYLON.Observable();
  16489. /**
  16490. * An event triggered when a light is removed
  16491. * @type {BABYLON.Observable}
  16492. */
  16493. this.onLightRemovedObservable = new BABYLON.Observable();
  16494. /**
  16495. * An event triggered when a geometry is created
  16496. * @type {BABYLON.Observable}
  16497. */
  16498. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16499. /**
  16500. * An event triggered when a geometry is removed
  16501. * @type {BABYLON.Observable}
  16502. */
  16503. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16504. /**
  16505. * An event triggered when a mesh is created
  16506. * @type {BABYLON.Observable}
  16507. */
  16508. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16509. /**
  16510. * An event triggered when a mesh is removed
  16511. * @type {BABYLON.Observable}
  16512. */
  16513. this.onMeshRemovedObservable = new BABYLON.Observable();
  16514. /**
  16515. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16516. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16517. * 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)
  16518. */
  16519. this.onRenderingGroupObservable = new BABYLON.Observable();
  16520. // Animations
  16521. this.animations = [];
  16522. /**
  16523. * 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).
  16524. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16525. */
  16526. this.onPrePointerObservable = new BABYLON.Observable();
  16527. /**
  16528. * Observable event triggered each time an input event is received from the rendering canvas
  16529. */
  16530. this.onPointerObservable = new BABYLON.Observable();
  16531. 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
  16532. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16533. this._startingPointerTime = 0;
  16534. // Fog
  16535. /**
  16536. * is fog enabled on this scene.
  16537. * @type {boolean}
  16538. */
  16539. this.fogEnabled = true;
  16540. this.fogMode = Scene.FOGMODE_NONE;
  16541. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16542. this.fogDensity = 0.1;
  16543. this.fogStart = 0;
  16544. this.fogEnd = 1000.0;
  16545. // Lights
  16546. /**
  16547. * is shadow enabled on this scene.
  16548. * @type {boolean}
  16549. */
  16550. this.shadowsEnabled = true;
  16551. /**
  16552. * is light enabled on this scene.
  16553. * @type {boolean}
  16554. */
  16555. this.lightsEnabled = true;
  16556. /**
  16557. * All of the lights added to this scene.
  16558. * @see BABYLON.Light
  16559. * @type {BABYLON.Light[]}
  16560. */
  16561. this.lights = new Array();
  16562. // Cameras
  16563. /**
  16564. * All of the cameras added to this scene.
  16565. * @see BABYLON.Camera
  16566. * @type {BABYLON.Camera[]}
  16567. */
  16568. this.cameras = new Array();
  16569. this.activeCameras = new Array();
  16570. // Meshes
  16571. /**
  16572. * All of the (abstract) meshes added to this scene.
  16573. * @see BABYLON.AbstractMesh
  16574. * @type {BABYLON.AbstractMesh[]}
  16575. */
  16576. this.meshes = new Array();
  16577. // Geometries
  16578. this._geometries = new Array();
  16579. this.materials = new Array();
  16580. this.multiMaterials = new Array();
  16581. // Textures
  16582. this.texturesEnabled = true;
  16583. this.textures = new Array();
  16584. // Particles
  16585. this.particlesEnabled = true;
  16586. this.particleSystems = new Array();
  16587. // Sprites
  16588. this.spritesEnabled = true;
  16589. this.spriteManagers = new Array();
  16590. // Layers
  16591. this.layers = new Array();
  16592. this.highlightLayers = new Array();
  16593. // Skeletons
  16594. this.skeletonsEnabled = true;
  16595. this.skeletons = new Array();
  16596. // Lens flares
  16597. this.lensFlaresEnabled = true;
  16598. this.lensFlareSystems = new Array();
  16599. // Collisions
  16600. this.collisionsEnabled = true;
  16601. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16602. // Postprocesses
  16603. this.postProcessesEnabled = true;
  16604. // Customs render targets
  16605. this.renderTargetsEnabled = true;
  16606. this.dumpNextRenderTargets = false;
  16607. this.customRenderTargets = new Array();
  16608. // Imported meshes
  16609. this.importedMeshesFiles = new Array();
  16610. // Probes
  16611. this.probesEnabled = true;
  16612. this.reflectionProbes = new Array();
  16613. this._actionManagers = new Array();
  16614. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16615. // Procedural textures
  16616. this.proceduralTexturesEnabled = true;
  16617. this._proceduralTextures = new Array();
  16618. this.soundTracks = new Array();
  16619. this._audioEnabled = true;
  16620. this._headphone = false;
  16621. // Performance counters
  16622. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16623. this._totalLightsCounter = new BABYLON.PerfCounter();
  16624. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16625. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16626. this._totalVertices = new BABYLON.PerfCounter();
  16627. this._activeIndices = new BABYLON.PerfCounter();
  16628. this._activeParticles = new BABYLON.PerfCounter();
  16629. this._lastFrameDuration = new BABYLON.PerfCounter();
  16630. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16631. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16632. this._particlesDuration = new BABYLON.PerfCounter();
  16633. this._renderDuration = new BABYLON.PerfCounter();
  16634. this._spritesDuration = new BABYLON.PerfCounter();
  16635. this._activeBones = new BABYLON.PerfCounter();
  16636. this._renderId = 0;
  16637. this._executeWhenReadyTimeoutId = -1;
  16638. this._intermediateRendering = false;
  16639. this._toBeDisposed = new BABYLON.SmartArray(256);
  16640. this._pendingData = []; //ANY
  16641. this._activeMeshes = new BABYLON.SmartArray(256);
  16642. this._processedMaterials = new BABYLON.SmartArray(256);
  16643. this._renderTargets = new BABYLON.SmartArray(256);
  16644. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16645. this._activeSkeletons = new BABYLON.SmartArray(32);
  16646. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16647. this._activeAnimatables = new Array();
  16648. this._transformMatrix = BABYLON.Matrix.Zero();
  16649. this._edgesRenderers = new BABYLON.SmartArray(16);
  16650. this._uniqueIdCounter = 0;
  16651. this._engine = engine;
  16652. engine.scenes.push(this);
  16653. this._externalData = new BABYLON.StringDictionary();
  16654. this._uid = null;
  16655. this._renderingManager = new BABYLON.RenderingManager(this);
  16656. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16657. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16658. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16659. if (BABYLON.OutlineRenderer) {
  16660. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16661. }
  16662. this.attachControl();
  16663. if (BABYLON.SoundTrack) {
  16664. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16665. }
  16666. //simplification queue
  16667. if (BABYLON.SimplificationQueue) {
  16668. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16669. }
  16670. //collision coordinator initialization. For now legacy per default.
  16671. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16672. }
  16673. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16674. get: function () {
  16675. return Scene._FOGMODE_NONE;
  16676. },
  16677. enumerable: true,
  16678. configurable: true
  16679. });
  16680. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16681. get: function () {
  16682. return Scene._FOGMODE_EXP;
  16683. },
  16684. enumerable: true,
  16685. configurable: true
  16686. });
  16687. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16688. get: function () {
  16689. return Scene._FOGMODE_EXP2;
  16690. },
  16691. enumerable: true,
  16692. configurable: true
  16693. });
  16694. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16695. get: function () {
  16696. return Scene._FOGMODE_LINEAR;
  16697. },
  16698. enumerable: true,
  16699. configurable: true
  16700. });
  16701. Object.defineProperty(Scene.prototype, "onDispose", {
  16702. set: function (callback) {
  16703. if (this._onDisposeObserver) {
  16704. this.onDisposeObservable.remove(this._onDisposeObserver);
  16705. }
  16706. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16707. },
  16708. enumerable: true,
  16709. configurable: true
  16710. });
  16711. Object.defineProperty(Scene.prototype, "beforeRender", {
  16712. set: function (callback) {
  16713. if (this._onBeforeRenderObserver) {
  16714. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16715. }
  16716. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16717. },
  16718. enumerable: true,
  16719. configurable: true
  16720. });
  16721. Object.defineProperty(Scene.prototype, "afterRender", {
  16722. set: function (callback) {
  16723. if (this._onAfterRenderObserver) {
  16724. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16725. }
  16726. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16727. },
  16728. enumerable: true,
  16729. configurable: true
  16730. });
  16731. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16732. set: function (callback) {
  16733. if (this._onBeforeCameraRenderObserver) {
  16734. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16735. }
  16736. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16737. },
  16738. enumerable: true,
  16739. configurable: true
  16740. });
  16741. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16742. set: function (callback) {
  16743. if (this._onAfterCameraRenderObserver) {
  16744. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16745. }
  16746. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16747. },
  16748. enumerable: true,
  16749. configurable: true
  16750. });
  16751. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16752. get: function () {
  16753. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16754. },
  16755. enumerable: true,
  16756. configurable: true
  16757. });
  16758. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16759. get: function () {
  16760. if (!this._defaultMaterial) {
  16761. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16762. }
  16763. return this._defaultMaterial;
  16764. },
  16765. enumerable: true,
  16766. configurable: true
  16767. });
  16768. Object.defineProperty(Scene.prototype, "debugLayer", {
  16769. // Properties
  16770. get: function () {
  16771. if (!this._debugLayer) {
  16772. this._debugLayer = new BABYLON.DebugLayer(this);
  16773. }
  16774. return this._debugLayer;
  16775. },
  16776. enumerable: true,
  16777. configurable: true
  16778. });
  16779. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16780. get: function () {
  16781. return this._workerCollisions;
  16782. },
  16783. set: function (enabled) {
  16784. enabled = (enabled && !!Worker);
  16785. this._workerCollisions = enabled;
  16786. if (this.collisionCoordinator) {
  16787. this.collisionCoordinator.destroy();
  16788. }
  16789. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16790. this.collisionCoordinator.init(this);
  16791. },
  16792. enumerable: true,
  16793. configurable: true
  16794. });
  16795. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  16796. get: function () {
  16797. return this._selectionOctree;
  16798. },
  16799. enumerable: true,
  16800. configurable: true
  16801. });
  16802. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16803. /**
  16804. * The mesh that is currently under the pointer.
  16805. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16806. */
  16807. get: function () {
  16808. return this._pointerOverMesh;
  16809. },
  16810. enumerable: true,
  16811. configurable: true
  16812. });
  16813. Object.defineProperty(Scene.prototype, "pointerX", {
  16814. /**
  16815. * Current on-screen X position of the pointer
  16816. * @return {number} X position of the pointer
  16817. */
  16818. get: function () {
  16819. return this._pointerX;
  16820. },
  16821. enumerable: true,
  16822. configurable: true
  16823. });
  16824. Object.defineProperty(Scene.prototype, "pointerY", {
  16825. /**
  16826. * Current on-screen Y position of the pointer
  16827. * @return {number} Y position of the pointer
  16828. */
  16829. get: function () {
  16830. return this._pointerY;
  16831. },
  16832. enumerable: true,
  16833. configurable: true
  16834. });
  16835. Scene.prototype.getCachedMaterial = function () {
  16836. return this._cachedMaterial;
  16837. };
  16838. Scene.prototype.getBoundingBoxRenderer = function () {
  16839. return this._boundingBoxRenderer;
  16840. };
  16841. Scene.prototype.getOutlineRenderer = function () {
  16842. return this._outlineRenderer;
  16843. };
  16844. Scene.prototype.getEngine = function () {
  16845. return this._engine;
  16846. };
  16847. Scene.prototype.getTotalVertices = function () {
  16848. return this._totalVertices.current;
  16849. };
  16850. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16851. get: function () {
  16852. return this._totalVertices;
  16853. },
  16854. enumerable: true,
  16855. configurable: true
  16856. });
  16857. Scene.prototype.getActiveIndices = function () {
  16858. return this._activeIndices.current;
  16859. };
  16860. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16861. get: function () {
  16862. return this._activeIndices;
  16863. },
  16864. enumerable: true,
  16865. configurable: true
  16866. });
  16867. Scene.prototype.getActiveParticles = function () {
  16868. return this._activeParticles.current;
  16869. };
  16870. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16871. get: function () {
  16872. return this._activeParticles;
  16873. },
  16874. enumerable: true,
  16875. configurable: true
  16876. });
  16877. Scene.prototype.getActiveBones = function () {
  16878. return this._activeBones.current;
  16879. };
  16880. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16881. get: function () {
  16882. return this._activeBones;
  16883. },
  16884. enumerable: true,
  16885. configurable: true
  16886. });
  16887. // Stats
  16888. Scene.prototype.getLastFrameDuration = function () {
  16889. return this._lastFrameDuration.current;
  16890. };
  16891. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16892. get: function () {
  16893. return this._lastFrameDuration;
  16894. },
  16895. enumerable: true,
  16896. configurable: true
  16897. });
  16898. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16899. return this._evaluateActiveMeshesDuration.current;
  16900. };
  16901. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16902. get: function () {
  16903. return this._evaluateActiveMeshesDuration;
  16904. },
  16905. enumerable: true,
  16906. configurable: true
  16907. });
  16908. Scene.prototype.getActiveMeshes = function () {
  16909. return this._activeMeshes;
  16910. };
  16911. Scene.prototype.getRenderTargetsDuration = function () {
  16912. return this._renderTargetsDuration.current;
  16913. };
  16914. Scene.prototype.getRenderDuration = function () {
  16915. return this._renderDuration.current;
  16916. };
  16917. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16918. get: function () {
  16919. return this._renderDuration;
  16920. },
  16921. enumerable: true,
  16922. configurable: true
  16923. });
  16924. Scene.prototype.getParticlesDuration = function () {
  16925. return this._particlesDuration.current;
  16926. };
  16927. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16928. get: function () {
  16929. return this._particlesDuration;
  16930. },
  16931. enumerable: true,
  16932. configurable: true
  16933. });
  16934. Scene.prototype.getSpritesDuration = function () {
  16935. return this._spritesDuration.current;
  16936. };
  16937. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16938. get: function () {
  16939. return this._spritesDuration;
  16940. },
  16941. enumerable: true,
  16942. configurable: true
  16943. });
  16944. Scene.prototype.getAnimationRatio = function () {
  16945. return this._animationRatio;
  16946. };
  16947. Scene.prototype.getRenderId = function () {
  16948. return this._renderId;
  16949. };
  16950. Scene.prototype.incrementRenderId = function () {
  16951. this._renderId++;
  16952. };
  16953. Scene.prototype._updatePointerPosition = function (evt) {
  16954. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16955. this._pointerX = evt.clientX - canvasRect.left;
  16956. this._pointerY = evt.clientY - canvasRect.top;
  16957. this._unTranslatedPointerX = this._pointerX;
  16958. this._unTranslatedPointerY = this._pointerY;
  16959. if (this.cameraToUseForPointers) {
  16960. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16961. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16962. }
  16963. };
  16964. // Pointers handling
  16965. /**
  16966. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16967. * @param attachUp defines if you want to attach events to pointerup
  16968. * @param attachDown defines if you want to attach events to pointerdown
  16969. * @param attachMove defines if you want to attach events to pointermove
  16970. */
  16971. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16972. var _this = this;
  16973. if (attachUp === void 0) { attachUp = true; }
  16974. if (attachDown === void 0) { attachDown = true; }
  16975. if (attachMove === void 0) { attachMove = true; }
  16976. var spritePredicate = function (sprite) {
  16977. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16978. };
  16979. this._onPointerMove = function (evt) {
  16980. _this._updatePointerPosition(evt);
  16981. // PreObservable support
  16982. if (_this.onPrePointerObservable.hasObservers()) {
  16983. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16984. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16985. _this.onPrePointerObservable.notifyObservers(pi, type);
  16986. if (pi.skipOnPointerObservable) {
  16987. return;
  16988. }
  16989. }
  16990. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16991. return;
  16992. }
  16993. var canvas = _this._engine.getRenderingCanvas();
  16994. if (!_this.pointerMovePredicate) {
  16995. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  16996. }
  16997. // Meshes
  16998. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16999. if (pickResult.hit && pickResult.pickedMesh) {
  17000. _this.setPointerOverSprite(null);
  17001. _this.setPointerOverMesh(pickResult.pickedMesh);
  17002. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17003. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17004. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17005. }
  17006. else {
  17007. canvas.style.cursor = _this.hoverCursor;
  17008. }
  17009. }
  17010. else {
  17011. canvas.style.cursor = "";
  17012. }
  17013. }
  17014. else {
  17015. _this.setPointerOverMesh(null);
  17016. // Sprites
  17017. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17018. if (pickResult.hit && pickResult.pickedSprite) {
  17019. _this.setPointerOverSprite(pickResult.pickedSprite);
  17020. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17021. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17022. }
  17023. else {
  17024. canvas.style.cursor = _this.hoverCursor;
  17025. }
  17026. }
  17027. else {
  17028. _this.setPointerOverSprite(null);
  17029. // Restore pointer
  17030. canvas.style.cursor = "";
  17031. }
  17032. }
  17033. if (_this.onPointerMove) {
  17034. _this.onPointerMove(evt, pickResult);
  17035. }
  17036. if (_this.onPointerObservable.hasObservers()) {
  17037. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17038. var pi = new PointerInfo(type, evt, pickResult);
  17039. _this.onPointerObservable.notifyObservers(pi, type);
  17040. }
  17041. };
  17042. this._onPointerDown = function (evt) {
  17043. _this._updatePointerPosition(evt);
  17044. // PreObservable support
  17045. if (_this.onPrePointerObservable.hasObservers()) {
  17046. var type = PointerEventTypes.POINTERDOWN;
  17047. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17048. _this.onPrePointerObservable.notifyObservers(pi, type);
  17049. if (pi.skipOnPointerObservable) {
  17050. return;
  17051. }
  17052. }
  17053. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17054. return;
  17055. }
  17056. _this._startingPointerPosition.x = _this._pointerX;
  17057. _this._startingPointerPosition.y = _this._pointerY;
  17058. _this._startingPointerTime = new Date().getTime();
  17059. if (!_this.pointerDownPredicate) {
  17060. _this.pointerDownPredicate = function (mesh) {
  17061. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17062. };
  17063. }
  17064. // Meshes
  17065. _this._pickedDownMesh = null;
  17066. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17067. if (pickResult.hit && pickResult.pickedMesh) {
  17068. if (pickResult.pickedMesh.actionManager) {
  17069. _this._pickedDownMesh = pickResult.pickedMesh;
  17070. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  17071. switch (evt.button) {
  17072. case 0:
  17073. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17074. break;
  17075. case 1:
  17076. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17077. break;
  17078. case 2:
  17079. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17080. break;
  17081. }
  17082. if (pickResult.pickedMesh.actionManager) {
  17083. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17084. }
  17085. }
  17086. if (pickResult.pickedMesh.actionManager && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17087. var that = _this;
  17088. window.setTimeout(function () {
  17089. 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);
  17090. if (pickResult.hit && pickResult.pickedMesh) {
  17091. if (pickResult.pickedMesh.actionManager) {
  17092. 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)) {
  17093. that._startingPointerTime = 0;
  17094. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17095. }
  17096. }
  17097. }
  17098. }, BABYLON.ActionManager.LongPressDelay);
  17099. }
  17100. }
  17101. }
  17102. if (_this.onPointerDown) {
  17103. _this.onPointerDown(evt, pickResult);
  17104. }
  17105. if (_this.onPointerObservable.hasObservers()) {
  17106. var type = PointerEventTypes.POINTERDOWN;
  17107. var pi = new PointerInfo(type, evt, pickResult);
  17108. _this.onPointerObservable.notifyObservers(pi, type);
  17109. }
  17110. // Sprites
  17111. _this._pickedDownSprite = null;
  17112. if (_this.spriteManagers.length > 0) {
  17113. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17114. if (pickResult.hit && pickResult.pickedSprite) {
  17115. if (pickResult.pickedSprite.actionManager) {
  17116. _this._pickedDownSprite = pickResult.pickedSprite;
  17117. switch (evt.button) {
  17118. case 0:
  17119. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17120. break;
  17121. case 1:
  17122. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17123. break;
  17124. case 2:
  17125. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17126. break;
  17127. }
  17128. if (pickResult.pickedSprite.actionManager) {
  17129. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17130. }
  17131. }
  17132. }
  17133. }
  17134. };
  17135. this._onPointerUp = function (evt) {
  17136. _this._updatePointerPosition(evt);
  17137. // PreObservable support
  17138. if (_this.onPrePointerObservable.hasObservers()) {
  17139. var type = PointerEventTypes.POINTERUP;
  17140. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17141. _this.onPrePointerObservable.notifyObservers(pi, type);
  17142. if (pi.skipOnPointerObservable) {
  17143. return;
  17144. }
  17145. }
  17146. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17147. return;
  17148. }
  17149. if (!_this.pointerUpPredicate) {
  17150. _this.pointerUpPredicate = function (mesh) {
  17151. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17152. };
  17153. }
  17154. // Meshes
  17155. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  17156. if (pickResult.hit && pickResult.pickedMesh) {
  17157. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  17158. if (_this.onPointerPick) {
  17159. _this.onPointerPick(evt, pickResult);
  17160. }
  17161. if (_this.onPointerObservable.hasObservers()) {
  17162. var type = PointerEventTypes.POINTERPICK;
  17163. var pi = new PointerInfo(type, evt, pickResult);
  17164. _this.onPointerObservable.notifyObservers(pi, type);
  17165. }
  17166. }
  17167. if (pickResult.pickedMesh.actionManager) {
  17168. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17169. if (pickResult.pickedMesh.actionManager) {
  17170. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17171. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17172. }
  17173. }
  17174. }
  17175. }
  17176. if (_this._pickedDownMesh && _this._pickedDownMesh.actionManager && _this._pickedDownMesh !== pickResult.pickedMesh) {
  17177. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  17178. }
  17179. if (_this.onPointerUp) {
  17180. _this.onPointerUp(evt, pickResult);
  17181. }
  17182. if (_this.onPointerObservable.hasObservers()) {
  17183. var type = PointerEventTypes.POINTERUP;
  17184. var pi = new PointerInfo(type, evt, pickResult);
  17185. _this.onPointerObservable.notifyObservers(pi, type);
  17186. }
  17187. _this._startingPointerTime = 0;
  17188. // Sprites
  17189. if (_this.spriteManagers.length > 0) {
  17190. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17191. if (pickResult.hit && pickResult.pickedSprite) {
  17192. if (pickResult.pickedSprite.actionManager) {
  17193. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17194. if (pickResult.pickedSprite.actionManager) {
  17195. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17196. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17197. }
  17198. }
  17199. }
  17200. }
  17201. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
  17202. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  17203. }
  17204. }
  17205. };
  17206. this._onKeyDown = function (evt) {
  17207. if (_this.actionManager) {
  17208. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17209. }
  17210. };
  17211. this._onKeyUp = function (evt) {
  17212. if (_this.actionManager) {
  17213. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17214. }
  17215. };
  17216. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17217. var canvas = this._engine.getRenderingCanvas();
  17218. if (attachMove) {
  17219. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17220. // Wheel
  17221. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17222. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17223. }
  17224. if (attachDown) {
  17225. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17226. }
  17227. if (attachUp) {
  17228. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17229. }
  17230. canvas.tabIndex = 1;
  17231. canvas.addEventListener("keydown", this._onKeyDown, false);
  17232. canvas.addEventListener("keyup", this._onKeyUp, false);
  17233. };
  17234. Scene.prototype.detachControl = function () {
  17235. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17236. var canvas = this._engine.getRenderingCanvas();
  17237. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17238. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17239. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17240. // Wheel
  17241. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17242. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17243. canvas.removeEventListener("keydown", this._onKeyDown);
  17244. canvas.removeEventListener("keyup", this._onKeyUp);
  17245. };
  17246. // Ready
  17247. Scene.prototype.isReady = function () {
  17248. if (this._pendingData.length > 0) {
  17249. return false;
  17250. }
  17251. var index;
  17252. for (index = 0; index < this._geometries.length; index++) {
  17253. var geometry = this._geometries[index];
  17254. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17255. return false;
  17256. }
  17257. }
  17258. for (index = 0; index < this.meshes.length; index++) {
  17259. var mesh = this.meshes[index];
  17260. if (!mesh.isReady()) {
  17261. return false;
  17262. }
  17263. var mat = mesh.material;
  17264. if (mat) {
  17265. if (!mat.isReady(mesh)) {
  17266. return false;
  17267. }
  17268. }
  17269. }
  17270. return true;
  17271. };
  17272. Scene.prototype.resetCachedMaterial = function () {
  17273. this._cachedMaterial = null;
  17274. };
  17275. Scene.prototype.registerBeforeRender = function (func) {
  17276. this.onBeforeRenderObservable.add(func);
  17277. };
  17278. Scene.prototype.unregisterBeforeRender = function (func) {
  17279. this.onBeforeRenderObservable.removeCallback(func);
  17280. };
  17281. Scene.prototype.registerAfterRender = function (func) {
  17282. this.onAfterRenderObservable.add(func);
  17283. };
  17284. Scene.prototype.unregisterAfterRender = function (func) {
  17285. this.onAfterRenderObservable.removeCallback(func);
  17286. };
  17287. Scene.prototype._addPendingData = function (data) {
  17288. this._pendingData.push(data);
  17289. };
  17290. Scene.prototype._removePendingData = function (data) {
  17291. var index = this._pendingData.indexOf(data);
  17292. if (index !== -1) {
  17293. this._pendingData.splice(index, 1);
  17294. }
  17295. };
  17296. Scene.prototype.getWaitingItemsCount = function () {
  17297. return this._pendingData.length;
  17298. };
  17299. /**
  17300. * Registers a function to be executed when the scene is ready.
  17301. * @param {Function} func - the function to be executed.
  17302. */
  17303. Scene.prototype.executeWhenReady = function (func) {
  17304. var _this = this;
  17305. this.onReadyObservable.add(func);
  17306. if (this._executeWhenReadyTimeoutId !== -1) {
  17307. return;
  17308. }
  17309. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17310. _this._checkIsReady();
  17311. }, 150);
  17312. };
  17313. Scene.prototype._checkIsReady = function () {
  17314. var _this = this;
  17315. if (this.isReady()) {
  17316. this.onReadyObservable.notifyObservers(this);
  17317. this.onReadyObservable.clear();
  17318. this._executeWhenReadyTimeoutId = -1;
  17319. return;
  17320. }
  17321. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17322. _this._checkIsReady();
  17323. }, 150);
  17324. };
  17325. // Animations
  17326. /**
  17327. * Will start the animation sequence of a given target
  17328. * @param target - the target
  17329. * @param {number} from - from which frame should animation start
  17330. * @param {number} to - till which frame should animation run.
  17331. * @param {boolean} [loop] - should the animation loop
  17332. * @param {number} [speedRatio] - the speed in which to run the animation
  17333. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17334. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17335. * @return {BABYLON.Animatable} the animatable object created for this animation
  17336. * @see BABYLON.Animatable
  17337. * @see http://doc.babylonjs.com/page.php?p=22081
  17338. */
  17339. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17340. if (speedRatio === void 0) { speedRatio = 1.0; }
  17341. this.stopAnimation(target);
  17342. if (!animatable) {
  17343. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17344. }
  17345. // Local animations
  17346. if (target.animations) {
  17347. animatable.appendAnimations(target, target.animations);
  17348. }
  17349. // Children animations
  17350. if (target.getAnimatables) {
  17351. var animatables = target.getAnimatables();
  17352. for (var index = 0; index < animatables.length; index++) {
  17353. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17354. }
  17355. }
  17356. animatable.reset();
  17357. return animatable;
  17358. };
  17359. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17360. if (speedRatio === undefined) {
  17361. speedRatio = 1.0;
  17362. }
  17363. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17364. return animatable;
  17365. };
  17366. Scene.prototype.getAnimatableByTarget = function (target) {
  17367. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17368. if (this._activeAnimatables[index].target === target) {
  17369. return this._activeAnimatables[index];
  17370. }
  17371. }
  17372. return null;
  17373. };
  17374. Object.defineProperty(Scene.prototype, "Animatables", {
  17375. get: function () {
  17376. return this._activeAnimatables;
  17377. },
  17378. enumerable: true,
  17379. configurable: true
  17380. });
  17381. /**
  17382. * Will stop the animation of the given target
  17383. * @param target - the target
  17384. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17385. * @see beginAnimation
  17386. */
  17387. Scene.prototype.stopAnimation = function (target, animationName) {
  17388. var animatable = this.getAnimatableByTarget(target);
  17389. if (animatable) {
  17390. animatable.stop(animationName);
  17391. }
  17392. };
  17393. Scene.prototype._animate = function () {
  17394. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17395. return;
  17396. }
  17397. if (!this._animationStartDate) {
  17398. if (this._pendingData.length > 0) {
  17399. return;
  17400. }
  17401. this._animationStartDate = BABYLON.Tools.Now;
  17402. }
  17403. // Getting time
  17404. var now = BABYLON.Tools.Now;
  17405. var delay = now - this._animationStartDate;
  17406. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17407. this._activeAnimatables[index]._animate(delay);
  17408. }
  17409. };
  17410. // Matrix
  17411. Scene.prototype.getViewMatrix = function () {
  17412. return this._viewMatrix;
  17413. };
  17414. Scene.prototype.getProjectionMatrix = function () {
  17415. return this._projectionMatrix;
  17416. };
  17417. Scene.prototype.getTransformMatrix = function () {
  17418. return this._transformMatrix;
  17419. };
  17420. Scene.prototype.setTransformMatrix = function (view, projection) {
  17421. this._viewMatrix = view;
  17422. this._projectionMatrix = projection;
  17423. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17424. // Update frustum
  17425. if (!this._frustumPlanes) {
  17426. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17427. }
  17428. else {
  17429. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17430. }
  17431. };
  17432. // Methods
  17433. Scene.prototype.addMesh = function (newMesh) {
  17434. newMesh.uniqueId = this._uniqueIdCounter++;
  17435. var position = this.meshes.push(newMesh);
  17436. //notify the collision coordinator
  17437. this.collisionCoordinator.onMeshAdded(newMesh);
  17438. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17439. };
  17440. Scene.prototype.removeMesh = function (toRemove) {
  17441. var index = this.meshes.indexOf(toRemove);
  17442. if (index !== -1) {
  17443. // Remove from the scene if mesh found
  17444. this.meshes.splice(index, 1);
  17445. }
  17446. //notify the collision coordinator
  17447. this.collisionCoordinator.onMeshRemoved(toRemove);
  17448. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17449. return index;
  17450. };
  17451. Scene.prototype.removeSkeleton = function (toRemove) {
  17452. var index = this.skeletons.indexOf(toRemove);
  17453. if (index !== -1) {
  17454. // Remove from the scene if mesh found
  17455. this.skeletons.splice(index, 1);
  17456. }
  17457. return index;
  17458. };
  17459. Scene.prototype.removeLight = function (toRemove) {
  17460. var index = this.lights.indexOf(toRemove);
  17461. if (index !== -1) {
  17462. // Remove from the scene if mesh found
  17463. this.lights.splice(index, 1);
  17464. }
  17465. this.onLightRemovedObservable.notifyObservers(toRemove);
  17466. return index;
  17467. };
  17468. Scene.prototype.removeCamera = function (toRemove) {
  17469. var index = this.cameras.indexOf(toRemove);
  17470. if (index !== -1) {
  17471. // Remove from the scene if mesh found
  17472. this.cameras.splice(index, 1);
  17473. }
  17474. // Remove from activeCameras
  17475. var index2 = this.activeCameras.indexOf(toRemove);
  17476. if (index2 !== -1) {
  17477. // Remove from the scene if mesh found
  17478. this.activeCameras.splice(index2, 1);
  17479. }
  17480. // Reset the activeCamera
  17481. if (this.activeCamera === toRemove) {
  17482. if (this.cameras.length > 0) {
  17483. this.activeCamera = this.cameras[0];
  17484. }
  17485. else {
  17486. this.activeCamera = null;
  17487. }
  17488. }
  17489. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17490. return index;
  17491. };
  17492. Scene.prototype.addLight = function (newLight) {
  17493. newLight.uniqueId = this._uniqueIdCounter++;
  17494. var position = this.lights.push(newLight);
  17495. this.onNewLightAddedObservable.notifyObservers(newLight);
  17496. };
  17497. Scene.prototype.addCamera = function (newCamera) {
  17498. newCamera.uniqueId = this._uniqueIdCounter++;
  17499. var position = this.cameras.push(newCamera);
  17500. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17501. };
  17502. /**
  17503. * Switch active camera
  17504. * @param {Camera} newCamera - new active camera
  17505. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17506. */
  17507. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17508. if (attachControl === void 0) { attachControl = true; }
  17509. var canvas = this._engine.getRenderingCanvas();
  17510. this.activeCamera.detachControl(canvas);
  17511. this.activeCamera = newCamera;
  17512. if (attachControl) {
  17513. newCamera.attachControl(canvas);
  17514. }
  17515. };
  17516. /**
  17517. * sets the active camera of the scene using its ID
  17518. * @param {string} id - the camera's ID
  17519. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17520. * @see activeCamera
  17521. */
  17522. Scene.prototype.setActiveCameraByID = function (id) {
  17523. var camera = this.getCameraByID(id);
  17524. if (camera) {
  17525. this.activeCamera = camera;
  17526. return camera;
  17527. }
  17528. return null;
  17529. };
  17530. /**
  17531. * sets the active camera of the scene using its name
  17532. * @param {string} name - the camera's name
  17533. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17534. * @see activeCamera
  17535. */
  17536. Scene.prototype.setActiveCameraByName = function (name) {
  17537. var camera = this.getCameraByName(name);
  17538. if (camera) {
  17539. this.activeCamera = camera;
  17540. return camera;
  17541. }
  17542. return null;
  17543. };
  17544. /**
  17545. * get a material using its id
  17546. * @param {string} the material's ID
  17547. * @return {BABYLON.Material|null} the material or null if none found.
  17548. */
  17549. Scene.prototype.getMaterialByID = function (id) {
  17550. for (var index = 0; index < this.materials.length; index++) {
  17551. if (this.materials[index].id === id) {
  17552. return this.materials[index];
  17553. }
  17554. }
  17555. return null;
  17556. };
  17557. /**
  17558. * get a material using its name
  17559. * @param {string} the material's name
  17560. * @return {BABYLON.Material|null} the material or null if none found.
  17561. */
  17562. Scene.prototype.getMaterialByName = function (name) {
  17563. for (var index = 0; index < this.materials.length; index++) {
  17564. if (this.materials[index].name === name) {
  17565. return this.materials[index];
  17566. }
  17567. }
  17568. return null;
  17569. };
  17570. Scene.prototype.getLensFlareSystemByName = function (name) {
  17571. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17572. if (this.lensFlareSystems[index].name === name) {
  17573. return this.lensFlareSystems[index];
  17574. }
  17575. }
  17576. return null;
  17577. };
  17578. Scene.prototype.getLensFlareSystemByID = function (id) {
  17579. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17580. if (this.lensFlareSystems[index].id === id) {
  17581. return this.lensFlareSystems[index];
  17582. }
  17583. }
  17584. return null;
  17585. };
  17586. Scene.prototype.getCameraByID = function (id) {
  17587. for (var index = 0; index < this.cameras.length; index++) {
  17588. if (this.cameras[index].id === id) {
  17589. return this.cameras[index];
  17590. }
  17591. }
  17592. return null;
  17593. };
  17594. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17595. for (var index = 0; index < this.cameras.length; index++) {
  17596. if (this.cameras[index].uniqueId === uniqueId) {
  17597. return this.cameras[index];
  17598. }
  17599. }
  17600. return null;
  17601. };
  17602. /**
  17603. * get a camera using its name
  17604. * @param {string} the camera's name
  17605. * @return {BABYLON.Camera|null} the camera or null if none found.
  17606. */
  17607. Scene.prototype.getCameraByName = function (name) {
  17608. for (var index = 0; index < this.cameras.length; index++) {
  17609. if (this.cameras[index].name === name) {
  17610. return this.cameras[index];
  17611. }
  17612. }
  17613. return null;
  17614. };
  17615. /**
  17616. * get a bone using its id
  17617. * @param {string} the bone's id
  17618. * @return {BABYLON.Bone|null} the bone or null if not found
  17619. */
  17620. Scene.prototype.getBoneByID = function (id) {
  17621. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17622. var skeleton = this.skeletons[skeletonIndex];
  17623. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17624. if (skeleton.bones[boneIndex].id === id) {
  17625. return skeleton.bones[boneIndex];
  17626. }
  17627. }
  17628. }
  17629. return null;
  17630. };
  17631. /**
  17632. * get a bone using its id
  17633. * @param {string} the bone's name
  17634. * @return {BABYLON.Bone|null} the bone or null if not found
  17635. */
  17636. Scene.prototype.getBoneByName = function (name) {
  17637. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17638. var skeleton = this.skeletons[skeletonIndex];
  17639. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17640. if (skeleton.bones[boneIndex].name === name) {
  17641. return skeleton.bones[boneIndex];
  17642. }
  17643. }
  17644. }
  17645. return null;
  17646. };
  17647. /**
  17648. * get a light node using its name
  17649. * @param {string} the light's name
  17650. * @return {BABYLON.Light|null} the light or null if none found.
  17651. */
  17652. Scene.prototype.getLightByName = function (name) {
  17653. for (var index = 0; index < this.lights.length; index++) {
  17654. if (this.lights[index].name === name) {
  17655. return this.lights[index];
  17656. }
  17657. }
  17658. return null;
  17659. };
  17660. /**
  17661. * get a light node using its ID
  17662. * @param {string} the light's id
  17663. * @return {BABYLON.Light|null} the light or null if none found.
  17664. */
  17665. Scene.prototype.getLightByID = function (id) {
  17666. for (var index = 0; index < this.lights.length; index++) {
  17667. if (this.lights[index].id === id) {
  17668. return this.lights[index];
  17669. }
  17670. }
  17671. return null;
  17672. };
  17673. /**
  17674. * get a light node using its scene-generated unique ID
  17675. * @param {number} the light's unique id
  17676. * @return {BABYLON.Light|null} the light or null if none found.
  17677. */
  17678. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17679. for (var index = 0; index < this.lights.length; index++) {
  17680. if (this.lights[index].uniqueId === uniqueId) {
  17681. return this.lights[index];
  17682. }
  17683. }
  17684. return null;
  17685. };
  17686. /**
  17687. * get a particle system by id
  17688. * @param id {number} the particle system id
  17689. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17690. */
  17691. Scene.prototype.getParticleSystemByID = function (id) {
  17692. for (var index = 0; index < this.particleSystems.length; index++) {
  17693. if (this.particleSystems[index].id === id) {
  17694. return this.particleSystems[index];
  17695. }
  17696. }
  17697. return null;
  17698. };
  17699. /**
  17700. * get a geometry using its ID
  17701. * @param {string} the geometry's id
  17702. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17703. */
  17704. Scene.prototype.getGeometryByID = function (id) {
  17705. for (var index = 0; index < this._geometries.length; index++) {
  17706. if (this._geometries[index].id === id) {
  17707. return this._geometries[index];
  17708. }
  17709. }
  17710. return null;
  17711. };
  17712. /**
  17713. * add a new geometry to this scene.
  17714. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17715. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17716. * @return {boolean} was the geometry added or not
  17717. */
  17718. Scene.prototype.pushGeometry = function (geometry, force) {
  17719. if (!force && this.getGeometryByID(geometry.id)) {
  17720. return false;
  17721. }
  17722. this._geometries.push(geometry);
  17723. //notify the collision coordinator
  17724. this.collisionCoordinator.onGeometryAdded(geometry);
  17725. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17726. return true;
  17727. };
  17728. /**
  17729. * Removes an existing geometry
  17730. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17731. * @return {boolean} was the geometry removed or not
  17732. */
  17733. Scene.prototype.removeGeometry = function (geometry) {
  17734. var index = this._geometries.indexOf(geometry);
  17735. if (index > -1) {
  17736. this._geometries.splice(index, 1);
  17737. //notify the collision coordinator
  17738. this.collisionCoordinator.onGeometryDeleted(geometry);
  17739. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17740. return true;
  17741. }
  17742. return false;
  17743. };
  17744. Scene.prototype.getGeometries = function () {
  17745. return this._geometries;
  17746. };
  17747. /**
  17748. * Get the first added mesh found of a given ID
  17749. * @param {string} id - the id to search for
  17750. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17751. */
  17752. Scene.prototype.getMeshByID = function (id) {
  17753. for (var index = 0; index < this.meshes.length; index++) {
  17754. if (this.meshes[index].id === id) {
  17755. return this.meshes[index];
  17756. }
  17757. }
  17758. return null;
  17759. };
  17760. Scene.prototype.getMeshesByID = function (id) {
  17761. return this.meshes.filter(function (m) {
  17762. return m.id === id;
  17763. });
  17764. };
  17765. /**
  17766. * Get a mesh with its auto-generated unique id
  17767. * @param {number} uniqueId - the unique id to search for
  17768. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17769. */
  17770. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17771. for (var index = 0; index < this.meshes.length; index++) {
  17772. if (this.meshes[index].uniqueId === uniqueId) {
  17773. return this.meshes[index];
  17774. }
  17775. }
  17776. return null;
  17777. };
  17778. /**
  17779. * Get a the last added mesh found of a given ID
  17780. * @param {string} id - the id to search for
  17781. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17782. */
  17783. Scene.prototype.getLastMeshByID = function (id) {
  17784. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17785. if (this.meshes[index].id === id) {
  17786. return this.meshes[index];
  17787. }
  17788. }
  17789. return null;
  17790. };
  17791. /**
  17792. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17793. * @param {string} id - the id to search for
  17794. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17795. */
  17796. Scene.prototype.getLastEntryByID = function (id) {
  17797. var index;
  17798. for (index = this.meshes.length - 1; index >= 0; index--) {
  17799. if (this.meshes[index].id === id) {
  17800. return this.meshes[index];
  17801. }
  17802. }
  17803. for (index = this.cameras.length - 1; index >= 0; index--) {
  17804. if (this.cameras[index].id === id) {
  17805. return this.cameras[index];
  17806. }
  17807. }
  17808. for (index = this.lights.length - 1; index >= 0; index--) {
  17809. if (this.lights[index].id === id) {
  17810. return this.lights[index];
  17811. }
  17812. }
  17813. return null;
  17814. };
  17815. Scene.prototype.getNodeByID = function (id) {
  17816. var mesh = this.getMeshByID(id);
  17817. if (mesh) {
  17818. return mesh;
  17819. }
  17820. var light = this.getLightByID(id);
  17821. if (light) {
  17822. return light;
  17823. }
  17824. var camera = this.getCameraByID(id);
  17825. if (camera) {
  17826. return camera;
  17827. }
  17828. var bone = this.getBoneByID(id);
  17829. return bone;
  17830. };
  17831. Scene.prototype.getNodeByName = function (name) {
  17832. var mesh = this.getMeshByName(name);
  17833. if (mesh) {
  17834. return mesh;
  17835. }
  17836. var light = this.getLightByName(name);
  17837. if (light) {
  17838. return light;
  17839. }
  17840. var camera = this.getCameraByName(name);
  17841. if (camera) {
  17842. return camera;
  17843. }
  17844. var bone = this.getBoneByName(name);
  17845. return bone;
  17846. };
  17847. Scene.prototype.getMeshByName = function (name) {
  17848. for (var index = 0; index < this.meshes.length; index++) {
  17849. if (this.meshes[index].name === name) {
  17850. return this.meshes[index];
  17851. }
  17852. }
  17853. return null;
  17854. };
  17855. Scene.prototype.getSoundByName = function (name) {
  17856. var index;
  17857. if (BABYLON.AudioEngine) {
  17858. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17859. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17860. return this.mainSoundTrack.soundCollection[index];
  17861. }
  17862. }
  17863. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17864. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17865. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17866. return this.soundTracks[sdIndex].soundCollection[index];
  17867. }
  17868. }
  17869. }
  17870. }
  17871. return null;
  17872. };
  17873. Scene.prototype.getLastSkeletonByID = function (id) {
  17874. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17875. if (this.skeletons[index].id === id) {
  17876. return this.skeletons[index];
  17877. }
  17878. }
  17879. return null;
  17880. };
  17881. Scene.prototype.getSkeletonById = function (id) {
  17882. for (var index = 0; index < this.skeletons.length; index++) {
  17883. if (this.skeletons[index].id === id) {
  17884. return this.skeletons[index];
  17885. }
  17886. }
  17887. return null;
  17888. };
  17889. Scene.prototype.getSkeletonByName = function (name) {
  17890. for (var index = 0; index < this.skeletons.length; index++) {
  17891. if (this.skeletons[index].name === name) {
  17892. return this.skeletons[index];
  17893. }
  17894. }
  17895. return null;
  17896. };
  17897. Scene.prototype.isActiveMesh = function (mesh) {
  17898. return (this._activeMeshes.indexOf(mesh) !== -1);
  17899. };
  17900. Object.defineProperty(Scene.prototype, "uid", {
  17901. /**
  17902. * Return a unique id as a string which can serve as an identifier for the scene
  17903. */
  17904. get: function () {
  17905. if (!this._uid) {
  17906. this._uid = BABYLON.Tools.RandomId();
  17907. }
  17908. return this._uid;
  17909. },
  17910. enumerable: true,
  17911. configurable: true
  17912. });
  17913. /**
  17914. * Add an externaly attached data from its key.
  17915. * This method call will fail and return false, if such key already exists.
  17916. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17917. * @param key the unique key that identifies the data
  17918. * @param data the data object to associate to the key for this Engine instance
  17919. * @return true if no such key were already present and the data was added successfully, false otherwise
  17920. */
  17921. Scene.prototype.addExternalData = function (key, data) {
  17922. return this._externalData.add(key, data);
  17923. };
  17924. /**
  17925. * Get an externaly attached data from its key
  17926. * @param key the unique key that identifies the data
  17927. * @return the associated data, if present (can be null), or undefined if not present
  17928. */
  17929. Scene.prototype.getExternalData = function (key) {
  17930. return this._externalData.get(key);
  17931. };
  17932. /**
  17933. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17934. * @param key the unique key that identifies the data
  17935. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17936. * @return the associated data, can be null if the factory returned null.
  17937. */
  17938. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17939. return this._externalData.getOrAddWithFactory(key, factory);
  17940. };
  17941. /**
  17942. * Remove an externaly attached data from the Engine instance
  17943. * @param key the unique key that identifies the data
  17944. * @return true if the data was successfully removed, false if it doesn't exist
  17945. */
  17946. Scene.prototype.removeExternalData = function (key) {
  17947. return this._externalData.remove(key);
  17948. };
  17949. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17950. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17951. var material = subMesh.getMaterial();
  17952. if (mesh.showSubMeshesBoundingBox) {
  17953. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  17954. }
  17955. if (material) {
  17956. // Render targets
  17957. if (material.getRenderTargetTextures) {
  17958. if (this._processedMaterials.indexOf(material) === -1) {
  17959. this._processedMaterials.push(material);
  17960. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17961. }
  17962. }
  17963. // Dispatch
  17964. this._activeIndices.addCount(subMesh.indexCount, false);
  17965. this._renderingManager.dispatch(subMesh);
  17966. }
  17967. }
  17968. };
  17969. Scene.prototype._isInIntermediateRendering = function () {
  17970. return this._intermediateRendering;
  17971. };
  17972. Scene.prototype._evaluateActiveMeshes = function () {
  17973. this.activeCamera._activeMeshes.reset();
  17974. this._activeMeshes.reset();
  17975. this._renderingManager.reset();
  17976. this._processedMaterials.reset();
  17977. this._activeParticleSystems.reset();
  17978. this._activeSkeletons.reset();
  17979. this._softwareSkinnedMeshes.reset();
  17980. this._boundingBoxRenderer.reset();
  17981. this._edgesRenderers.reset();
  17982. // Meshes
  17983. var meshes;
  17984. var len;
  17985. if (this._selectionOctree) {
  17986. var selection = this._selectionOctree.select(this._frustumPlanes);
  17987. meshes = selection.data;
  17988. len = selection.length;
  17989. }
  17990. else {
  17991. len = this.meshes.length;
  17992. meshes = this.meshes;
  17993. }
  17994. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17995. var mesh = meshes[meshIndex];
  17996. if (mesh.isBlocked) {
  17997. continue;
  17998. }
  17999. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18000. if (!mesh.isReady() || !mesh.isEnabled()) {
  18001. continue;
  18002. }
  18003. mesh.computeWorldMatrix();
  18004. // Intersections
  18005. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18006. this._meshesForIntersections.pushNoDuplicate(mesh);
  18007. }
  18008. // Switch to current LOD
  18009. var meshLOD = mesh.getLOD(this.activeCamera);
  18010. if (!meshLOD) {
  18011. continue;
  18012. }
  18013. mesh._preActivate();
  18014. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18015. this._activeMeshes.push(mesh);
  18016. this.activeCamera._activeMeshes.push(mesh);
  18017. mesh._activate(this._renderId);
  18018. this._activeMesh(mesh, meshLOD);
  18019. }
  18020. }
  18021. // Particle systems
  18022. this._particlesDuration.beginMonitoring();
  18023. var beforeParticlesDate = BABYLON.Tools.Now;
  18024. if (this.particlesEnabled) {
  18025. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18026. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18027. var particleSystem = this.particleSystems[particleIndex];
  18028. if (!particleSystem.isStarted()) {
  18029. continue;
  18030. }
  18031. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  18032. this._activeParticleSystems.push(particleSystem);
  18033. particleSystem.animate();
  18034. }
  18035. }
  18036. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18037. }
  18038. this._particlesDuration.endMonitoring(false);
  18039. };
  18040. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18041. if (mesh.skeleton && this.skeletonsEnabled) {
  18042. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18043. mesh.skeleton.prepare();
  18044. }
  18045. if (!mesh.computeBonesUsingShaders) {
  18046. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18047. }
  18048. }
  18049. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18050. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18051. }
  18052. if (sourceMesh._edgesRenderer) {
  18053. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  18054. }
  18055. if (mesh && mesh.subMeshes) {
  18056. // Submeshes Octrees
  18057. var len;
  18058. var subMeshes;
  18059. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18060. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18061. len = intersections.length;
  18062. subMeshes = intersections.data;
  18063. }
  18064. else {
  18065. subMeshes = mesh.subMeshes;
  18066. len = subMeshes.length;
  18067. }
  18068. for (var subIndex = 0; subIndex < len; subIndex++) {
  18069. var subMesh = subMeshes[subIndex];
  18070. this._evaluateSubMesh(subMesh, mesh);
  18071. }
  18072. }
  18073. };
  18074. Scene.prototype.updateTransformMatrix = function (force) {
  18075. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18076. };
  18077. Scene.prototype._renderForCamera = function (camera) {
  18078. var engine = this._engine;
  18079. var startTime = BABYLON.Tools.Now;
  18080. this.activeCamera = camera;
  18081. if (!this.activeCamera)
  18082. throw new Error("Active camera not set");
  18083. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18084. // Viewport
  18085. engine.setViewport(this.activeCamera.viewport);
  18086. // Camera
  18087. this.resetCachedMaterial();
  18088. this._renderId++;
  18089. this.updateTransformMatrix();
  18090. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18091. // Meshes
  18092. this._evaluateActiveMeshesDuration.beginMonitoring();
  18093. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18094. this._evaluateActiveMeshes();
  18095. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18096. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18097. // Software skinning
  18098. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18099. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18100. mesh.applySkeleton(mesh.skeleton);
  18101. }
  18102. // Render targets
  18103. this._renderTargetsDuration.beginMonitoring();
  18104. var needsRestoreFrameBuffer = false;
  18105. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18106. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18107. this._intermediateRendering = true;
  18108. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18109. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18110. var renderTarget = this._renderTargets.data[renderIndex];
  18111. if (renderTarget._shouldRender()) {
  18112. this._renderId++;
  18113. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18114. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18115. }
  18116. }
  18117. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18118. this._intermediateRendering = false;
  18119. this._renderId++;
  18120. needsRestoreFrameBuffer = true; // Restore back buffer
  18121. }
  18122. // Render HighlightLayer Texture
  18123. var stencilState = this._engine.getStencilBuffer();
  18124. var renderhighlights = false;
  18125. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18126. this._intermediateRendering = true;
  18127. for (var i = 0; i < this.highlightLayers.length; i++) {
  18128. var highlightLayer = this.highlightLayers[i];
  18129. if (highlightLayer.shouldRender() &&
  18130. (!highlightLayer.camera ||
  18131. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18132. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18133. renderhighlights = true;
  18134. var renderTarget = highlightLayer._mainTexture;
  18135. if (renderTarget._shouldRender()) {
  18136. this._renderId++;
  18137. renderTarget.render(false, false);
  18138. needsRestoreFrameBuffer = true;
  18139. }
  18140. }
  18141. }
  18142. this._intermediateRendering = false;
  18143. this._renderId++;
  18144. }
  18145. if (needsRestoreFrameBuffer) {
  18146. engine.restoreDefaultFramebuffer();
  18147. }
  18148. this._renderTargetsDuration.endMonitoring(false);
  18149. // Prepare Frame
  18150. this.postProcessManager._prepareFrame();
  18151. this._renderDuration.beginMonitoring();
  18152. // Backgrounds
  18153. var layerIndex;
  18154. var layer;
  18155. if (this.layers.length) {
  18156. engine.setDepthBuffer(false);
  18157. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18158. layer = this.layers[layerIndex];
  18159. if (layer.isBackground) {
  18160. layer.render();
  18161. }
  18162. }
  18163. engine.setDepthBuffer(true);
  18164. }
  18165. // Render
  18166. BABYLON.Tools.StartPerformanceCounter("Main render");
  18167. // Activate HighlightLayer stencil
  18168. if (renderhighlights) {
  18169. this._engine.setStencilBuffer(true);
  18170. }
  18171. this._renderingManager.render(null, null, true, true);
  18172. // Restore HighlightLayer stencil
  18173. if (renderhighlights) {
  18174. this._engine.setStencilBuffer(stencilState);
  18175. }
  18176. BABYLON.Tools.EndPerformanceCounter("Main render");
  18177. // Bounding boxes
  18178. this._boundingBoxRenderer.render();
  18179. // Edges
  18180. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18181. this._edgesRenderers.data[edgesRendererIndex].render();
  18182. }
  18183. // Lens flares
  18184. if (this.lensFlaresEnabled) {
  18185. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18186. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18187. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18188. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18189. lensFlareSystem.render();
  18190. }
  18191. }
  18192. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18193. }
  18194. // Foregrounds
  18195. if (this.layers.length) {
  18196. engine.setDepthBuffer(false);
  18197. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18198. layer = this.layers[layerIndex];
  18199. if (!layer.isBackground) {
  18200. layer.render();
  18201. }
  18202. }
  18203. engine.setDepthBuffer(true);
  18204. }
  18205. // Highlight Layer
  18206. if (renderhighlights) {
  18207. engine.setDepthBuffer(false);
  18208. for (var i = 0; i < this.highlightLayers.length; i++) {
  18209. if (this.highlightLayers[i].shouldRender()) {
  18210. this.highlightLayers[i].render();
  18211. }
  18212. }
  18213. engine.setDepthBuffer(true);
  18214. }
  18215. this._renderDuration.endMonitoring(false);
  18216. // Finalize frame
  18217. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18218. // Update camera
  18219. this.activeCamera._updateFromScene();
  18220. // Reset some special arrays
  18221. this._renderTargets.reset();
  18222. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18223. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18224. };
  18225. Scene.prototype._processSubCameras = function (camera) {
  18226. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18227. this._renderForCamera(camera);
  18228. return;
  18229. }
  18230. // rig cameras
  18231. for (var index = 0; index < camera._rigCameras.length; index++) {
  18232. this._renderForCamera(camera._rigCameras[index]);
  18233. }
  18234. this.activeCamera = camera;
  18235. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18236. // Update camera
  18237. this.activeCamera._updateFromScene();
  18238. };
  18239. Scene.prototype._checkIntersections = function () {
  18240. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18241. var sourceMesh = this._meshesForIntersections.data[index];
  18242. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18243. var action = sourceMesh.actionManager.actions[actionIndex];
  18244. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18245. var parameters = action.getTriggerParameter();
  18246. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18247. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18248. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18249. if (areIntersecting && currentIntersectionInProgress === -1) {
  18250. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18251. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18252. sourceMesh._intersectionsInProgress.push(otherMesh);
  18253. }
  18254. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18255. sourceMesh._intersectionsInProgress.push(otherMesh);
  18256. }
  18257. }
  18258. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18259. //They intersected, and now they don't.
  18260. //is this trigger an exit trigger? execute an event.
  18261. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18262. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18263. }
  18264. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18265. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18266. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18267. }
  18268. }
  18269. }
  18270. }
  18271. }
  18272. };
  18273. Scene.prototype.render = function () {
  18274. this._lastFrameDuration.beginMonitoring();
  18275. this._particlesDuration.fetchNewFrame();
  18276. this._spritesDuration.fetchNewFrame();
  18277. this._activeParticles.fetchNewFrame();
  18278. this._renderDuration.fetchNewFrame();
  18279. this._renderTargetsDuration.fetchNewFrame();
  18280. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18281. this._totalVertices.fetchNewFrame();
  18282. this._activeIndices.fetchNewFrame();
  18283. this._activeBones.fetchNewFrame();
  18284. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18285. this._meshesForIntersections.reset();
  18286. this.resetCachedMaterial();
  18287. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18288. // Actions
  18289. if (this.actionManager) {
  18290. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18291. }
  18292. //Simplification Queue
  18293. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18294. this.simplificationQueue.executeNext();
  18295. }
  18296. // Animations
  18297. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18298. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18299. this._animate();
  18300. // Physics
  18301. if (this._physicsEngine) {
  18302. BABYLON.Tools.StartPerformanceCounter("Physics");
  18303. this._physicsEngine._step(deltaTime / 1000.0);
  18304. BABYLON.Tools.EndPerformanceCounter("Physics");
  18305. }
  18306. // Before render
  18307. this.onBeforeRenderObservable.notifyObservers(this);
  18308. // Customs render targets
  18309. this._renderTargetsDuration.beginMonitoring();
  18310. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18311. var engine = this.getEngine();
  18312. var currentActiveCamera = this.activeCamera;
  18313. if (this.renderTargetsEnabled) {
  18314. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18315. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18316. var renderTarget = this.customRenderTargets[customIndex];
  18317. if (renderTarget._shouldRender()) {
  18318. this._renderId++;
  18319. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18320. if (!this.activeCamera)
  18321. throw new Error("Active camera not set");
  18322. // Viewport
  18323. engine.setViewport(this.activeCamera.viewport);
  18324. // Camera
  18325. this.updateTransformMatrix();
  18326. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18327. }
  18328. }
  18329. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18330. this._renderId++;
  18331. }
  18332. if (this.customRenderTargets.length > 0) {
  18333. engine.restoreDefaultFramebuffer();
  18334. }
  18335. this._renderTargetsDuration.endMonitoring();
  18336. this.activeCamera = currentActiveCamera;
  18337. // Procedural textures
  18338. if (this.proceduralTexturesEnabled) {
  18339. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18340. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18341. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18342. if (proceduralTexture._shouldRender()) {
  18343. proceduralTexture.render();
  18344. }
  18345. }
  18346. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18347. }
  18348. // Clear
  18349. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  18350. // Shadows
  18351. if (this.shadowsEnabled) {
  18352. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18353. var light = this.lights[lightIndex];
  18354. var shadowGenerator = light.getShadowGenerator();
  18355. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  18356. this._renderTargets.push(shadowGenerator.getShadowMap());
  18357. }
  18358. }
  18359. }
  18360. // Depth renderer
  18361. if (this._depthRenderer) {
  18362. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18363. }
  18364. // RenderPipeline
  18365. this.postProcessRenderPipelineManager.update();
  18366. // Multi-cameras?
  18367. if (this.activeCameras.length > 0) {
  18368. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18369. if (cameraIndex > 0) {
  18370. this._engine.clear(0, false, true, true);
  18371. }
  18372. this._processSubCameras(this.activeCameras[cameraIndex]);
  18373. }
  18374. }
  18375. else {
  18376. if (!this.activeCamera) {
  18377. throw new Error("No camera defined");
  18378. }
  18379. this._processSubCameras(this.activeCamera);
  18380. }
  18381. // Intersection checks
  18382. this._checkIntersections();
  18383. // Update the audio listener attached to the camera
  18384. if (BABYLON.AudioEngine) {
  18385. this._updateAudioParameters();
  18386. }
  18387. // After render
  18388. if (this.afterRender) {
  18389. this.afterRender();
  18390. }
  18391. this.onAfterRenderObservable.notifyObservers(this);
  18392. // Cleaning
  18393. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18394. this._toBeDisposed.data[index].dispose();
  18395. this._toBeDisposed[index] = null;
  18396. }
  18397. this._toBeDisposed.reset();
  18398. if (this.dumpNextRenderTargets) {
  18399. this.dumpNextRenderTargets = false;
  18400. }
  18401. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18402. this._lastFrameDuration.endMonitoring();
  18403. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18404. this._totalLightsCounter.addCount(this.lights.length, true);
  18405. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18406. this._totalTexturesCounter.addCount(this.textures.length, true);
  18407. this._activeBones.addCount(0, true);
  18408. this._activeIndices.addCount(0, true);
  18409. this._activeParticles.addCount(0, true);
  18410. };
  18411. Scene.prototype._updateAudioParameters = function () {
  18412. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18413. return;
  18414. }
  18415. var listeningCamera;
  18416. var audioEngine = BABYLON.Engine.audioEngine;
  18417. if (this.activeCameras.length > 0) {
  18418. listeningCamera = this.activeCameras[0];
  18419. }
  18420. else {
  18421. listeningCamera = this.activeCamera;
  18422. }
  18423. if (listeningCamera && audioEngine.canUseWebAudio) {
  18424. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18425. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18426. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18427. cameraDirection.normalize();
  18428. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18429. var i;
  18430. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18431. var sound = this.mainSoundTrack.soundCollection[i];
  18432. if (sound.useCustomAttenuation) {
  18433. sound.updateDistanceFromListener();
  18434. }
  18435. }
  18436. for (i = 0; i < this.soundTracks.length; i++) {
  18437. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18438. sound = this.soundTracks[i].soundCollection[j];
  18439. if (sound.useCustomAttenuation) {
  18440. sound.updateDistanceFromListener();
  18441. }
  18442. }
  18443. }
  18444. }
  18445. };
  18446. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18447. // Audio
  18448. get: function () {
  18449. return this._audioEnabled;
  18450. },
  18451. set: function (value) {
  18452. this._audioEnabled = value;
  18453. if (BABYLON.AudioEngine) {
  18454. if (this._audioEnabled) {
  18455. this._enableAudio();
  18456. }
  18457. else {
  18458. this._disableAudio();
  18459. }
  18460. }
  18461. },
  18462. enumerable: true,
  18463. configurable: true
  18464. });
  18465. Scene.prototype._disableAudio = function () {
  18466. var i;
  18467. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18468. this.mainSoundTrack.soundCollection[i].pause();
  18469. }
  18470. for (i = 0; i < this.soundTracks.length; i++) {
  18471. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18472. this.soundTracks[i].soundCollection[j].pause();
  18473. }
  18474. }
  18475. };
  18476. Scene.prototype._enableAudio = function () {
  18477. var i;
  18478. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18479. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18480. this.mainSoundTrack.soundCollection[i].play();
  18481. }
  18482. }
  18483. for (i = 0; i < this.soundTracks.length; i++) {
  18484. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18485. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18486. this.soundTracks[i].soundCollection[j].play();
  18487. }
  18488. }
  18489. }
  18490. };
  18491. Object.defineProperty(Scene.prototype, "headphone", {
  18492. get: function () {
  18493. return this._headphone;
  18494. },
  18495. set: function (value) {
  18496. this._headphone = value;
  18497. if (BABYLON.AudioEngine) {
  18498. if (this._headphone) {
  18499. this._switchAudioModeForHeadphones();
  18500. }
  18501. else {
  18502. this._switchAudioModeForNormalSpeakers();
  18503. }
  18504. }
  18505. },
  18506. enumerable: true,
  18507. configurable: true
  18508. });
  18509. Scene.prototype._switchAudioModeForHeadphones = function () {
  18510. this.mainSoundTrack.switchPanningModelToHRTF();
  18511. for (var i = 0; i < this.soundTracks.length; i++) {
  18512. this.soundTracks[i].switchPanningModelToHRTF();
  18513. }
  18514. };
  18515. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18516. this.mainSoundTrack.switchPanningModelToEqualPower();
  18517. for (var i = 0; i < this.soundTracks.length; i++) {
  18518. this.soundTracks[i].switchPanningModelToEqualPower();
  18519. }
  18520. };
  18521. Scene.prototype.enableDepthRenderer = function () {
  18522. if (this._depthRenderer) {
  18523. return this._depthRenderer;
  18524. }
  18525. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18526. return this._depthRenderer;
  18527. };
  18528. Scene.prototype.disableDepthRenderer = function () {
  18529. if (!this._depthRenderer) {
  18530. return;
  18531. }
  18532. this._depthRenderer.dispose();
  18533. this._depthRenderer = null;
  18534. };
  18535. Scene.prototype.freezeMaterials = function () {
  18536. for (var i = 0; i < this.materials.length; i++) {
  18537. this.materials[i].freeze();
  18538. }
  18539. };
  18540. Scene.prototype.unfreezeMaterials = function () {
  18541. for (var i = 0; i < this.materials.length; i++) {
  18542. this.materials[i].unfreeze();
  18543. }
  18544. };
  18545. Scene.prototype.dispose = function () {
  18546. this.beforeRender = null;
  18547. this.afterRender = null;
  18548. this.skeletons = [];
  18549. this._boundingBoxRenderer.dispose();
  18550. if (this._depthRenderer) {
  18551. this._depthRenderer.dispose();
  18552. }
  18553. // Debug layer
  18554. if (this._debugLayer) {
  18555. this._debugLayer.hide();
  18556. }
  18557. // Events
  18558. this.onDisposeObservable.notifyObservers(this);
  18559. this.onDisposeObservable.clear();
  18560. this.onBeforeRenderObservable.clear();
  18561. this.onAfterRenderObservable.clear();
  18562. this.detachControl();
  18563. // Release sounds & sounds tracks
  18564. if (BABYLON.AudioEngine) {
  18565. this.disposeSounds();
  18566. }
  18567. // Detach cameras
  18568. var canvas = this._engine.getRenderingCanvas();
  18569. var index;
  18570. for (index = 0; index < this.cameras.length; index++) {
  18571. this.cameras[index].detachControl(canvas);
  18572. }
  18573. // Release lights
  18574. while (this.lights.length) {
  18575. this.lights[0].dispose();
  18576. }
  18577. // Release meshes
  18578. while (this.meshes.length) {
  18579. this.meshes[0].dispose(true);
  18580. }
  18581. // Release cameras
  18582. while (this.cameras.length) {
  18583. this.cameras[0].dispose();
  18584. }
  18585. // Release materials
  18586. while (this.materials.length) {
  18587. this.materials[0].dispose();
  18588. }
  18589. // Release particles
  18590. while (this.particleSystems.length) {
  18591. this.particleSystems[0].dispose();
  18592. }
  18593. // Release sprites
  18594. while (this.spriteManagers.length) {
  18595. this.spriteManagers[0].dispose();
  18596. }
  18597. // Release layers
  18598. while (this.layers.length) {
  18599. this.layers[0].dispose();
  18600. }
  18601. while (this.highlightLayers.length) {
  18602. this.highlightLayers[0].dispose();
  18603. }
  18604. // Release textures
  18605. while (this.textures.length) {
  18606. this.textures[0].dispose();
  18607. }
  18608. // Post-processes
  18609. this.postProcessManager.dispose();
  18610. // Physics
  18611. if (this._physicsEngine) {
  18612. this.disablePhysicsEngine();
  18613. }
  18614. // Remove from engine
  18615. index = this._engine.scenes.indexOf(this);
  18616. if (index > -1) {
  18617. this._engine.scenes.splice(index, 1);
  18618. }
  18619. this._engine.wipeCaches();
  18620. };
  18621. // Release sounds & sounds tracks
  18622. Scene.prototype.disposeSounds = function () {
  18623. this.mainSoundTrack.dispose();
  18624. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18625. this.soundTracks[scIndex].dispose();
  18626. }
  18627. };
  18628. // Octrees
  18629. Scene.prototype.getWorldExtends = function () {
  18630. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18631. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18632. for (var index = 0; index < this.meshes.length; index++) {
  18633. var mesh = this.meshes[index];
  18634. mesh.computeWorldMatrix(true);
  18635. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18636. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18637. BABYLON.Tools.CheckExtends(minBox, min, max);
  18638. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18639. }
  18640. return {
  18641. min: min,
  18642. max: max
  18643. };
  18644. };
  18645. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18646. if (maxCapacity === void 0) { maxCapacity = 64; }
  18647. if (maxDepth === void 0) { maxDepth = 2; }
  18648. if (!this._selectionOctree) {
  18649. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18650. }
  18651. var worldExtends = this.getWorldExtends();
  18652. // Update octree
  18653. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18654. return this._selectionOctree;
  18655. };
  18656. // Picking
  18657. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18658. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18659. var engine = this._engine;
  18660. if (!camera) {
  18661. if (!this.activeCamera)
  18662. throw new Error("Active camera not set");
  18663. camera = this.activeCamera;
  18664. }
  18665. var cameraViewport = camera.viewport;
  18666. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18667. // Moving coordinates to local viewport world
  18668. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18669. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18670. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18671. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18672. };
  18673. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18674. var engine = this._engine;
  18675. if (!camera) {
  18676. if (!this.activeCamera)
  18677. throw new Error("Active camera not set");
  18678. camera = this.activeCamera;
  18679. }
  18680. var cameraViewport = camera.viewport;
  18681. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18682. var identity = BABYLON.Matrix.Identity();
  18683. // Moving coordinates to local viewport world
  18684. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18685. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18686. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18687. };
  18688. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18689. var pickingInfo = null;
  18690. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18691. var mesh = this.meshes[meshIndex];
  18692. if (predicate) {
  18693. if (!predicate(mesh)) {
  18694. continue;
  18695. }
  18696. }
  18697. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18698. continue;
  18699. }
  18700. var world = mesh.getWorldMatrix();
  18701. var ray = rayFunction(world);
  18702. var result = mesh.intersects(ray, fastCheck);
  18703. if (!result || !result.hit)
  18704. continue;
  18705. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18706. continue;
  18707. pickingInfo = result;
  18708. if (fastCheck) {
  18709. break;
  18710. }
  18711. }
  18712. return pickingInfo || new BABYLON.PickingInfo();
  18713. };
  18714. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18715. var pickingInfos = new Array();
  18716. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18717. var mesh = this.meshes[meshIndex];
  18718. if (predicate) {
  18719. if (!predicate(mesh)) {
  18720. continue;
  18721. }
  18722. }
  18723. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18724. continue;
  18725. }
  18726. var world = mesh.getWorldMatrix();
  18727. var ray = rayFunction(world);
  18728. var result = mesh.intersects(ray, false);
  18729. if (!result || !result.hit)
  18730. continue;
  18731. pickingInfos.push(result);
  18732. }
  18733. return pickingInfos;
  18734. };
  18735. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18736. var pickingInfo = null;
  18737. camera = camera || this.activeCamera;
  18738. if (this.spriteManagers.length > 0) {
  18739. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18740. var spriteManager = this.spriteManagers[spriteIndex];
  18741. if (!spriteManager.isPickable) {
  18742. continue;
  18743. }
  18744. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18745. if (!result || !result.hit)
  18746. continue;
  18747. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18748. continue;
  18749. pickingInfo = result;
  18750. if (fastCheck) {
  18751. break;
  18752. }
  18753. }
  18754. }
  18755. return pickingInfo || new BABYLON.PickingInfo();
  18756. };
  18757. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18758. /// <param name="x">X position on screen</param>
  18759. /// <param name="y">Y position on screen</param>
  18760. /// <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>
  18761. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18762. /// <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>
  18763. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18764. var _this = this;
  18765. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18766. };
  18767. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18768. /// <param name="x">X position on screen</param>
  18769. /// <param name="y">Y position on screen</param>
  18770. /// <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>
  18771. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18772. /// <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>
  18773. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18774. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18775. };
  18776. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18777. var _this = this;
  18778. return this._internalPick(function (world) {
  18779. if (!_this._pickWithRayInverseMatrix) {
  18780. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18781. }
  18782. world.invertToRef(_this._pickWithRayInverseMatrix);
  18783. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18784. }, predicate, fastCheck);
  18785. };
  18786. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18787. /// <param name="x">X position on screen</param>
  18788. /// <param name="y">Y position on screen</param>
  18789. /// <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>
  18790. /// <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>
  18791. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18792. var _this = this;
  18793. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18794. };
  18795. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18796. /// <param name="ray">Ray to use</param>
  18797. /// <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>
  18798. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18799. var _this = this;
  18800. return this._internalMultiPick(function (world) {
  18801. if (!_this._pickWithRayInverseMatrix) {
  18802. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18803. }
  18804. world.invertToRef(_this._pickWithRayInverseMatrix);
  18805. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18806. }, predicate);
  18807. };
  18808. Scene.prototype.setPointerOverMesh = function (mesh) {
  18809. if (this._pointerOverMesh === mesh) {
  18810. return;
  18811. }
  18812. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18813. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18814. }
  18815. this._pointerOverMesh = mesh;
  18816. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18817. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18818. }
  18819. };
  18820. Scene.prototype.getPointerOverMesh = function () {
  18821. return this._pointerOverMesh;
  18822. };
  18823. Scene.prototype.setPointerOverSprite = function (sprite) {
  18824. if (this._pointerOverSprite === sprite) {
  18825. return;
  18826. }
  18827. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18828. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18829. }
  18830. this._pointerOverSprite = sprite;
  18831. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18832. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18833. }
  18834. };
  18835. Scene.prototype.getPointerOverSprite = function () {
  18836. return this._pointerOverSprite;
  18837. };
  18838. // Physics
  18839. Scene.prototype.getPhysicsEngine = function () {
  18840. return this._physicsEngine;
  18841. };
  18842. /**
  18843. * Enables physics to the current scene
  18844. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18845. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18846. * @return {boolean} was the physics engine initialized
  18847. */
  18848. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18849. if (this._physicsEngine) {
  18850. return true;
  18851. }
  18852. try {
  18853. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18854. return true;
  18855. }
  18856. catch (e) {
  18857. BABYLON.Tools.Error(e.message);
  18858. return false;
  18859. }
  18860. };
  18861. Scene.prototype.disablePhysicsEngine = function () {
  18862. if (!this._physicsEngine) {
  18863. return;
  18864. }
  18865. this._physicsEngine.dispose();
  18866. this._physicsEngine = undefined;
  18867. };
  18868. Scene.prototype.isPhysicsEnabled = function () {
  18869. return this._physicsEngine !== undefined;
  18870. };
  18871. /**
  18872. *
  18873. * Sets the gravity of the physics engine (and NOT of the scene)
  18874. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  18875. */
  18876. Scene.prototype.setGravity = function (gravity) {
  18877. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  18878. if (!this._physicsEngine) {
  18879. return;
  18880. }
  18881. this._physicsEngine.setGravity(gravity);
  18882. };
  18883. /**
  18884. * Legacy support, using the new API
  18885. * @Deprecated
  18886. */
  18887. Scene.prototype.createCompoundImpostor = function (parts, options) {
  18888. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  18889. if (parts.parts) {
  18890. options = parts;
  18891. parts = parts.parts;
  18892. }
  18893. var mainMesh = parts[0].mesh;
  18894. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  18895. for (var index = 1; index < parts.length; index++) {
  18896. var mesh = parts[index].mesh;
  18897. if (mesh.parent !== mainMesh) {
  18898. mesh.position = mesh.position.subtract(mainMesh.position);
  18899. mesh.parent = mainMesh;
  18900. }
  18901. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  18902. }
  18903. mainMesh.physicsImpostor.forceUpdate();
  18904. };
  18905. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18906. var mesh = compound.parts[0].mesh;
  18907. mesh.physicsImpostor.dispose();
  18908. mesh.physicsImpostor = null;
  18909. };
  18910. // Misc.
  18911. Scene.prototype.createDefaultCameraOrLight = function () {
  18912. // Light
  18913. if (this.lights.length === 0) {
  18914. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18915. }
  18916. // Camera
  18917. if (!this.activeCamera) {
  18918. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  18919. // Compute position
  18920. var worldExtends = this.getWorldExtends();
  18921. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  18922. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  18923. camera.setTarget(worldCenter);
  18924. this.activeCamera = camera;
  18925. }
  18926. };
  18927. // Tags
  18928. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18929. if (tagsQuery === undefined) {
  18930. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18931. return list;
  18932. }
  18933. var listByTags = [];
  18934. forEach = forEach || (function (item) { return; });
  18935. for (var i in list) {
  18936. var item = list[i];
  18937. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18938. listByTags.push(item);
  18939. forEach(item);
  18940. }
  18941. }
  18942. return listByTags;
  18943. };
  18944. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18945. return this._getByTags(this.meshes, tagsQuery, forEach);
  18946. };
  18947. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18948. return this._getByTags(this.cameras, tagsQuery, forEach);
  18949. };
  18950. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18951. return this._getByTags(this.lights, tagsQuery, forEach);
  18952. };
  18953. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18954. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18955. };
  18956. /**
  18957. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18958. * This allowed control for front to back rendering or reversly depending of the special needs.
  18959. *
  18960. * @param renderingGroupId The rendering group id corresponding to its index
  18961. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18962. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18963. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18964. */
  18965. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18966. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18967. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18968. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18969. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18970. };
  18971. /**
  18972. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18973. *
  18974. * @param renderingGroupId The rendering group id corresponding to its index
  18975. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18976. */
  18977. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  18978. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  18979. };
  18980. // Statics
  18981. Scene._FOGMODE_NONE = 0;
  18982. Scene._FOGMODE_EXP = 1;
  18983. Scene._FOGMODE_EXP2 = 2;
  18984. Scene._FOGMODE_LINEAR = 3;
  18985. Scene.MinDeltaTime = 1.0;
  18986. Scene.MaxDeltaTime = 1000.0;
  18987. return Scene;
  18988. }());
  18989. BABYLON.Scene = Scene;
  18990. })(BABYLON || (BABYLON = {}));
  18991. //# sourceMappingURL=babylon.scene.js.map
  18992. var BABYLON;
  18993. (function (BABYLON) {
  18994. var Buffer = (function () {
  18995. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18996. if (engine instanceof BABYLON.Mesh) {
  18997. this._engine = engine.getScene().getEngine();
  18998. }
  18999. else {
  19000. this._engine = engine;
  19001. }
  19002. this._updatable = updatable;
  19003. this._data = data;
  19004. this._strideSize = stride;
  19005. if (!postponeInternalCreation) {
  19006. this.create();
  19007. }
  19008. this._instanced = instanced;
  19009. }
  19010. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19011. // a lot of these parameters are ignored as they are overriden by the buffer
  19012. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19013. };
  19014. // Properties
  19015. Buffer.prototype.isUpdatable = function () {
  19016. return this._updatable;
  19017. };
  19018. Buffer.prototype.getData = function () {
  19019. return this._data;
  19020. };
  19021. Buffer.prototype.getBuffer = function () {
  19022. return this._buffer;
  19023. };
  19024. Buffer.prototype.getStrideSize = function () {
  19025. return this._strideSize;
  19026. };
  19027. Buffer.prototype.getIsInstanced = function () {
  19028. return this._instanced;
  19029. };
  19030. // Methods
  19031. Buffer.prototype.create = function (data) {
  19032. if (!data && this._buffer) {
  19033. return; // nothing to do
  19034. }
  19035. data = data || this._data;
  19036. if (!this._buffer) {
  19037. if (this._updatable) {
  19038. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19039. this._data = data;
  19040. }
  19041. else {
  19042. this._buffer = this._engine.createVertexBuffer(data);
  19043. }
  19044. }
  19045. else if (this._updatable) {
  19046. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19047. this._data = data;
  19048. }
  19049. };
  19050. Buffer.prototype.update = function (data) {
  19051. this.create(data);
  19052. };
  19053. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19054. if (!this._buffer) {
  19055. return;
  19056. }
  19057. if (this._updatable) {
  19058. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19059. this._data = null;
  19060. }
  19061. };
  19062. Buffer.prototype.dispose = function () {
  19063. if (!this._buffer) {
  19064. return;
  19065. }
  19066. if (this._engine._releaseBuffer(this._buffer)) {
  19067. this._buffer = null;
  19068. }
  19069. };
  19070. return Buffer;
  19071. }());
  19072. BABYLON.Buffer = Buffer;
  19073. })(BABYLON || (BABYLON = {}));
  19074. //# sourceMappingURL=../Mesh/babylon.buffer.js.map
  19075. var BABYLON;
  19076. (function (BABYLON) {
  19077. var VertexBuffer = (function () {
  19078. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19079. if (!stride) {
  19080. // Deduce stride from kind
  19081. switch (kind) {
  19082. case VertexBuffer.PositionKind:
  19083. stride = 3;
  19084. break;
  19085. case VertexBuffer.NormalKind:
  19086. stride = 3;
  19087. break;
  19088. case VertexBuffer.UVKind:
  19089. case VertexBuffer.UV2Kind:
  19090. case VertexBuffer.UV3Kind:
  19091. case VertexBuffer.UV4Kind:
  19092. case VertexBuffer.UV5Kind:
  19093. case VertexBuffer.UV6Kind:
  19094. stride = 2;
  19095. break;
  19096. case VertexBuffer.ColorKind:
  19097. stride = 4;
  19098. break;
  19099. case VertexBuffer.MatricesIndicesKind:
  19100. case VertexBuffer.MatricesIndicesExtraKind:
  19101. stride = 4;
  19102. break;
  19103. case VertexBuffer.MatricesWeightsKind:
  19104. case VertexBuffer.MatricesWeightsExtraKind:
  19105. stride = 4;
  19106. break;
  19107. }
  19108. }
  19109. if (data instanceof BABYLON.Buffer) {
  19110. if (!stride) {
  19111. stride = data.getStrideSize();
  19112. }
  19113. this._buffer = data;
  19114. this._ownsBuffer = false;
  19115. }
  19116. else {
  19117. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19118. this._ownsBuffer = true;
  19119. }
  19120. this._stride = stride;
  19121. this._offset = offset ? offset : 0;
  19122. this._size = size ? size : stride;
  19123. this._kind = kind;
  19124. }
  19125. VertexBuffer.prototype.getKind = function () {
  19126. return this._kind;
  19127. };
  19128. // Properties
  19129. VertexBuffer.prototype.isUpdatable = function () {
  19130. return this._buffer.isUpdatable();
  19131. };
  19132. VertexBuffer.prototype.getData = function () {
  19133. return this._buffer.getData();
  19134. };
  19135. VertexBuffer.prototype.getBuffer = function () {
  19136. return this._buffer.getBuffer();
  19137. };
  19138. VertexBuffer.prototype.getStrideSize = function () {
  19139. return this._stride;
  19140. };
  19141. VertexBuffer.prototype.getOffset = function () {
  19142. return this._offset;
  19143. };
  19144. VertexBuffer.prototype.getSize = function () {
  19145. return this._size;
  19146. };
  19147. VertexBuffer.prototype.getIsInstanced = function () {
  19148. return this._buffer.getIsInstanced();
  19149. };
  19150. // Methods
  19151. VertexBuffer.prototype.create = function (data) {
  19152. return this._buffer.create(data);
  19153. };
  19154. VertexBuffer.prototype.update = function (data) {
  19155. return this._buffer.update(data);
  19156. };
  19157. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19158. return this._buffer.updateDirectly(data, offset);
  19159. };
  19160. VertexBuffer.prototype.dispose = function () {
  19161. if (this._ownsBuffer) {
  19162. this._buffer.dispose();
  19163. }
  19164. };
  19165. Object.defineProperty(VertexBuffer, "PositionKind", {
  19166. get: function () {
  19167. return VertexBuffer._PositionKind;
  19168. },
  19169. enumerable: true,
  19170. configurable: true
  19171. });
  19172. Object.defineProperty(VertexBuffer, "NormalKind", {
  19173. get: function () {
  19174. return VertexBuffer._NormalKind;
  19175. },
  19176. enumerable: true,
  19177. configurable: true
  19178. });
  19179. Object.defineProperty(VertexBuffer, "UVKind", {
  19180. get: function () {
  19181. return VertexBuffer._UVKind;
  19182. },
  19183. enumerable: true,
  19184. configurable: true
  19185. });
  19186. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19187. get: function () {
  19188. return VertexBuffer._UV2Kind;
  19189. },
  19190. enumerable: true,
  19191. configurable: true
  19192. });
  19193. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19194. get: function () {
  19195. return VertexBuffer._UV3Kind;
  19196. },
  19197. enumerable: true,
  19198. configurable: true
  19199. });
  19200. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19201. get: function () {
  19202. return VertexBuffer._UV4Kind;
  19203. },
  19204. enumerable: true,
  19205. configurable: true
  19206. });
  19207. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19208. get: function () {
  19209. return VertexBuffer._UV5Kind;
  19210. },
  19211. enumerable: true,
  19212. configurable: true
  19213. });
  19214. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19215. get: function () {
  19216. return VertexBuffer._UV6Kind;
  19217. },
  19218. enumerable: true,
  19219. configurable: true
  19220. });
  19221. Object.defineProperty(VertexBuffer, "ColorKind", {
  19222. get: function () {
  19223. return VertexBuffer._ColorKind;
  19224. },
  19225. enumerable: true,
  19226. configurable: true
  19227. });
  19228. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19229. get: function () {
  19230. return VertexBuffer._MatricesIndicesKind;
  19231. },
  19232. enumerable: true,
  19233. configurable: true
  19234. });
  19235. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19236. get: function () {
  19237. return VertexBuffer._MatricesWeightsKind;
  19238. },
  19239. enumerable: true,
  19240. configurable: true
  19241. });
  19242. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19243. get: function () {
  19244. return VertexBuffer._MatricesIndicesExtraKind;
  19245. },
  19246. enumerable: true,
  19247. configurable: true
  19248. });
  19249. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19250. get: function () {
  19251. return VertexBuffer._MatricesWeightsExtraKind;
  19252. },
  19253. enumerable: true,
  19254. configurable: true
  19255. });
  19256. // Enums
  19257. VertexBuffer._PositionKind = "position";
  19258. VertexBuffer._NormalKind = "normal";
  19259. VertexBuffer._UVKind = "uv";
  19260. VertexBuffer._UV2Kind = "uv2";
  19261. VertexBuffer._UV3Kind = "uv3";
  19262. VertexBuffer._UV4Kind = "uv4";
  19263. VertexBuffer._UV5Kind = "uv5";
  19264. VertexBuffer._UV6Kind = "uv6";
  19265. VertexBuffer._ColorKind = "color";
  19266. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19267. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19268. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19269. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19270. return VertexBuffer;
  19271. }());
  19272. BABYLON.VertexBuffer = VertexBuffer;
  19273. })(BABYLON || (BABYLON = {}));
  19274. //# sourceMappingURL=../Mesh/babylon.vertexBuffer.js.map
  19275. var BABYLON;
  19276. (function (BABYLON) {
  19277. /**
  19278. * Creates an instance based on a source mesh.
  19279. */
  19280. var InstancedMesh = (function (_super) {
  19281. __extends(InstancedMesh, _super);
  19282. function InstancedMesh(name, source) {
  19283. _super.call(this, name, source.getScene());
  19284. source.instances.push(this);
  19285. this._sourceMesh = source;
  19286. this.position.copyFrom(source.position);
  19287. this.rotation.copyFrom(source.rotation);
  19288. this.scaling.copyFrom(source.scaling);
  19289. if (source.rotationQuaternion) {
  19290. this.rotationQuaternion = source.rotationQuaternion.clone();
  19291. }
  19292. this.infiniteDistance = source.infiniteDistance;
  19293. this.setPivotMatrix(source.getPivotMatrix());
  19294. this.refreshBoundingInfo();
  19295. this._syncSubMeshes();
  19296. }
  19297. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  19298. // Methods
  19299. get: function () {
  19300. return this._sourceMesh.receiveShadows;
  19301. },
  19302. enumerable: true,
  19303. configurable: true
  19304. });
  19305. Object.defineProperty(InstancedMesh.prototype, "material", {
  19306. get: function () {
  19307. return this._sourceMesh.material;
  19308. },
  19309. enumerable: true,
  19310. configurable: true
  19311. });
  19312. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  19313. get: function () {
  19314. return this._sourceMesh.visibility;
  19315. },
  19316. enumerable: true,
  19317. configurable: true
  19318. });
  19319. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  19320. get: function () {
  19321. return this._sourceMesh.skeleton;
  19322. },
  19323. enumerable: true,
  19324. configurable: true
  19325. });
  19326. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  19327. get: function () {
  19328. return this._sourceMesh.renderingGroupId;
  19329. },
  19330. enumerable: true,
  19331. configurable: true
  19332. });
  19333. InstancedMesh.prototype.getTotalVertices = function () {
  19334. return this._sourceMesh.getTotalVertices();
  19335. };
  19336. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  19337. get: function () {
  19338. return this._sourceMesh;
  19339. },
  19340. enumerable: true,
  19341. configurable: true
  19342. });
  19343. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19344. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  19345. };
  19346. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  19347. return this._sourceMesh.isVerticesDataPresent(kind);
  19348. };
  19349. InstancedMesh.prototype.getIndices = function () {
  19350. return this._sourceMesh.getIndices();
  19351. };
  19352. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  19353. get: function () {
  19354. return this._sourceMesh._positions;
  19355. },
  19356. enumerable: true,
  19357. configurable: true
  19358. });
  19359. InstancedMesh.prototype.refreshBoundingInfo = function () {
  19360. var meshBB = this._sourceMesh.getBoundingInfo();
  19361. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  19362. this._updateBoundingInfo();
  19363. };
  19364. InstancedMesh.prototype._preActivate = function () {
  19365. if (this._currentLOD) {
  19366. this._currentLOD._preActivate();
  19367. }
  19368. };
  19369. InstancedMesh.prototype._activate = function (renderId) {
  19370. if (this._currentLOD) {
  19371. this._currentLOD._registerInstanceForRenderId(this, renderId);
  19372. }
  19373. };
  19374. InstancedMesh.prototype.getLOD = function (camera) {
  19375. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  19376. if (this._currentLOD === this.sourceMesh) {
  19377. return this;
  19378. }
  19379. return this._currentLOD;
  19380. };
  19381. InstancedMesh.prototype._syncSubMeshes = function () {
  19382. this.releaseSubMeshes();
  19383. if (this._sourceMesh.subMeshes) {
  19384. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  19385. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  19386. }
  19387. }
  19388. };
  19389. InstancedMesh.prototype._generatePointsArray = function () {
  19390. return this._sourceMesh._generatePointsArray();
  19391. };
  19392. // Clone
  19393. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19394. var result = this._sourceMesh.createInstance(name);
  19395. // Deep copy
  19396. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  19397. // Bounding info
  19398. this.refreshBoundingInfo();
  19399. // Parent
  19400. if (newParent) {
  19401. result.parent = newParent;
  19402. }
  19403. if (!doNotCloneChildren) {
  19404. // Children
  19405. for (var index = 0; index < this.getScene().meshes.length; index++) {
  19406. var mesh = this.getScene().meshes[index];
  19407. if (mesh.parent === this) {
  19408. mesh.clone(mesh.name, result);
  19409. }
  19410. }
  19411. }
  19412. result.computeWorldMatrix(true);
  19413. return result;
  19414. };
  19415. // Dispoe
  19416. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  19417. // Remove from mesh
  19418. var index = this._sourceMesh.instances.indexOf(this);
  19419. this._sourceMesh.instances.splice(index, 1);
  19420. _super.prototype.dispose.call(this, doNotRecurse);
  19421. };
  19422. return InstancedMesh;
  19423. }(BABYLON.AbstractMesh));
  19424. BABYLON.InstancedMesh = InstancedMesh;
  19425. })(BABYLON || (BABYLON = {}));
  19426. //# sourceMappingURL=../Mesh/babylon.instancedMesh.js.map
  19427. var BABYLON;
  19428. (function (BABYLON) {
  19429. var _InstancesBatch = (function () {
  19430. function _InstancesBatch() {
  19431. this.mustReturn = false;
  19432. this.visibleInstances = new Array();
  19433. this.renderSelf = new Array();
  19434. }
  19435. return _InstancesBatch;
  19436. }());
  19437. BABYLON._InstancesBatch = _InstancesBatch;
  19438. var Mesh = (function (_super) {
  19439. __extends(Mesh, _super);
  19440. /**
  19441. * @constructor
  19442. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19443. * @param {Scene} scene The scene to add this mesh to.
  19444. * @param {Node} parent The parent of this mesh, if it has one
  19445. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19446. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19447. * When false, achieved by calling a clone(), also passing False.
  19448. * This will make creation of children, recursive.
  19449. */
  19450. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19451. if (parent === void 0) { parent = null; }
  19452. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19453. _super.call(this, name, scene);
  19454. // Events
  19455. /**
  19456. * An event triggered before rendering the mesh
  19457. * @type {BABYLON.Observable}
  19458. */
  19459. this.onBeforeRenderObservable = new BABYLON.Observable();
  19460. /**
  19461. * An event triggered after rendering the mesh
  19462. * @type {BABYLON.Observable}
  19463. */
  19464. this.onAfterRenderObservable = new BABYLON.Observable();
  19465. /**
  19466. * An event triggered before drawing the mesh
  19467. * @type {BABYLON.Observable}
  19468. */
  19469. this.onBeforeDrawObservable = new BABYLON.Observable();
  19470. // Members
  19471. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19472. this.instances = new Array();
  19473. this._LODLevels = new Array();
  19474. this._visibleInstances = {};
  19475. this._renderIdForInstances = new Array();
  19476. this._batchCache = new _InstancesBatch();
  19477. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19478. this._sideOrientation = Mesh._DEFAULTSIDE;
  19479. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19480. if (source) {
  19481. // Geometry
  19482. if (source._geometry) {
  19483. source._geometry.applyToMesh(this);
  19484. }
  19485. // Deep copy
  19486. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
  19487. // Parent
  19488. this.parent = source.parent;
  19489. // Pivot
  19490. this.setPivotMatrix(source.getPivotMatrix());
  19491. this.id = name + "." + source.id;
  19492. // Material
  19493. this.material = source.material;
  19494. var index;
  19495. if (!doNotCloneChildren) {
  19496. // Children
  19497. for (index = 0; index < scene.meshes.length; index++) {
  19498. var mesh = scene.meshes[index];
  19499. if (mesh.parent === source) {
  19500. // doNotCloneChildren is always going to be False
  19501. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  19502. }
  19503. }
  19504. }
  19505. // Physics clone
  19506. var physicsEngine = this.getScene().getPhysicsEngine();
  19507. if (clonePhysicsImpostor && physicsEngine) {
  19508. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19509. if (impostor) {
  19510. this.physicsImpostor = impostor.clone(this);
  19511. }
  19512. }
  19513. // Particles
  19514. for (index = 0; index < scene.particleSystems.length; index++) {
  19515. var system = scene.particleSystems[index];
  19516. if (system.emitter === source) {
  19517. system.clone(system.name, this);
  19518. }
  19519. }
  19520. this.computeWorldMatrix(true);
  19521. }
  19522. // Parent
  19523. if (parent !== null) {
  19524. this.parent = parent;
  19525. }
  19526. }
  19527. Object.defineProperty(Mesh, "FRONTSIDE", {
  19528. /**
  19529. * Mesh side orientation : usually the external or front surface
  19530. */
  19531. get: function () {
  19532. return Mesh._FRONTSIDE;
  19533. },
  19534. enumerable: true,
  19535. configurable: true
  19536. });
  19537. Object.defineProperty(Mesh, "BACKSIDE", {
  19538. /**
  19539. * Mesh side orientation : usually the internal or back surface
  19540. */
  19541. get: function () {
  19542. return Mesh._BACKSIDE;
  19543. },
  19544. enumerable: true,
  19545. configurable: true
  19546. });
  19547. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19548. /**
  19549. * Mesh side orientation : both internal and external or front and back surfaces
  19550. */
  19551. get: function () {
  19552. return Mesh._DOUBLESIDE;
  19553. },
  19554. enumerable: true,
  19555. configurable: true
  19556. });
  19557. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19558. /**
  19559. * Mesh side orientation : by default, `FRONTSIDE`
  19560. */
  19561. get: function () {
  19562. return Mesh._DEFAULTSIDE;
  19563. },
  19564. enumerable: true,
  19565. configurable: true
  19566. });
  19567. Object.defineProperty(Mesh, "NO_CAP", {
  19568. /**
  19569. * Mesh cap setting : no cap
  19570. */
  19571. get: function () {
  19572. return Mesh._NO_CAP;
  19573. },
  19574. enumerable: true,
  19575. configurable: true
  19576. });
  19577. Object.defineProperty(Mesh, "CAP_START", {
  19578. /**
  19579. * Mesh cap setting : one cap at the beginning of the mesh
  19580. */
  19581. get: function () {
  19582. return Mesh._CAP_START;
  19583. },
  19584. enumerable: true,
  19585. configurable: true
  19586. });
  19587. Object.defineProperty(Mesh, "CAP_END", {
  19588. /**
  19589. * Mesh cap setting : one cap at the end of the mesh
  19590. */
  19591. get: function () {
  19592. return Mesh._CAP_END;
  19593. },
  19594. enumerable: true,
  19595. configurable: true
  19596. });
  19597. Object.defineProperty(Mesh, "CAP_ALL", {
  19598. /**
  19599. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19600. */
  19601. get: function () {
  19602. return Mesh._CAP_ALL;
  19603. },
  19604. enumerable: true,
  19605. configurable: true
  19606. });
  19607. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19608. set: function (callback) {
  19609. if (this._onBeforeDrawObserver) {
  19610. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19611. }
  19612. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19613. },
  19614. enumerable: true,
  19615. configurable: true
  19616. });
  19617. // Methods
  19618. /**
  19619. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19620. */
  19621. Mesh.prototype.toString = function (fullDetails) {
  19622. var ret = _super.prototype.toString.call(this, fullDetails);
  19623. ret += ", n vertices: " + this.getTotalVertices();
  19624. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19625. if (this.animations) {
  19626. for (var i = 0; i < this.animations.length; i++) {
  19627. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19628. }
  19629. }
  19630. if (fullDetails) {
  19631. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19632. }
  19633. return ret;
  19634. };
  19635. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19636. get: function () {
  19637. return this._LODLevels.length > 0;
  19638. },
  19639. enumerable: true,
  19640. configurable: true
  19641. });
  19642. Mesh.prototype._sortLODLevels = function () {
  19643. this._LODLevels.sort(function (a, b) {
  19644. if (a.distance < b.distance) {
  19645. return 1;
  19646. }
  19647. if (a.distance > b.distance) {
  19648. return -1;
  19649. }
  19650. return 0;
  19651. });
  19652. };
  19653. /**
  19654. * Add a mesh as LOD level triggered at the given distance.
  19655. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19656. * @param {number} distance The distance from the center of the object to show this level
  19657. * @param {Mesh} mesh The mesh to be added as LOD level
  19658. * @return {Mesh} This mesh (for chaining)
  19659. */
  19660. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19661. if (mesh && mesh._masterMesh) {
  19662. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19663. return this;
  19664. }
  19665. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19666. this._LODLevels.push(level);
  19667. if (mesh) {
  19668. mesh._masterMesh = this;
  19669. }
  19670. this._sortLODLevels();
  19671. return this;
  19672. };
  19673. /**
  19674. * Returns the LOD level mesh at the passed distance or null if not found.
  19675. * It is related to the method `addLODLevel(distance, mesh)`.
  19676. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19677. */
  19678. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19679. for (var index = 0; index < this._LODLevels.length; index++) {
  19680. var level = this._LODLevels[index];
  19681. if (level.distance === distance) {
  19682. return level.mesh;
  19683. }
  19684. }
  19685. return null;
  19686. };
  19687. /**
  19688. * Remove a mesh from the LOD array
  19689. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19690. * @param {Mesh} mesh The mesh to be removed.
  19691. * @return {Mesh} This mesh (for chaining)
  19692. */
  19693. Mesh.prototype.removeLODLevel = function (mesh) {
  19694. for (var index = 0; index < this._LODLevels.length; index++) {
  19695. if (this._LODLevels[index].mesh === mesh) {
  19696. this._LODLevels.splice(index, 1);
  19697. if (mesh) {
  19698. mesh._masterMesh = null;
  19699. }
  19700. }
  19701. }
  19702. this._sortLODLevels();
  19703. return this;
  19704. };
  19705. /**
  19706. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19707. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19708. */
  19709. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19710. if (!this._LODLevels || this._LODLevels.length === 0) {
  19711. return this;
  19712. }
  19713. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19714. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19715. if (this.onLODLevelSelection) {
  19716. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19717. }
  19718. return this;
  19719. }
  19720. for (var index = 0; index < this._LODLevels.length; index++) {
  19721. var level = this._LODLevels[index];
  19722. if (level.distance < distanceToCamera) {
  19723. if (level.mesh) {
  19724. level.mesh._preActivate();
  19725. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19726. }
  19727. if (this.onLODLevelSelection) {
  19728. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19729. }
  19730. return level.mesh;
  19731. }
  19732. }
  19733. if (this.onLODLevelSelection) {
  19734. this.onLODLevelSelection(distanceToCamera, this, this);
  19735. }
  19736. return this;
  19737. };
  19738. Object.defineProperty(Mesh.prototype, "geometry", {
  19739. /**
  19740. * Returns the mesh internal Geometry object.
  19741. */
  19742. get: function () {
  19743. return this._geometry;
  19744. },
  19745. enumerable: true,
  19746. configurable: true
  19747. });
  19748. /**
  19749. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19750. */
  19751. Mesh.prototype.getTotalVertices = function () {
  19752. if (!this._geometry) {
  19753. return 0;
  19754. }
  19755. return this._geometry.getTotalVertices();
  19756. };
  19757. /**
  19758. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19759. * 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.
  19760. * Returns null if the mesh has no geometry or no vertex buffer.
  19761. * Possible `kind` values :
  19762. * - BABYLON.VertexBuffer.PositionKind
  19763. * - BABYLON.VertexBuffer.UVKind
  19764. * - BABYLON.VertexBuffer.UV2Kind
  19765. * - BABYLON.VertexBuffer.UV3Kind
  19766. * - BABYLON.VertexBuffer.UV4Kind
  19767. * - BABYLON.VertexBuffer.UV5Kind
  19768. * - BABYLON.VertexBuffer.UV6Kind
  19769. * - BABYLON.VertexBuffer.ColorKind
  19770. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19771. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19772. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19773. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19774. */
  19775. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19776. if (!this._geometry) {
  19777. return null;
  19778. }
  19779. return this._geometry.getVerticesData(kind, copyWhenShared);
  19780. };
  19781. /**
  19782. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19783. * Returns `undefined` if the mesh has no geometry.
  19784. * Possible `kind` values :
  19785. * - BABYLON.VertexBuffer.PositionKind
  19786. * - BABYLON.VertexBuffer.UVKind
  19787. * - BABYLON.VertexBuffer.UV2Kind
  19788. * - BABYLON.VertexBuffer.UV3Kind
  19789. * - BABYLON.VertexBuffer.UV4Kind
  19790. * - BABYLON.VertexBuffer.UV5Kind
  19791. * - BABYLON.VertexBuffer.UV6Kind
  19792. * - BABYLON.VertexBuffer.ColorKind
  19793. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19794. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19795. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19796. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19797. */
  19798. Mesh.prototype.getVertexBuffer = function (kind) {
  19799. if (!this._geometry) {
  19800. return undefined;
  19801. }
  19802. return this._geometry.getVertexBuffer(kind);
  19803. };
  19804. /**
  19805. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19806. * Possible `kind` values :
  19807. * - BABYLON.VertexBuffer.PositionKind
  19808. * - BABYLON.VertexBuffer.UVKind
  19809. * - BABYLON.VertexBuffer.UV2Kind
  19810. * - BABYLON.VertexBuffer.UV3Kind
  19811. * - BABYLON.VertexBuffer.UV4Kind
  19812. * - BABYLON.VertexBuffer.UV5Kind
  19813. * - BABYLON.VertexBuffer.UV6Kind
  19814. * - BABYLON.VertexBuffer.ColorKind
  19815. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19816. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19817. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19818. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19819. */
  19820. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19821. if (!this._geometry) {
  19822. if (this._delayInfo) {
  19823. return this._delayInfo.indexOf(kind) !== -1;
  19824. }
  19825. return false;
  19826. }
  19827. return this._geometry.isVerticesDataPresent(kind);
  19828. };
  19829. /**
  19830. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19831. * Possible `kind` values :
  19832. * - BABYLON.VertexBuffer.PositionKind
  19833. * - BABYLON.VertexBuffer.UVKind
  19834. * - BABYLON.VertexBuffer.UV2Kind
  19835. * - BABYLON.VertexBuffer.UV3Kind
  19836. * - BABYLON.VertexBuffer.UV4Kind
  19837. * - BABYLON.VertexBuffer.UV5Kind
  19838. * - BABYLON.VertexBuffer.UV6Kind
  19839. * - BABYLON.VertexBuffer.ColorKind
  19840. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19841. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19842. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19843. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19844. */
  19845. Mesh.prototype.getVerticesDataKinds = function () {
  19846. if (!this._geometry) {
  19847. var result = [];
  19848. if (this._delayInfo) {
  19849. this._delayInfo.forEach(function (kind, index, array) {
  19850. result.push(kind);
  19851. });
  19852. }
  19853. return result;
  19854. }
  19855. return this._geometry.getVerticesDataKinds();
  19856. };
  19857. /**
  19858. * Returns a positive integer : the total number of indices in this mesh geometry.
  19859. * Returns zero if the mesh has no geometry.
  19860. */
  19861. Mesh.prototype.getTotalIndices = function () {
  19862. if (!this._geometry) {
  19863. return 0;
  19864. }
  19865. return this._geometry.getTotalIndices();
  19866. };
  19867. /**
  19868. * Returns an array of integers or a Int32Array populated with the mesh indices.
  19869. * 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.
  19870. * Returns an empty array if the mesh has no geometry.
  19871. */
  19872. Mesh.prototype.getIndices = function (copyWhenShared) {
  19873. if (!this._geometry) {
  19874. return [];
  19875. }
  19876. return this._geometry.getIndices(copyWhenShared);
  19877. };
  19878. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19879. get: function () {
  19880. return this._masterMesh !== null && this._masterMesh !== undefined;
  19881. },
  19882. enumerable: true,
  19883. configurable: true
  19884. });
  19885. /**
  19886. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19887. */
  19888. Mesh.prototype.isReady = function () {
  19889. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19890. return false;
  19891. }
  19892. return _super.prototype.isReady.call(this);
  19893. };
  19894. /**
  19895. * Boolean : true if the mesh has been disposed.
  19896. */
  19897. Mesh.prototype.isDisposed = function () {
  19898. return this._isDisposed;
  19899. };
  19900. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19901. get: function () {
  19902. return this._sideOrientation;
  19903. },
  19904. /**
  19905. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19906. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19907. */
  19908. set: function (sideO) {
  19909. this._sideOrientation = sideO;
  19910. },
  19911. enumerable: true,
  19912. configurable: true
  19913. });
  19914. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19915. /**
  19916. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19917. * This property is pertinent only for updatable parametric shapes.
  19918. */
  19919. get: function () {
  19920. return this._areNormalsFrozen;
  19921. },
  19922. enumerable: true,
  19923. configurable: true
  19924. });
  19925. /**
  19926. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19927. * It has no effect at all on other shapes.
  19928. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19929. */
  19930. Mesh.prototype.freezeNormals = function () {
  19931. this._areNormalsFrozen = true;
  19932. };
  19933. /**
  19934. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19935. * It has no effect at all on other shapes.
  19936. * It reactivates the mesh normals computation if it was previously frozen.
  19937. */
  19938. Mesh.prototype.unfreezeNormals = function () {
  19939. this._areNormalsFrozen = false;
  19940. };
  19941. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19942. /**
  19943. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19944. */
  19945. set: function (count) {
  19946. this._overridenInstanceCount = count;
  19947. },
  19948. enumerable: true,
  19949. configurable: true
  19950. });
  19951. // Methods
  19952. Mesh.prototype._preActivate = function () {
  19953. var sceneRenderId = this.getScene().getRenderId();
  19954. if (this._preActivateId === sceneRenderId) {
  19955. return;
  19956. }
  19957. this._preActivateId = sceneRenderId;
  19958. this._visibleInstances = null;
  19959. };
  19960. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19961. if (this._visibleInstances) {
  19962. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19963. }
  19964. };
  19965. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19966. if (!this._visibleInstances) {
  19967. this._visibleInstances = {};
  19968. this._visibleInstances.defaultRenderId = renderId;
  19969. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19970. }
  19971. if (!this._visibleInstances[renderId]) {
  19972. this._visibleInstances[renderId] = new Array();
  19973. }
  19974. this._visibleInstances[renderId].push(instance);
  19975. };
  19976. /**
  19977. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19978. * This means the mesh underlying bounding box and sphere are recomputed.
  19979. */
  19980. Mesh.prototype.refreshBoundingInfo = function () {
  19981. if (this._boundingInfo.isLocked) {
  19982. return;
  19983. }
  19984. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19985. if (data) {
  19986. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19987. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19988. }
  19989. if (this.subMeshes) {
  19990. for (var index = 0; index < this.subMeshes.length; index++) {
  19991. this.subMeshes[index].refreshBoundingInfo();
  19992. }
  19993. }
  19994. this._updateBoundingInfo();
  19995. };
  19996. Mesh.prototype._createGlobalSubMesh = function () {
  19997. var totalVertices = this.getTotalVertices();
  19998. if (!totalVertices || !this.getIndices()) {
  19999. return null;
  20000. }
  20001. this.releaseSubMeshes();
  20002. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20003. };
  20004. Mesh.prototype.subdivide = function (count) {
  20005. if (count < 1) {
  20006. return;
  20007. }
  20008. var totalIndices = this.getTotalIndices();
  20009. var subdivisionSize = (totalIndices / count) | 0;
  20010. var offset = 0;
  20011. // Ensure that subdivisionSize is a multiple of 3
  20012. while (subdivisionSize % 3 !== 0) {
  20013. subdivisionSize++;
  20014. }
  20015. this.releaseSubMeshes();
  20016. for (var index = 0; index < count; index++) {
  20017. if (offset >= totalIndices) {
  20018. break;
  20019. }
  20020. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20021. offset += subdivisionSize;
  20022. }
  20023. this.synchronizeInstances();
  20024. };
  20025. /**
  20026. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20027. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20028. * The `data` are either a numeric array either a Float32Array.
  20029. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20030. * 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).
  20031. * Note that a new underlying VertexBuffer object is created each call.
  20032. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20033. *
  20034. * Possible `kind` values :
  20035. * - BABYLON.VertexBuffer.PositionKind
  20036. * - BABYLON.VertexBuffer.UVKind
  20037. * - BABYLON.VertexBuffer.UV2Kind
  20038. * - BABYLON.VertexBuffer.UV3Kind
  20039. * - BABYLON.VertexBuffer.UV4Kind
  20040. * - BABYLON.VertexBuffer.UV5Kind
  20041. * - BABYLON.VertexBuffer.UV6Kind
  20042. * - BABYLON.VertexBuffer.ColorKind
  20043. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20044. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20045. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20046. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20047. */
  20048. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20049. if (!this._geometry) {
  20050. var vertexData = new BABYLON.VertexData();
  20051. vertexData.set(data, kind);
  20052. var scene = this.getScene();
  20053. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20054. }
  20055. else {
  20056. this._geometry.setVerticesData(kind, data, updatable, stride);
  20057. }
  20058. };
  20059. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20060. if (!this._geometry) {
  20061. var scene = this.getScene();
  20062. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20063. }
  20064. this._geometry.setVerticesBuffer(buffer);
  20065. };
  20066. /**
  20067. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20068. * If the mesh has no geometry, it is simply returned as it is.
  20069. * The `data` are either a numeric array either a Float32Array.
  20070. * No new underlying VertexBuffer object is created.
  20071. * 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.
  20072. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20073. *
  20074. * Possible `kind` values :
  20075. * - BABYLON.VertexBuffer.PositionKind
  20076. * - BABYLON.VertexBuffer.UVKind
  20077. * - BABYLON.VertexBuffer.UV2Kind
  20078. * - BABYLON.VertexBuffer.UV3Kind
  20079. * - BABYLON.VertexBuffer.UV4Kind
  20080. * - BABYLON.VertexBuffer.UV5Kind
  20081. * - BABYLON.VertexBuffer.UV6Kind
  20082. * - BABYLON.VertexBuffer.ColorKind
  20083. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20084. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20085. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20086. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20087. */
  20088. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20089. if (!this._geometry) {
  20090. return;
  20091. }
  20092. if (!makeItUnique) {
  20093. this._geometry.updateVerticesData(kind, data, updateExtends);
  20094. }
  20095. else {
  20096. this.makeGeometryUnique();
  20097. this.updateVerticesData(kind, data, updateExtends, false);
  20098. }
  20099. };
  20100. /**
  20101. * Deprecated since BabylonJS v2.3
  20102. */
  20103. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  20104. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  20105. if (!this._geometry) {
  20106. return;
  20107. }
  20108. if (!makeItUnique) {
  20109. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  20110. }
  20111. else {
  20112. this.makeGeometryUnique();
  20113. this.updateVerticesDataDirectly(kind, data, offset, false);
  20114. }
  20115. };
  20116. /**
  20117. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20118. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20119. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20120. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20121. */
  20122. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20123. if (computeNormals === void 0) { computeNormals = true; }
  20124. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20125. positionFunction(positions);
  20126. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20127. if (computeNormals) {
  20128. var indices = this.getIndices();
  20129. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20130. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20131. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20132. }
  20133. };
  20134. Mesh.prototype.makeGeometryUnique = function () {
  20135. if (!this._geometry) {
  20136. return;
  20137. }
  20138. var oldGeometry = this._geometry;
  20139. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20140. oldGeometry.releaseForMesh(this, true);
  20141. geometry.applyToMesh(this);
  20142. };
  20143. /**
  20144. * Sets the mesh indices.
  20145. * Expects an array populated with integers or a Int32Array.
  20146. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20147. * This method creates a new index buffer each call.
  20148. */
  20149. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20150. if (!this._geometry) {
  20151. var vertexData = new BABYLON.VertexData();
  20152. vertexData.indices = indices;
  20153. var scene = this.getScene();
  20154. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20155. }
  20156. else {
  20157. this._geometry.setIndices(indices, totalVertices);
  20158. }
  20159. };
  20160. /**
  20161. * Invert the geometry to move from a right handed system to a left handed one.
  20162. */
  20163. Mesh.prototype.toLeftHanded = function () {
  20164. if (!this._geometry) {
  20165. return;
  20166. }
  20167. this._geometry.toLeftHanded();
  20168. };
  20169. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20170. var engine = this.getScene().getEngine();
  20171. // Wireframe
  20172. var indexToBind;
  20173. if (this._unIndexed) {
  20174. indexToBind = null;
  20175. }
  20176. else {
  20177. switch (fillMode) {
  20178. case BABYLON.Material.PointFillMode:
  20179. indexToBind = null;
  20180. break;
  20181. case BABYLON.Material.WireFrameFillMode:
  20182. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20183. break;
  20184. default:
  20185. case BABYLON.Material.TriangleFillMode:
  20186. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20187. break;
  20188. }
  20189. }
  20190. // VBOs
  20191. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  20192. };
  20193. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20194. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20195. return;
  20196. }
  20197. this.onBeforeDrawObservable.notifyObservers(this);
  20198. var engine = this.getScene().getEngine();
  20199. // Draw order
  20200. switch (fillMode) {
  20201. case BABYLON.Material.PointFillMode:
  20202. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20203. break;
  20204. case BABYLON.Material.WireFrameFillMode:
  20205. if (this._unIndexed) {
  20206. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20207. }
  20208. else {
  20209. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20210. }
  20211. break;
  20212. default:
  20213. if (this._unIndexed) {
  20214. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20215. }
  20216. else {
  20217. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20218. }
  20219. }
  20220. };
  20221. /**
  20222. * Registers for this mesh a javascript function called just before the rendering process.
  20223. * This function is passed the current mesh and doesn't return anything.
  20224. */
  20225. Mesh.prototype.registerBeforeRender = function (func) {
  20226. this.onBeforeRenderObservable.add(func);
  20227. };
  20228. /**
  20229. * Disposes a previously registered javascript function called before the rendering.
  20230. * This function is passed the current mesh and doesn't return anything.
  20231. */
  20232. Mesh.prototype.unregisterBeforeRender = function (func) {
  20233. this.onBeforeRenderObservable.removeCallback(func);
  20234. };
  20235. /**
  20236. * Registers for this mesh a javascript function called just after the rendering is complete.
  20237. * This function is passed the current mesh and doesn't return anything.
  20238. */
  20239. Mesh.prototype.registerAfterRender = function (func) {
  20240. this.onAfterRenderObservable.add(func);
  20241. };
  20242. /**
  20243. * Disposes a previously registered javascript function called after the rendering.
  20244. * This function is passed the current mesh and doesn't return anything.
  20245. */
  20246. Mesh.prototype.unregisterAfterRender = function (func) {
  20247. this.onAfterRenderObservable.removeCallback(func);
  20248. };
  20249. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20250. var scene = this.getScene();
  20251. this._batchCache.mustReturn = false;
  20252. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20253. this._batchCache.visibleInstances[subMeshId] = null;
  20254. if (this._visibleInstances) {
  20255. var currentRenderId = scene.getRenderId();
  20256. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20257. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20258. var selfRenderId = this._renderId;
  20259. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20260. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20261. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20262. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20263. }
  20264. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20265. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20266. this._batchCache.mustReturn = true;
  20267. return this._batchCache;
  20268. }
  20269. if (currentRenderId !== selfRenderId) {
  20270. this._batchCache.renderSelf[subMeshId] = false;
  20271. }
  20272. }
  20273. this._renderIdForInstances[subMeshId] = currentRenderId;
  20274. }
  20275. return this._batchCache;
  20276. };
  20277. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20278. var visibleInstances = batch.visibleInstances[subMesh._id];
  20279. var matricesCount = visibleInstances.length + 1;
  20280. var bufferSize = matricesCount * 16 * 4;
  20281. var currentInstancesBufferSize = this._instancesBufferSize;
  20282. var instancesBuffer = this._instancesBuffer;
  20283. while (this._instancesBufferSize < bufferSize) {
  20284. this._instancesBufferSize *= 2;
  20285. }
  20286. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20287. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20288. }
  20289. var offset = 0;
  20290. var instancesCount = 0;
  20291. var world = this.getWorldMatrix();
  20292. if (batch.renderSelf[subMesh._id]) {
  20293. world.copyToArray(this._instancesData, offset);
  20294. offset += 16;
  20295. instancesCount++;
  20296. }
  20297. if (visibleInstances) {
  20298. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20299. var instance = visibleInstances[instanceIndex];
  20300. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20301. offset += 16;
  20302. instancesCount++;
  20303. }
  20304. }
  20305. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20306. if (instancesBuffer) {
  20307. instancesBuffer.dispose();
  20308. }
  20309. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20310. this._instancesBuffer = instancesBuffer;
  20311. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20312. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20313. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20314. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20315. }
  20316. else {
  20317. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20318. }
  20319. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  20320. this._draw(subMesh, fillMode, instancesCount);
  20321. engine.unbindInstanceAttributes();
  20322. };
  20323. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20324. var scene = this.getScene();
  20325. var engine = scene.getEngine();
  20326. if (hardwareInstancedRendering) {
  20327. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20328. }
  20329. else {
  20330. if (batch.renderSelf[subMesh._id]) {
  20331. // Draw
  20332. if (onBeforeDraw) {
  20333. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20334. }
  20335. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20336. }
  20337. if (batch.visibleInstances[subMesh._id]) {
  20338. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20339. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20340. // World
  20341. var world = instance.getWorldMatrix();
  20342. if (onBeforeDraw) {
  20343. onBeforeDraw(true, world, effectiveMaterial);
  20344. }
  20345. // Draw
  20346. this._draw(subMesh, fillMode);
  20347. }
  20348. }
  20349. }
  20350. };
  20351. /**
  20352. * Triggers the draw call for the mesh.
  20353. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20354. */
  20355. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20356. var scene = this.getScene();
  20357. // Managing instances
  20358. var batch = this._getInstancesRenderList(subMesh._id);
  20359. if (batch.mustReturn) {
  20360. return;
  20361. }
  20362. // Checking geometry state
  20363. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20364. return;
  20365. }
  20366. var callbackIndex;
  20367. this.onBeforeRenderObservable.notifyObservers(this);
  20368. var engine = scene.getEngine();
  20369. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20370. // Material
  20371. var effectiveMaterial = subMesh.getMaterial();
  20372. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20373. return;
  20374. }
  20375. // Outline - step 1
  20376. var savedDepthWrite = engine.getDepthWrite();
  20377. if (this.renderOutline) {
  20378. engine.setDepthWrite(false);
  20379. scene.getOutlineRenderer().render(subMesh, batch);
  20380. engine.setDepthWrite(savedDepthWrite);
  20381. }
  20382. effectiveMaterial._preBind();
  20383. var effect = effectiveMaterial.getEffect();
  20384. // Bind
  20385. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20386. this._bind(subMesh, effect, fillMode);
  20387. var world = this.getWorldMatrix();
  20388. effectiveMaterial.bind(world, this);
  20389. // Alpha mode
  20390. if (enableAlphaMode) {
  20391. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20392. }
  20393. // Draw
  20394. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20395. // Unbind
  20396. effectiveMaterial.unbind();
  20397. // Outline - step 2
  20398. if (this.renderOutline && savedDepthWrite) {
  20399. engine.setDepthWrite(true);
  20400. engine.setColorWrite(false);
  20401. scene.getOutlineRenderer().render(subMesh, batch);
  20402. engine.setColorWrite(true);
  20403. }
  20404. // Overlay
  20405. if (this.renderOverlay) {
  20406. var currentMode = engine.getAlphaMode();
  20407. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20408. scene.getOutlineRenderer().render(subMesh, batch, true);
  20409. engine.setAlphaMode(currentMode);
  20410. }
  20411. this.onAfterRenderObservable.notifyObservers(this);
  20412. };
  20413. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20414. if (isInstance) {
  20415. effectiveMaterial.bindOnlyWorldMatrix(world);
  20416. }
  20417. };
  20418. /**
  20419. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20420. */
  20421. Mesh.prototype.getEmittedParticleSystems = function () {
  20422. var results = new Array();
  20423. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20424. var particleSystem = this.getScene().particleSystems[index];
  20425. if (particleSystem.emitter === this) {
  20426. results.push(particleSystem);
  20427. }
  20428. }
  20429. return results;
  20430. };
  20431. /**
  20432. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20433. */
  20434. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20435. var results = new Array();
  20436. var descendants = this.getDescendants();
  20437. descendants.push(this);
  20438. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20439. var particleSystem = this.getScene().particleSystems[index];
  20440. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20441. results.push(particleSystem);
  20442. }
  20443. }
  20444. return results;
  20445. };
  20446. Mesh.prototype._checkDelayState = function () {
  20447. var scene = this.getScene();
  20448. if (this._geometry) {
  20449. this._geometry.load(scene);
  20450. }
  20451. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20452. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20453. this._queueLoad(this, scene);
  20454. }
  20455. };
  20456. Mesh.prototype._queueLoad = function (mesh, scene) {
  20457. var _this = this;
  20458. scene._addPendingData(mesh);
  20459. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20460. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20461. if (data instanceof ArrayBuffer) {
  20462. _this._delayLoadingFunction(data, _this);
  20463. }
  20464. else {
  20465. _this._delayLoadingFunction(JSON.parse(data), _this);
  20466. }
  20467. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20468. scene._removePendingData(_this);
  20469. }, function () { }, scene.database, getBinaryData);
  20470. };
  20471. /**
  20472. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20473. */
  20474. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20475. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20476. return false;
  20477. }
  20478. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20479. return false;
  20480. }
  20481. this._checkDelayState();
  20482. return true;
  20483. };
  20484. /**
  20485. * Sets the mesh material by the material or multiMaterial `id` property.
  20486. * The material `id` is a string identifying the material or the multiMaterial.
  20487. * This method returns nothing.
  20488. */
  20489. Mesh.prototype.setMaterialByID = function (id) {
  20490. var materials = this.getScene().materials;
  20491. var index;
  20492. for (index = 0; index < materials.length; index++) {
  20493. if (materials[index].id === id) {
  20494. this.material = materials[index];
  20495. return;
  20496. }
  20497. }
  20498. // Multi
  20499. var multiMaterials = this.getScene().multiMaterials;
  20500. for (index = 0; index < multiMaterials.length; index++) {
  20501. if (multiMaterials[index].id === id) {
  20502. this.material = multiMaterials[index];
  20503. return;
  20504. }
  20505. }
  20506. };
  20507. /**
  20508. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20509. */
  20510. Mesh.prototype.getAnimatables = function () {
  20511. var results = [];
  20512. if (this.material) {
  20513. results.push(this.material);
  20514. }
  20515. if (this.skeleton) {
  20516. results.push(this.skeleton);
  20517. }
  20518. return results;
  20519. };
  20520. /**
  20521. * Modifies the mesh geometry according to the passed transformation matrix.
  20522. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20523. * The mesh normals are modified accordingly the same transformation.
  20524. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20525. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20526. */
  20527. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20528. // Position
  20529. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20530. return;
  20531. }
  20532. var submeshes = this.subMeshes.splice(0);
  20533. this._resetPointsArrayCache();
  20534. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20535. var temp = [];
  20536. var index;
  20537. for (index = 0; index < data.length; index += 3) {
  20538. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20539. }
  20540. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20541. // Normals
  20542. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20543. return;
  20544. }
  20545. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20546. temp = [];
  20547. for (index = 0; index < data.length; index += 3) {
  20548. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20549. }
  20550. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20551. // flip faces?
  20552. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20553. this.flipFaces();
  20554. }
  20555. // Restore submeshes
  20556. this.releaseSubMeshes();
  20557. this.subMeshes = submeshes;
  20558. };
  20559. /**
  20560. * Modifies the mesh geometry according to its own current World Matrix.
  20561. * The mesh World Matrix is then reset.
  20562. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20563. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20564. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20565. */
  20566. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20567. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20568. this.scaling.copyFromFloats(1, 1, 1);
  20569. this.position.copyFromFloats(0, 0, 0);
  20570. this.rotation.copyFromFloats(0, 0, 0);
  20571. //only if quaternion is already set
  20572. if (this.rotationQuaternion) {
  20573. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20574. }
  20575. this._worldMatrix = BABYLON.Matrix.Identity();
  20576. };
  20577. // Cache
  20578. Mesh.prototype._resetPointsArrayCache = function () {
  20579. this._positions = null;
  20580. };
  20581. Mesh.prototype._generatePointsArray = function () {
  20582. if (this._positions)
  20583. return true;
  20584. this._positions = [];
  20585. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20586. if (!data) {
  20587. return false;
  20588. }
  20589. for (var index = 0; index < data.length; index += 3) {
  20590. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  20591. }
  20592. return true;
  20593. };
  20594. /**
  20595. * Returns a new Mesh object generated from the current mesh properties.
  20596. * This method must not get confused with createInstance().
  20597. * The parameter `name` is a string, the name given to the new mesh.
  20598. * The optional parameter `newParent` can be any Node object (default `null`).
  20599. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20600. * 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.
  20601. */
  20602. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20603. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20604. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20605. };
  20606. /**
  20607. * Disposes the mesh.
  20608. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20609. */
  20610. Mesh.prototype.dispose = function (doNotRecurse) {
  20611. if (this._geometry) {
  20612. this._geometry.releaseForMesh(this, true);
  20613. }
  20614. // Instances
  20615. if (this._instancesBuffer) {
  20616. this._instancesBuffer.dispose();
  20617. this._instancesBuffer = null;
  20618. }
  20619. while (this.instances.length) {
  20620. this.instances[0].dispose();
  20621. }
  20622. // Highlight layers.
  20623. var highlightLayers = this.getScene().highlightLayers;
  20624. for (var i = 0; i < highlightLayers.length; i++) {
  20625. var highlightLayer = highlightLayers[i];
  20626. if (highlightLayer) {
  20627. highlightLayer.removeMesh(this);
  20628. highlightLayer.removeExcludedMesh(this);
  20629. }
  20630. }
  20631. _super.prototype.dispose.call(this, doNotRecurse);
  20632. };
  20633. /**
  20634. * Modifies the mesh geometry according to a displacement map.
  20635. * 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.
  20636. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20637. * This method returns nothing.
  20638. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20639. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20640. * 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.
  20641. */
  20642. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  20643. var _this = this;
  20644. var scene = this.getScene();
  20645. var onload = function (img) {
  20646. // Getting height map data
  20647. var canvas = document.createElement("canvas");
  20648. var context = canvas.getContext("2d");
  20649. var heightMapWidth = img.width;
  20650. var heightMapHeight = img.height;
  20651. canvas.width = heightMapWidth;
  20652. canvas.height = heightMapHeight;
  20653. context.drawImage(img, 0, 0);
  20654. // Create VertexData from map data
  20655. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20656. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20657. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  20658. //execute success callback, if set
  20659. if (onSuccess) {
  20660. onSuccess(_this);
  20661. }
  20662. };
  20663. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20664. };
  20665. /**
  20666. * Modifies the mesh geometry according to a displacementMap buffer.
  20667. * 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.
  20668. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20669. * This method returns nothing.
  20670. * 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.
  20671. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20672. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20673. */
  20674. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  20675. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20676. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20677. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20678. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20679. return;
  20680. }
  20681. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20682. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20683. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20684. var position = BABYLON.Vector3.Zero();
  20685. var normal = BABYLON.Vector3.Zero();
  20686. var uv = BABYLON.Vector2.Zero();
  20687. for (var index = 0; index < positions.length; index += 3) {
  20688. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20689. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20690. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20691. // Compute height
  20692. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  20693. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  20694. var pos = (u + v * heightMapWidth) * 4;
  20695. var r = buffer[pos] / 255.0;
  20696. var g = buffer[pos + 1] / 255.0;
  20697. var b = buffer[pos + 2] / 255.0;
  20698. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20699. normal.normalize();
  20700. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20701. position = position.add(normal);
  20702. position.toArray(positions, index);
  20703. }
  20704. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20705. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20706. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20707. };
  20708. /**
  20709. * Modify the mesh to get a flat shading rendering.
  20710. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20711. * This method returns nothing.
  20712. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20713. */
  20714. Mesh.prototype.convertToFlatShadedMesh = function () {
  20715. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20716. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20717. var kinds = this.getVerticesDataKinds();
  20718. var vbs = [];
  20719. var data = [];
  20720. var newdata = [];
  20721. var updatableNormals = false;
  20722. var kindIndex;
  20723. var kind;
  20724. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20725. kind = kinds[kindIndex];
  20726. var vertexBuffer = this.getVertexBuffer(kind);
  20727. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20728. updatableNormals = vertexBuffer.isUpdatable();
  20729. kinds.splice(kindIndex, 1);
  20730. kindIndex--;
  20731. continue;
  20732. }
  20733. vbs[kind] = vertexBuffer;
  20734. data[kind] = vbs[kind].getData();
  20735. newdata[kind] = [];
  20736. }
  20737. // Save previous submeshes
  20738. var previousSubmeshes = this.subMeshes.slice(0);
  20739. var indices = this.getIndices();
  20740. var totalIndices = this.getTotalIndices();
  20741. // Generating unique vertices per face
  20742. var index;
  20743. for (index = 0; index < totalIndices; index++) {
  20744. var vertexIndex = indices[index];
  20745. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20746. kind = kinds[kindIndex];
  20747. var stride = vbs[kind].getStrideSize();
  20748. for (var offset = 0; offset < stride; offset++) {
  20749. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20750. }
  20751. }
  20752. }
  20753. // Updating faces & normal
  20754. var normals = [];
  20755. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20756. for (index = 0; index < totalIndices; index += 3) {
  20757. indices[index] = index;
  20758. indices[index + 1] = index + 1;
  20759. indices[index + 2] = index + 2;
  20760. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20761. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20762. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20763. var p1p2 = p1.subtract(p2);
  20764. var p3p2 = p3.subtract(p2);
  20765. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20766. // Store same normals for every vertex
  20767. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20768. normals.push(normal.x);
  20769. normals.push(normal.y);
  20770. normals.push(normal.z);
  20771. }
  20772. }
  20773. this.setIndices(indices);
  20774. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20775. // Updating vertex buffers
  20776. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20777. kind = kinds[kindIndex];
  20778. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20779. }
  20780. // Updating submeshes
  20781. this.releaseSubMeshes();
  20782. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20783. var previousOne = previousSubmeshes[submeshIndex];
  20784. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20785. }
  20786. this.synchronizeInstances();
  20787. };
  20788. /**
  20789. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20790. * In other words, more vertices, no more indices and a single bigger VBO.
  20791. * This method returns nothing.
  20792. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20793. *
  20794. */
  20795. Mesh.prototype.convertToUnIndexedMesh = function () {
  20796. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20797. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20798. var kinds = this.getVerticesDataKinds();
  20799. var vbs = [];
  20800. var data = [];
  20801. var newdata = [];
  20802. var updatableNormals = false;
  20803. var kindIndex;
  20804. var kind;
  20805. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20806. kind = kinds[kindIndex];
  20807. var vertexBuffer = this.getVertexBuffer(kind);
  20808. vbs[kind] = vertexBuffer;
  20809. data[kind] = vbs[kind].getData();
  20810. newdata[kind] = [];
  20811. }
  20812. // Save previous submeshes
  20813. var previousSubmeshes = this.subMeshes.slice(0);
  20814. var indices = this.getIndices();
  20815. var totalIndices = this.getTotalIndices();
  20816. // Generating unique vertices per face
  20817. var index;
  20818. for (index = 0; index < totalIndices; index++) {
  20819. var vertexIndex = indices[index];
  20820. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20821. kind = kinds[kindIndex];
  20822. var stride = vbs[kind].getStrideSize();
  20823. for (var offset = 0; offset < stride; offset++) {
  20824. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20825. }
  20826. }
  20827. }
  20828. // Updating indices
  20829. for (index = 0; index < totalIndices; index += 3) {
  20830. indices[index] = index;
  20831. indices[index + 1] = index + 1;
  20832. indices[index + 2] = index + 2;
  20833. }
  20834. this.setIndices(indices);
  20835. // Updating vertex buffers
  20836. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20837. kind = kinds[kindIndex];
  20838. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20839. }
  20840. // Updating submeshes
  20841. this.releaseSubMeshes();
  20842. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20843. var previousOne = previousSubmeshes[submeshIndex];
  20844. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20845. }
  20846. this._unIndexed = true;
  20847. this.synchronizeInstances();
  20848. };
  20849. /**
  20850. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20851. * This method returns nothing.
  20852. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20853. */
  20854. Mesh.prototype.flipFaces = function (flipNormals) {
  20855. if (flipNormals === void 0) { flipNormals = false; }
  20856. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20857. var i;
  20858. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20859. for (i = 0; i < vertex_data.normals.length; i++) {
  20860. vertex_data.normals[i] *= -1;
  20861. }
  20862. }
  20863. var temp;
  20864. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20865. // reassign indices
  20866. temp = vertex_data.indices[i + 1];
  20867. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20868. vertex_data.indices[i + 2] = temp;
  20869. }
  20870. vertex_data.applyToMesh(this);
  20871. };
  20872. // Instances
  20873. /**
  20874. * Creates a new InstancedMesh object from the mesh model.
  20875. * An instance shares the same properties and the same material than its model.
  20876. * Only these properties of each instance can then be set individually :
  20877. * - position
  20878. * - rotation
  20879. * - rotationQuaternion
  20880. * - setPivotMatrix
  20881. * - scaling
  20882. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20883. * Warning : this method is not supported for Line mesh and LineSystem
  20884. */
  20885. Mesh.prototype.createInstance = function (name) {
  20886. return new BABYLON.InstancedMesh(name, this);
  20887. };
  20888. /**
  20889. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20890. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20891. * This method returns nothing.
  20892. */
  20893. Mesh.prototype.synchronizeInstances = function () {
  20894. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20895. var instance = this.instances[instanceIndex];
  20896. instance._syncSubMeshes();
  20897. }
  20898. };
  20899. /**
  20900. * Simplify the mesh according to the given array of settings.
  20901. * Function will return immediately and will simplify async. It returns nothing.
  20902. * @param settings a collection of simplification settings.
  20903. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20904. * @param type the type of simplification to run.
  20905. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20906. */
  20907. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20908. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20909. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20910. this.getScene().simplificationQueue.addTask({
  20911. settings: settings,
  20912. parallelProcessing: parallelProcessing,
  20913. mesh: this,
  20914. simplificationType: simplificationType,
  20915. successCallback: successCallback
  20916. });
  20917. };
  20918. /**
  20919. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20920. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20921. * This should be used together with the simplification to avoid disappearing triangles.
  20922. * @param successCallback an optional success callback to be called after the optimization finished.
  20923. */
  20924. Mesh.prototype.optimizeIndices = function (successCallback) {
  20925. var _this = this;
  20926. var indices = this.getIndices();
  20927. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20928. var vectorPositions = [];
  20929. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20930. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20931. }
  20932. var dupes = [];
  20933. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20934. var realPos = vectorPositions.length - 1 - iteration;
  20935. var testedPosition = vectorPositions[realPos];
  20936. for (var j = 0; j < realPos; ++j) {
  20937. var againstPosition = vectorPositions[j];
  20938. if (testedPosition.equals(againstPosition)) {
  20939. dupes[realPos] = j;
  20940. break;
  20941. }
  20942. }
  20943. }, function () {
  20944. for (var i = 0; i < indices.length; ++i) {
  20945. indices[i] = dupes[indices[i]] || indices[i];
  20946. }
  20947. //indices are now reordered
  20948. var originalSubMeshes = _this.subMeshes.slice(0);
  20949. _this.setIndices(indices);
  20950. _this.subMeshes = originalSubMeshes;
  20951. if (successCallback) {
  20952. successCallback(_this);
  20953. }
  20954. });
  20955. };
  20956. // Statics
  20957. /**
  20958. * Returns a new Mesh object what is a deep copy of the passed mesh.
  20959. * The parameter `parsedMesh` is the mesh to be copied.
  20960. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20961. */
  20962. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  20963. var mesh = new Mesh(parsedMesh.name, scene);
  20964. mesh.id = parsedMesh.id;
  20965. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20966. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20967. if (parsedMesh.metadata !== undefined) {
  20968. mesh.metadata = parsedMesh.metadata;
  20969. }
  20970. if (parsedMesh.rotationQuaternion) {
  20971. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20972. }
  20973. else if (parsedMesh.rotation) {
  20974. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20975. }
  20976. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20977. if (parsedMesh.localMatrix) {
  20978. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20979. }
  20980. else if (parsedMesh.pivotMatrix) {
  20981. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20982. }
  20983. mesh.setEnabled(parsedMesh.isEnabled);
  20984. mesh.isVisible = parsedMesh.isVisible;
  20985. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20986. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20987. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20988. if (parsedMesh.applyFog !== undefined) {
  20989. mesh.applyFog = parsedMesh.applyFog;
  20990. }
  20991. if (parsedMesh.pickable !== undefined) {
  20992. mesh.isPickable = parsedMesh.pickable;
  20993. }
  20994. if (parsedMesh.alphaIndex !== undefined) {
  20995. mesh.alphaIndex = parsedMesh.alphaIndex;
  20996. }
  20997. mesh.receiveShadows = parsedMesh.receiveShadows;
  20998. mesh.billboardMode = parsedMesh.billboardMode;
  20999. if (parsedMesh.visibility !== undefined) {
  21000. mesh.visibility = parsedMesh.visibility;
  21001. }
  21002. mesh.checkCollisions = parsedMesh.checkCollisions;
  21003. if (parsedMesh.isBlocker !== undefined) {
  21004. mesh.isBlocker = parsedMesh.isBlocker;
  21005. }
  21006. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21007. // freezeWorldMatrix
  21008. if (parsedMesh.freezeWorldMatrix) {
  21009. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21010. }
  21011. // Parent
  21012. if (parsedMesh.parentId) {
  21013. mesh._waitingParentId = parsedMesh.parentId;
  21014. }
  21015. // Actions
  21016. if (parsedMesh.actions !== undefined) {
  21017. mesh._waitingActions = parsedMesh.actions;
  21018. }
  21019. // Geometry
  21020. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21021. if (parsedMesh.delayLoadingFile) {
  21022. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21023. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21024. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21025. if (parsedMesh._binaryInfo) {
  21026. mesh._binaryInfo = parsedMesh._binaryInfo;
  21027. }
  21028. mesh._delayInfo = [];
  21029. if (parsedMesh.hasUVs) {
  21030. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21031. }
  21032. if (parsedMesh.hasUVs2) {
  21033. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21034. }
  21035. if (parsedMesh.hasUVs3) {
  21036. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21037. }
  21038. if (parsedMesh.hasUVs4) {
  21039. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21040. }
  21041. if (parsedMesh.hasUVs5) {
  21042. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21043. }
  21044. if (parsedMesh.hasUVs6) {
  21045. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21046. }
  21047. if (parsedMesh.hasColors) {
  21048. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21049. }
  21050. if (parsedMesh.hasMatricesIndices) {
  21051. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21052. }
  21053. if (parsedMesh.hasMatricesWeights) {
  21054. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21055. }
  21056. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21057. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21058. mesh._checkDelayState();
  21059. }
  21060. }
  21061. else {
  21062. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21063. }
  21064. // Material
  21065. if (parsedMesh.materialId) {
  21066. mesh.setMaterialByID(parsedMesh.materialId);
  21067. }
  21068. else {
  21069. mesh.material = null;
  21070. }
  21071. // Skeleton
  21072. if (parsedMesh.skeletonId > -1) {
  21073. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21074. if (parsedMesh.numBoneInfluencers) {
  21075. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21076. }
  21077. }
  21078. // Animations
  21079. if (parsedMesh.animations) {
  21080. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21081. var parsedAnimation = parsedMesh.animations[animationIndex];
  21082. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21083. }
  21084. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21085. }
  21086. if (parsedMesh.autoAnimate) {
  21087. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21088. }
  21089. // Layer Mask
  21090. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21091. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21092. }
  21093. else {
  21094. mesh.layerMask = 0x0FFFFFFF;
  21095. }
  21096. //(Deprecated) physics
  21097. if (parsedMesh.physicsImpostor) {
  21098. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21099. mass: parsedMesh.physicsMass,
  21100. friction: parsedMesh.physicsFriction,
  21101. restitution: parsedMesh.physicsRestitution
  21102. }, scene);
  21103. }
  21104. // Instances
  21105. if (parsedMesh.instances) {
  21106. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21107. var parsedInstance = parsedMesh.instances[index];
  21108. var instance = mesh.createInstance(parsedInstance.name);
  21109. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21110. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21111. if (parsedInstance.parentId) {
  21112. instance._waitingParentId = parsedInstance.parentId;
  21113. }
  21114. if (parsedInstance.rotationQuaternion) {
  21115. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21116. }
  21117. else if (parsedInstance.rotation) {
  21118. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21119. }
  21120. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21121. instance.checkCollisions = mesh.checkCollisions;
  21122. if (parsedMesh.animations) {
  21123. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21124. parsedAnimation = parsedMesh.animations[animationIndex];
  21125. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21126. }
  21127. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21128. }
  21129. }
  21130. }
  21131. return mesh;
  21132. };
  21133. /**
  21134. * Creates a ribbon mesh.
  21135. * Please consider using the same method from the MeshBuilder class instead.
  21136. * 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.
  21137. *
  21138. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21139. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21140. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21141. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21142. * 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.
  21143. * 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.
  21144. * 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
  21145. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21146. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21147. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21148. */
  21149. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21150. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21151. pathArray: pathArray,
  21152. closeArray: closeArray,
  21153. closePath: closePath,
  21154. offset: offset,
  21155. updatable: updatable,
  21156. sideOrientation: sideOrientation,
  21157. instance: instance
  21158. }, scene);
  21159. };
  21160. /**
  21161. * Creates a plane polygonal mesh. By default, this is a disc.
  21162. * Please consider using the same method from the MeshBuilder class instead.
  21163. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21164. * 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.
  21165. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21166. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21167. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21168. */
  21169. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21170. var options = {
  21171. radius: radius,
  21172. tessellation: tessellation,
  21173. sideOrientation: sideOrientation,
  21174. updatable: updatable
  21175. };
  21176. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21177. };
  21178. /**
  21179. * Creates a box mesh.
  21180. * Please consider using the same method from the MeshBuilder class instead.
  21181. * The parameter `size` sets the size (float) of each box side (default 1).
  21182. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21183. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21184. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21185. */
  21186. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21187. var options = {
  21188. size: size,
  21189. sideOrientation: sideOrientation,
  21190. updatable: updatable
  21191. };
  21192. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21193. };
  21194. /**
  21195. * Creates a sphere mesh.
  21196. * Please consider using the same method from the MeshBuilder class instead.
  21197. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21198. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21199. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21200. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21201. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21202. */
  21203. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21204. var options = {
  21205. segments: segments,
  21206. diameterX: diameter,
  21207. diameterY: diameter,
  21208. diameterZ: diameter,
  21209. sideOrientation: sideOrientation,
  21210. updatable: updatable
  21211. };
  21212. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21213. };
  21214. /**
  21215. * Creates a cylinder or a cone mesh.
  21216. * Please consider using the same method from the MeshBuilder class instead.
  21217. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21218. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21219. * 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.
  21220. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21221. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21222. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21223. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21224. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21225. */
  21226. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21227. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21228. if (scene !== undefined) {
  21229. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21230. updatable = scene;
  21231. }
  21232. scene = subdivisions;
  21233. subdivisions = 1;
  21234. }
  21235. var options = {
  21236. height: height,
  21237. diameterTop: diameterTop,
  21238. diameterBottom: diameterBottom,
  21239. tessellation: tessellation,
  21240. subdivisions: subdivisions,
  21241. sideOrientation: sideOrientation,
  21242. updatable: updatable
  21243. };
  21244. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21245. };
  21246. // Torus (Code from SharpDX.org)
  21247. /**
  21248. * Creates a torus mesh.
  21249. * Please consider using the same method from the MeshBuilder class instead.
  21250. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21251. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21252. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21253. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21254. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21255. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21256. */
  21257. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21258. var options = {
  21259. diameter: diameter,
  21260. thickness: thickness,
  21261. tessellation: tessellation,
  21262. sideOrientation: sideOrientation,
  21263. updatable: updatable
  21264. };
  21265. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21266. };
  21267. /**
  21268. * Creates a torus knot mesh.
  21269. * Please consider using the same method from the MeshBuilder class instead.
  21270. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21271. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21272. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21273. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21274. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21275. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21276. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21277. */
  21278. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21279. var options = {
  21280. radius: radius,
  21281. tube: tube,
  21282. radialSegments: radialSegments,
  21283. tubularSegments: tubularSegments,
  21284. p: p,
  21285. q: q,
  21286. sideOrientation: sideOrientation,
  21287. updatable: updatable
  21288. };
  21289. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21290. };
  21291. /**
  21292. * Creates a line mesh.
  21293. * Please consider using the same method from the MeshBuilder class instead.
  21294. * 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.
  21295. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21296. * The parameter `points` is an array successive Vector3.
  21297. * 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
  21298. * When updating an instance, remember that only point positions can change, not the number of points.
  21299. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21300. */
  21301. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21302. var options = {
  21303. points: points,
  21304. updatable: updatable,
  21305. instance: instance
  21306. };
  21307. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21308. };
  21309. /**
  21310. * Creates a dashed line mesh.
  21311. * Please consider using the same method from the MeshBuilder class instead.
  21312. * 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.
  21313. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21314. * The parameter `points` is an array successive Vector3.
  21315. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21316. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21317. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21318. * 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
  21319. * When updating an instance, remember that only point positions can change, not the number of points.
  21320. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21321. */
  21322. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21323. var options = {
  21324. points: points,
  21325. dashSize: dashSize,
  21326. gapSize: gapSize,
  21327. dashNb: dashNb,
  21328. updatable: updatable,
  21329. instance: instance
  21330. };
  21331. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21332. };
  21333. /**
  21334. * Creates an extruded shape mesh.
  21335. * 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.
  21336. * Please consider using the same method from the MeshBuilder class instead.
  21337. *
  21338. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21339. * 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
  21340. * extruded along the Z axis.
  21341. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21342. * 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.
  21343. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21344. * 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
  21345. * 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
  21346. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21347. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21348. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21349. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21350. */
  21351. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21352. var options = {
  21353. shape: shape,
  21354. path: path,
  21355. scale: scale,
  21356. rotation: rotation,
  21357. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21358. sideOrientation: sideOrientation,
  21359. instance: instance,
  21360. updatable: updatable
  21361. };
  21362. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21363. };
  21364. /**
  21365. * Creates an custom extruded shape mesh.
  21366. * 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.
  21367. * Please consider using the same method from the MeshBuilder class instead.
  21368. *
  21369. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21370. * 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
  21371. * extruded along the Z axis.
  21372. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21373. * 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
  21374. * and the distance of this point from the begining of the path :
  21375. * ```javascript
  21376. * var rotationFunction = function(i, distance) {
  21377. * // do things
  21378. * return rotationValue; }
  21379. * ```
  21380. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21381. * 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
  21382. * and the distance of this point from the begining of the path :
  21383. * ```javascript
  21384. * var scaleFunction = function(i, distance) {
  21385. * // do things
  21386. * return scaleValue;}
  21387. * ```
  21388. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21389. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21390. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21391. * 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
  21392. * 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
  21393. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21394. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21395. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21397. */
  21398. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21399. var options = {
  21400. shape: shape,
  21401. path: path,
  21402. scaleFunction: scaleFunction,
  21403. rotationFunction: rotationFunction,
  21404. ribbonCloseArray: ribbonCloseArray,
  21405. ribbonClosePath: ribbonClosePath,
  21406. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21407. sideOrientation: sideOrientation,
  21408. instance: instance,
  21409. updatable: updatable
  21410. };
  21411. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21412. };
  21413. /**
  21414. * Creates lathe mesh.
  21415. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21416. * Please consider using the same method from the MeshBuilder class instead.
  21417. * 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
  21418. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21419. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21420. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21421. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21422. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21423. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21424. */
  21425. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21426. var options = {
  21427. shape: shape,
  21428. radius: radius,
  21429. tessellation: tessellation,
  21430. sideOrientation: sideOrientation,
  21431. updatable: updatable
  21432. };
  21433. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21434. };
  21435. /**
  21436. * Creates a plane mesh.
  21437. * Please consider using the same method from the MeshBuilder class instead.
  21438. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21439. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21440. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21441. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21442. */
  21443. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21444. var options = {
  21445. size: size,
  21446. width: size,
  21447. height: size,
  21448. sideOrientation: sideOrientation,
  21449. updatable: updatable
  21450. };
  21451. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21452. };
  21453. /**
  21454. * Creates a ground mesh.
  21455. * Please consider using the same method from the MeshBuilder class instead.
  21456. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21457. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21458. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21459. */
  21460. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21461. var options = {
  21462. width: width,
  21463. height: height,
  21464. subdivisions: subdivisions,
  21465. updatable: updatable
  21466. };
  21467. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21468. };
  21469. /**
  21470. * Creates a tiled ground mesh.
  21471. * Please consider using the same method from the MeshBuilder class instead.
  21472. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21473. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21474. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21475. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21476. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21477. * numbers of subdivisions on the ground width and height of each tile.
  21478. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21479. */
  21480. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21481. var options = {
  21482. xmin: xmin,
  21483. zmin: zmin,
  21484. xmax: xmax,
  21485. zmax: zmax,
  21486. subdivisions: subdivisions,
  21487. precision: precision,
  21488. updatable: updatable
  21489. };
  21490. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21491. };
  21492. /**
  21493. * Creates a ground mesh from a height map.
  21494. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21495. * Please consider using the same method from the MeshBuilder class instead.
  21496. * The parameter `url` sets the URL of the height map image resource.
  21497. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21498. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21499. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21500. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21501. * 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).
  21502. * This function is passed the newly built mesh :
  21503. * ```javascript
  21504. * function(mesh) { // do things
  21505. * return; }
  21506. * ```
  21507. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21508. */
  21509. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21510. var options = {
  21511. width: width,
  21512. height: height,
  21513. subdivisions: subdivisions,
  21514. minHeight: minHeight,
  21515. maxHeight: maxHeight,
  21516. updatable: updatable,
  21517. onReady: onReady
  21518. };
  21519. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21520. };
  21521. /**
  21522. * Creates a tube mesh.
  21523. * 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.
  21524. * Please consider using the same method from the MeshBuilder class instead.
  21525. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21526. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21527. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21528. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21529. * 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.
  21530. * It must return a radius value (positive float) :
  21531. * ```javascript
  21532. * var radiusFunction = function(i, distance) {
  21533. * // do things
  21534. * return radius; }
  21535. * ```
  21536. * 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
  21537. * 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
  21538. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21539. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21540. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21541. */
  21542. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21543. var options = {
  21544. path: path,
  21545. radius: radius,
  21546. tessellation: tessellation,
  21547. radiusFunction: radiusFunction,
  21548. arc: 1,
  21549. cap: cap,
  21550. updatable: updatable,
  21551. sideOrientation: sideOrientation,
  21552. instance: instance
  21553. };
  21554. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21555. };
  21556. /**
  21557. * Creates a polyhedron mesh.
  21558. * Please consider using the same method from the MeshBuilder class instead.
  21559. * 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
  21560. * to choose the wanted type.
  21561. * The parameter `size` (positive float, default 1) sets the polygon size.
  21562. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21563. * 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`.
  21564. * 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
  21565. * 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)`).
  21566. * 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
  21567. * 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.
  21568. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21569. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21570. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21571. */
  21572. Mesh.CreatePolyhedron = function (name, options, scene) {
  21573. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21574. };
  21575. /**
  21576. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21577. * Please consider using the same method from the MeshBuilder class instead.
  21578. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21579. * 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`).
  21580. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21581. * 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.
  21582. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21583. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21584. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21585. */
  21586. Mesh.CreateIcoSphere = function (name, options, scene) {
  21587. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21588. };
  21589. /**
  21590. * Creates a decal mesh.
  21591. * Please consider using the same method from the MeshBuilder class instead.
  21592. * 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.
  21593. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21594. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21595. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21596. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21597. */
  21598. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21599. var options = {
  21600. position: position,
  21601. normal: normal,
  21602. size: size,
  21603. angle: angle
  21604. };
  21605. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21606. };
  21607. // Skeletons
  21608. /**
  21609. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21610. */
  21611. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21612. var source;
  21613. if (!this._sourcePositions) {
  21614. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21615. this._sourcePositions = new Float32Array(source);
  21616. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21617. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21618. }
  21619. }
  21620. return this._sourcePositions;
  21621. };
  21622. /**
  21623. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21624. */
  21625. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21626. var source;
  21627. if (!this._sourceNormals) {
  21628. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21629. this._sourceNormals = new Float32Array(source);
  21630. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21631. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21632. }
  21633. }
  21634. return this._sourceNormals;
  21635. };
  21636. /**
  21637. * Update the vertex buffers by applying transformation from the bones
  21638. * @param {skeleton} skeleton to apply
  21639. */
  21640. Mesh.prototype.applySkeleton = function (skeleton) {
  21641. if (!this.geometry) {
  21642. return;
  21643. }
  21644. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21645. return;
  21646. }
  21647. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21648. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21649. return this;
  21650. }
  21651. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21652. return this;
  21653. }
  21654. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21655. return this;
  21656. }
  21657. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21658. return this;
  21659. }
  21660. if (!this._sourcePositions) {
  21661. var submeshes = this.subMeshes.slice();
  21662. this.setPositionsForCPUSkinning();
  21663. this.subMeshes = submeshes;
  21664. }
  21665. if (!this._sourceNormals) {
  21666. this.setNormalsForCPUSkinning();
  21667. }
  21668. // positionsData checks for not being Float32Array will only pass at most once
  21669. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21670. if (!(positionsData instanceof Float32Array)) {
  21671. positionsData = new Float32Array(positionsData);
  21672. }
  21673. // normalsData checks for not being Float32Array will only pass at most once
  21674. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21675. if (!(normalsData instanceof Float32Array)) {
  21676. normalsData = new Float32Array(normalsData);
  21677. }
  21678. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21679. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21680. var needExtras = this.numBoneInfluencers > 4;
  21681. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21682. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21683. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21684. var tempVector3 = BABYLON.Vector3.Zero();
  21685. var finalMatrix = new BABYLON.Matrix();
  21686. var tempMatrix = new BABYLON.Matrix();
  21687. var matWeightIdx = 0;
  21688. var inf;
  21689. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21690. var weight;
  21691. for (inf = 0; inf < 4; inf++) {
  21692. weight = matricesWeightsData[matWeightIdx + inf];
  21693. if (weight > 0) {
  21694. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21695. finalMatrix.addToSelf(tempMatrix);
  21696. }
  21697. else
  21698. break;
  21699. }
  21700. if (needExtras) {
  21701. for (inf = 0; inf < 4; inf++) {
  21702. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21703. if (weight > 0) {
  21704. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21705. finalMatrix.addToSelf(tempMatrix);
  21706. }
  21707. else
  21708. break;
  21709. }
  21710. }
  21711. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21712. tempVector3.toArray(positionsData, index);
  21713. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21714. tempVector3.toArray(normalsData, index);
  21715. finalMatrix.reset();
  21716. }
  21717. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21718. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21719. return this;
  21720. };
  21721. // Tools
  21722. /**
  21723. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21724. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21725. */
  21726. Mesh.MinMax = function (meshes) {
  21727. var minVector = null;
  21728. var maxVector = null;
  21729. meshes.forEach(function (mesh, index, array) {
  21730. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21731. if (!minVector) {
  21732. minVector = boundingBox.minimumWorld;
  21733. maxVector = boundingBox.maximumWorld;
  21734. }
  21735. else {
  21736. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21737. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21738. }
  21739. });
  21740. return {
  21741. min: minVector,
  21742. max: maxVector
  21743. };
  21744. };
  21745. /**
  21746. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21747. */
  21748. Mesh.Center = function (meshesOrMinMaxVector) {
  21749. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21750. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21751. };
  21752. /**
  21753. * Merge the array of meshes into a single mesh for performance reasons.
  21754. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21755. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21756. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21757. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21758. */
  21759. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  21760. if (disposeSource === void 0) { disposeSource = true; }
  21761. var index;
  21762. if (!allow32BitsIndices) {
  21763. var totalVertices = 0;
  21764. // Counting vertices
  21765. for (index = 0; index < meshes.length; index++) {
  21766. if (meshes[index]) {
  21767. totalVertices += meshes[index].getTotalVertices();
  21768. if (totalVertices > 65536) {
  21769. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21770. return null;
  21771. }
  21772. }
  21773. }
  21774. }
  21775. // Merge
  21776. var vertexData;
  21777. var otherVertexData;
  21778. var source;
  21779. for (index = 0; index < meshes.length; index++) {
  21780. if (meshes[index]) {
  21781. meshes[index].computeWorldMatrix(true);
  21782. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21783. otherVertexData.transform(meshes[index].getWorldMatrix());
  21784. if (vertexData) {
  21785. vertexData.merge(otherVertexData);
  21786. }
  21787. else {
  21788. vertexData = otherVertexData;
  21789. source = meshes[index];
  21790. }
  21791. }
  21792. }
  21793. if (!meshSubclass) {
  21794. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21795. }
  21796. vertexData.applyToMesh(meshSubclass);
  21797. // Setting properties
  21798. meshSubclass.material = source.material;
  21799. meshSubclass.checkCollisions = source.checkCollisions;
  21800. // Cleaning
  21801. if (disposeSource) {
  21802. for (index = 0; index < meshes.length; index++) {
  21803. if (meshes[index]) {
  21804. meshes[index].dispose();
  21805. }
  21806. }
  21807. }
  21808. return meshSubclass;
  21809. };
  21810. // Consts
  21811. Mesh._FRONTSIDE = 0;
  21812. Mesh._BACKSIDE = 1;
  21813. Mesh._DOUBLESIDE = 2;
  21814. Mesh._DEFAULTSIDE = 0;
  21815. Mesh._NO_CAP = 0;
  21816. Mesh._CAP_START = 1;
  21817. Mesh._CAP_END = 2;
  21818. Mesh._CAP_ALL = 3;
  21819. return Mesh;
  21820. }(BABYLON.AbstractMesh));
  21821. BABYLON.Mesh = Mesh;
  21822. })(BABYLON || (BABYLON = {}));
  21823. //# sourceMappingURL=../Mesh/babylon.mesh.js.map
  21824. var BABYLON;
  21825. (function (BABYLON) {
  21826. var SubMesh = (function () {
  21827. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  21828. if (createBoundingBox === void 0) { createBoundingBox = true; }
  21829. this.materialIndex = materialIndex;
  21830. this.verticesStart = verticesStart;
  21831. this.verticesCount = verticesCount;
  21832. this.indexStart = indexStart;
  21833. this.indexCount = indexCount;
  21834. this._renderId = 0;
  21835. this._mesh = mesh;
  21836. this._renderingMesh = renderingMesh || mesh;
  21837. mesh.subMeshes.push(this);
  21838. this._trianglePlanes = [];
  21839. this._id = mesh.subMeshes.length - 1;
  21840. if (createBoundingBox) {
  21841. this.refreshBoundingInfo();
  21842. mesh.computeWorldMatrix(true);
  21843. }
  21844. }
  21845. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21846. get: function () {
  21847. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21848. },
  21849. enumerable: true,
  21850. configurable: true
  21851. });
  21852. SubMesh.prototype.getBoundingInfo = function () {
  21853. if (this.IsGlobal) {
  21854. return this._mesh.getBoundingInfo();
  21855. }
  21856. return this._boundingInfo;
  21857. };
  21858. SubMesh.prototype.getMesh = function () {
  21859. return this._mesh;
  21860. };
  21861. SubMesh.prototype.getRenderingMesh = function () {
  21862. return this._renderingMesh;
  21863. };
  21864. SubMesh.prototype.getMaterial = function () {
  21865. var rootMaterial = this._renderingMesh.material;
  21866. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  21867. var multiMaterial = rootMaterial;
  21868. return multiMaterial.getSubMaterial(this.materialIndex);
  21869. }
  21870. if (!rootMaterial) {
  21871. return this._mesh.getScene().defaultMaterial;
  21872. }
  21873. return rootMaterial;
  21874. };
  21875. // Methods
  21876. SubMesh.prototype.refreshBoundingInfo = function () {
  21877. this._lastColliderWorldVertices = null;
  21878. if (this.IsGlobal) {
  21879. return;
  21880. }
  21881. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21882. if (!data) {
  21883. this._boundingInfo = this._mesh._boundingInfo;
  21884. return;
  21885. }
  21886. var indices = this._renderingMesh.getIndices();
  21887. var extend;
  21888. //is this the only submesh?
  21889. if (this.indexStart === 0 && this.indexCount === indices.length) {
  21890. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  21891. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  21892. }
  21893. else {
  21894. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  21895. }
  21896. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21897. };
  21898. SubMesh.prototype._checkCollision = function (collider) {
  21899. return this.getBoundingInfo()._checkCollision(collider);
  21900. };
  21901. SubMesh.prototype.updateBoundingInfo = function (world) {
  21902. if (!this.getBoundingInfo()) {
  21903. this.refreshBoundingInfo();
  21904. }
  21905. this.getBoundingInfo().update(world);
  21906. };
  21907. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  21908. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  21909. };
  21910. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21911. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  21912. };
  21913. SubMesh.prototype.render = function (enableAlphaMode) {
  21914. this._renderingMesh.render(this, enableAlphaMode);
  21915. };
  21916. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  21917. if (!this._linesIndexBuffer) {
  21918. var linesIndices = [];
  21919. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21920. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  21921. }
  21922. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  21923. this.linesIndexCount = linesIndices.length;
  21924. }
  21925. return this._linesIndexBuffer;
  21926. };
  21927. SubMesh.prototype.canIntersects = function (ray) {
  21928. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  21929. };
  21930. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  21931. var intersectInfo = null;
  21932. // LineMesh first as it's also a Mesh...
  21933. if (this._mesh instanceof BABYLON.LinesMesh) {
  21934. var lineMesh = this._mesh;
  21935. // Line test
  21936. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  21937. var p0 = positions[indices[index]];
  21938. var p1 = positions[indices[index + 1]];
  21939. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  21940. if (length < 0) {
  21941. continue;
  21942. }
  21943. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  21944. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  21945. if (fastCheck) {
  21946. break;
  21947. }
  21948. }
  21949. }
  21950. }
  21951. else {
  21952. // Triangles test
  21953. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21954. var p0 = positions[indices[index]];
  21955. var p1 = positions[indices[index + 1]];
  21956. var p2 = positions[indices[index + 2]];
  21957. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  21958. if (currentIntersectInfo) {
  21959. if (currentIntersectInfo.distance < 0) {
  21960. continue;
  21961. }
  21962. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21963. intersectInfo = currentIntersectInfo;
  21964. intersectInfo.faceId = index / 3;
  21965. if (fastCheck) {
  21966. break;
  21967. }
  21968. }
  21969. }
  21970. }
  21971. }
  21972. return intersectInfo;
  21973. };
  21974. // Clone
  21975. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  21976. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  21977. if (!this.IsGlobal) {
  21978. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  21979. }
  21980. return result;
  21981. };
  21982. // Dispose
  21983. SubMesh.prototype.dispose = function () {
  21984. if (this._linesIndexBuffer) {
  21985. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  21986. this._linesIndexBuffer = null;
  21987. }
  21988. // Remove from mesh
  21989. var index = this._mesh.subMeshes.indexOf(this);
  21990. this._mesh.subMeshes.splice(index, 1);
  21991. };
  21992. // Statics
  21993. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21994. var minVertexIndex = Number.MAX_VALUE;
  21995. var maxVertexIndex = -Number.MAX_VALUE;
  21996. renderingMesh = renderingMesh || mesh;
  21997. var indices = renderingMesh.getIndices();
  21998. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21999. var vertexIndex = indices[index];
  22000. if (vertexIndex < minVertexIndex)
  22001. minVertexIndex = vertexIndex;
  22002. if (vertexIndex > maxVertexIndex)
  22003. maxVertexIndex = vertexIndex;
  22004. }
  22005. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22006. };
  22007. return SubMesh;
  22008. }());
  22009. BABYLON.SubMesh = SubMesh;
  22010. })(BABYLON || (BABYLON = {}));
  22011. //# sourceMappingURL=../Mesh/babylon.subMesh.js.map
  22012. var BABYLON;
  22013. (function (BABYLON) {
  22014. var MeshBuilder = (function () {
  22015. function MeshBuilder() {
  22016. }
  22017. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  22018. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  22019. return BABYLON.Mesh.DOUBLESIDE;
  22020. }
  22021. if (orientation === undefined || orientation === null) {
  22022. return BABYLON.Mesh.FRONTSIDE;
  22023. }
  22024. return orientation;
  22025. };
  22026. /**
  22027. * Creates a box mesh.
  22028. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  22029. * The parameter `size` sets the size (float) of each box side (default 1).
  22030. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  22031. * 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).
  22032. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  22033. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22034. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22035. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22036. */
  22037. MeshBuilder.CreateBox = function (name, options, scene) {
  22038. var box = new BABYLON.Mesh(name, scene);
  22039. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22040. var vertexData = BABYLON.VertexData.CreateBox(options);
  22041. vertexData.applyToMesh(box, options.updatable);
  22042. return box;
  22043. };
  22044. /**
  22045. * Creates a sphere mesh.
  22046. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  22047. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22048. * 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`).
  22049. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22050. * 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
  22051. * 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).
  22052. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22053. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22054. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22055. */
  22056. MeshBuilder.CreateSphere = function (name, options, scene) {
  22057. var sphere = new BABYLON.Mesh(name, scene);
  22058. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22059. var vertexData = BABYLON.VertexData.CreateSphere(options);
  22060. vertexData.applyToMesh(sphere, options.updatable);
  22061. return sphere;
  22062. };
  22063. /**
  22064. * Creates a plane polygonal mesh. By default, this is a disc.
  22065. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  22066. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22067. * 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.
  22068. * 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
  22069. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22070. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22071. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22072. */
  22073. MeshBuilder.CreateDisc = function (name, options, scene) {
  22074. var disc = new BABYLON.Mesh(name, scene);
  22075. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22076. var vertexData = BABYLON.VertexData.CreateDisc(options);
  22077. vertexData.applyToMesh(disc, options.updatable);
  22078. return disc;
  22079. };
  22080. /**
  22081. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22082. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  22083. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22084. * 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`).
  22085. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22086. * 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.
  22087. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22088. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22089. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22090. */
  22091. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  22092. var sphere = new BABYLON.Mesh(name, scene);
  22093. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22094. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  22095. vertexData.applyToMesh(sphere, options.updatable);
  22096. return sphere;
  22097. };
  22098. ;
  22099. /**
  22100. * Creates a ribbon mesh.
  22101. * 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.
  22102. *
  22103. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22104. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22105. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22106. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22107. * 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.
  22108. * 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.
  22109. * 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
  22110. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22111. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22112. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22113. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22114. */
  22115. MeshBuilder.CreateRibbon = function (name, options, scene) {
  22116. var pathArray = options.pathArray;
  22117. var closeArray = options.closeArray;
  22118. var closePath = options.closePath;
  22119. var offset = options.offset;
  22120. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22121. var instance = options.instance;
  22122. var updatable = options.updatable;
  22123. if (instance) {
  22124. // positionFunction : ribbon case
  22125. // only pathArray and sideOrientation parameters are taken into account for positions update
  22126. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  22127. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  22128. var positionFunction = function (positions) {
  22129. var minlg = pathArray[0].length;
  22130. var i = 0;
  22131. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  22132. for (var si = 1; si <= ns; si++) {
  22133. for (var p = 0; p < pathArray.length; p++) {
  22134. var path = pathArray[p];
  22135. var l = path.length;
  22136. minlg = (minlg < l) ? minlg : l;
  22137. var j = 0;
  22138. while (j < minlg) {
  22139. positions[i] = path[j].x;
  22140. positions[i + 1] = path[j].y;
  22141. positions[i + 2] = path[j].z;
  22142. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  22143. BABYLON.Tmp.Vector3[0].x = path[j].x;
  22144. }
  22145. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  22146. BABYLON.Tmp.Vector3[1].x = path[j].x;
  22147. }
  22148. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  22149. BABYLON.Tmp.Vector3[0].y = path[j].y;
  22150. }
  22151. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  22152. BABYLON.Tmp.Vector3[1].y = path[j].y;
  22153. }
  22154. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  22155. BABYLON.Tmp.Vector3[0].z = path[j].z;
  22156. }
  22157. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  22158. BABYLON.Tmp.Vector3[1].z = path[j].z;
  22159. }
  22160. j++;
  22161. i += 3;
  22162. }
  22163. if (instance._closePath) {
  22164. positions[i] = path[0].x;
  22165. positions[i + 1] = path[0].y;
  22166. positions[i + 2] = path[0].z;
  22167. i += 3;
  22168. }
  22169. }
  22170. }
  22171. };
  22172. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22173. positionFunction(positions);
  22174. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  22175. instance._boundingInfo.update(instance._worldMatrix);
  22176. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22177. if (!(instance.areNormalsFrozen)) {
  22178. var indices = instance.getIndices();
  22179. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22180. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22181. if (instance._closePath) {
  22182. var indexFirst = 0;
  22183. var indexLast = 0;
  22184. for (var p = 0; p < pathArray.length; p++) {
  22185. indexFirst = instance._idx[p] * 3;
  22186. if (p + 1 < pathArray.length) {
  22187. indexLast = (instance._idx[p + 1] - 1) * 3;
  22188. }
  22189. else {
  22190. indexLast = normals.length - 3;
  22191. }
  22192. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  22193. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  22194. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  22195. normals[indexLast] = normals[indexFirst];
  22196. normals[indexLast + 1] = normals[indexFirst + 1];
  22197. normals[indexLast + 2] = normals[indexFirst + 2];
  22198. }
  22199. }
  22200. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22201. }
  22202. return instance;
  22203. }
  22204. else {
  22205. var ribbon = new BABYLON.Mesh(name, scene);
  22206. ribbon.sideOrientation = sideOrientation;
  22207. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  22208. if (closePath) {
  22209. ribbon._idx = vertexData._idx;
  22210. }
  22211. ribbon._closePath = closePath;
  22212. ribbon._closeArray = closeArray;
  22213. vertexData.applyToMesh(ribbon, updatable);
  22214. return ribbon;
  22215. }
  22216. };
  22217. /**
  22218. * Creates a cylinder or a cone mesh.
  22219. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  22220. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22221. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22222. * 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.
  22223. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22224. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22225. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  22226. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  22227. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  22228. * 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).
  22229. * 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
  22230. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  22231. * 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
  22232. * 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.
  22233. * If `enclose` is false, a ring surface is one element.
  22234. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  22235. * 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
  22236. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22237. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22238. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22239. */
  22240. MeshBuilder.CreateCylinder = function (name, options, scene) {
  22241. var cylinder = new BABYLON.Mesh(name, scene);
  22242. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22243. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  22244. vertexData.applyToMesh(cylinder, options.updatable);
  22245. return cylinder;
  22246. };
  22247. /**
  22248. * Creates a torus mesh.
  22249. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  22250. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22251. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22252. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22253. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22254. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22255. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22256. */
  22257. MeshBuilder.CreateTorus = function (name, options, scene) {
  22258. var torus = new BABYLON.Mesh(name, scene);
  22259. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22260. var vertexData = BABYLON.VertexData.CreateTorus(options);
  22261. vertexData.applyToMesh(torus, options.updatable);
  22262. return torus;
  22263. };
  22264. /**
  22265. * Creates a torus knot mesh.
  22266. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  22267. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22268. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22269. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22270. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22271. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22272. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22273. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22274. */
  22275. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  22276. var torusKnot = new BABYLON.Mesh(name, scene);
  22277. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22278. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  22279. vertexData.applyToMesh(torusKnot, options.updatable);
  22280. return torusKnot;
  22281. };
  22282. /**
  22283. * Creates a line system mesh.
  22284. * A line system is a pool of many lines gathered in a single mesh.
  22285. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  22286. * 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.
  22287. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  22288. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  22289. * 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
  22290. * 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
  22291. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  22292. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22293. */
  22294. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  22295. var instance = options.instance;
  22296. var lines = options.lines;
  22297. if (instance) {
  22298. var positionFunction = function (positions) {
  22299. var i = 0;
  22300. for (var l = 0; l < lines.length; l++) {
  22301. var points = lines[l];
  22302. for (var p = 0; p < points.length; p++) {
  22303. positions[i] = points[p].x;
  22304. positions[i + 1] = points[p].y;
  22305. positions[i + 2] = points[p].z;
  22306. i += 3;
  22307. }
  22308. }
  22309. };
  22310. instance.updateMeshPositions(positionFunction, false);
  22311. return instance;
  22312. }
  22313. // line system creation
  22314. var lineSystem = new BABYLON.LinesMesh(name, scene);
  22315. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  22316. vertexData.applyToMesh(lineSystem, options.updatable);
  22317. return lineSystem;
  22318. };
  22319. /**
  22320. * Creates a line mesh.
  22321. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  22322. * 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.
  22323. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22324. * The parameter `points` is an array successive Vector3.
  22325. * 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
  22326. * When updating an instance, remember that only point positions can change, not the number of points.
  22327. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22328. */
  22329. MeshBuilder.CreateLines = function (name, options, scene) {
  22330. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  22331. return lines;
  22332. };
  22333. /**
  22334. * Creates a dashed line mesh.
  22335. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  22336. * 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.
  22337. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22338. * The parameter `points` is an array successive Vector3.
  22339. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22340. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22341. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22342. * 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
  22343. * When updating an instance, remember that only point positions can change, not the number of points.
  22344. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22345. */
  22346. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  22347. var points = options.points;
  22348. var instance = options.instance;
  22349. var gapSize = options.gapSize;
  22350. var dashNb = options.dashNb;
  22351. var dashSize = options.dashSize;
  22352. if (instance) {
  22353. var positionFunction = function (positions) {
  22354. var curvect = BABYLON.Vector3.Zero();
  22355. var nbSeg = positions.length / 6;
  22356. var lg = 0;
  22357. var nb = 0;
  22358. var shft = 0;
  22359. var dashshft = 0;
  22360. var curshft = 0;
  22361. var p = 0;
  22362. var i = 0;
  22363. var j = 0;
  22364. for (i = 0; i < points.length - 1; i++) {
  22365. points[i + 1].subtractToRef(points[i], curvect);
  22366. lg += curvect.length();
  22367. }
  22368. shft = lg / nbSeg;
  22369. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  22370. for (i = 0; i < points.length - 1; i++) {
  22371. points[i + 1].subtractToRef(points[i], curvect);
  22372. nb = Math.floor(curvect.length() / shft);
  22373. curvect.normalize();
  22374. j = 0;
  22375. while (j < nb && p < positions.length) {
  22376. curshft = shft * j;
  22377. positions[p] = points[i].x + curshft * curvect.x;
  22378. positions[p + 1] = points[i].y + curshft * curvect.y;
  22379. positions[p + 2] = points[i].z + curshft * curvect.z;
  22380. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  22381. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  22382. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  22383. p += 6;
  22384. j++;
  22385. }
  22386. }
  22387. while (p < positions.length) {
  22388. positions[p] = points[i].x;
  22389. positions[p + 1] = points[i].y;
  22390. positions[p + 2] = points[i].z;
  22391. p += 3;
  22392. }
  22393. };
  22394. instance.updateMeshPositions(positionFunction, false);
  22395. return instance;
  22396. }
  22397. // dashed lines creation
  22398. var dashedLines = new BABYLON.LinesMesh(name, scene);
  22399. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  22400. vertexData.applyToMesh(dashedLines, options.updatable);
  22401. dashedLines.dashSize = dashSize;
  22402. dashedLines.gapSize = gapSize;
  22403. return dashedLines;
  22404. };
  22405. /**
  22406. * Creates an extruded shape mesh.
  22407. * 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.
  22408. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  22409. *
  22410. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22411. * 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
  22412. * extruded along the Z axis.
  22413. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22414. * 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.
  22415. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22416. * 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
  22417. * 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
  22418. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22419. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22420. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22421. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22422. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22423. */
  22424. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  22425. var path = options.path;
  22426. var shape = options.shape;
  22427. var scale = options.scale || 1;
  22428. var rotation = options.rotation || 0;
  22429. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22430. var updatable = options.updatable;
  22431. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22432. var instance = options.instance;
  22433. var invertUV = options.invertUV || false;
  22434. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  22435. };
  22436. /**
  22437. * Creates an custom extruded shape mesh.
  22438. * 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.
  22439. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  22440. *
  22441. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22442. * 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
  22443. * extruded along the Z axis.
  22444. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22445. * 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
  22446. * and the distance of this point from the begining of the path :
  22447. * ```javascript
  22448. * var rotationFunction = function(i, distance) {
  22449. * // do things
  22450. * return rotationValue; }
  22451. * ```
  22452. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22453. * 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
  22454. * and the distance of this point from the begining of the path :
  22455. * ```javascript
  22456. * var scaleFunction = function(i, distance) {
  22457. * // do things
  22458. * return scaleValue;}
  22459. * ```
  22460. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22461. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22462. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22463. * 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
  22464. * 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
  22465. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22466. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22467. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22468. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22469. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22470. */
  22471. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  22472. var path = options.path;
  22473. var shape = options.shape;
  22474. var scaleFunction = options.scaleFunction || (function () { return 1; });
  22475. var rotationFunction = options.rotationFunction || (function () { return 0; });
  22476. var ribbonCloseArray = options.ribbonCloseArray || false;
  22477. var ribbonClosePath = options.ribbonClosePath || false;
  22478. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22479. var updatable = options.updatable;
  22480. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22481. var instance = options.instance;
  22482. var invertUV = options.invertUV || false;
  22483. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  22484. };
  22485. /**
  22486. * Creates lathe mesh.
  22487. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22488. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  22489. *
  22490. * 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
  22491. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22492. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22493. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22494. * 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.
  22495. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  22496. * 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
  22497. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22498. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22499. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22500. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22501. */
  22502. MeshBuilder.CreateLathe = function (name, options, scene) {
  22503. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  22504. var closed = (options.closed === undefined) ? true : options.closed;
  22505. var shape = options.shape;
  22506. var radius = options.radius || 1;
  22507. var tessellation = options.tessellation || 64;
  22508. var updatable = options.updatable;
  22509. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22510. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22511. var pi2 = Math.PI * 2;
  22512. var paths = new Array();
  22513. var invertUV = options.invertUV || false;
  22514. var i = 0;
  22515. var p = 0;
  22516. var step = pi2 / tessellation * arc;
  22517. var rotated;
  22518. var path = new Array();
  22519. ;
  22520. for (i = 0; i <= tessellation; i++) {
  22521. var path = [];
  22522. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  22523. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  22524. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  22525. }
  22526. for (p = 0; p < shape.length; p++) {
  22527. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  22528. path.push(rotated);
  22529. }
  22530. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  22531. 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));
  22532. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  22533. }
  22534. paths.push(path);
  22535. }
  22536. // lathe ribbon
  22537. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  22538. return lathe;
  22539. };
  22540. /**
  22541. * Creates a plane mesh.
  22542. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22543. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22544. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  22545. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  22546. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22547. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22548. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22549. */
  22550. MeshBuilder.CreatePlane = function (name, options, scene) {
  22551. var plane = new BABYLON.Mesh(name, scene);
  22552. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22553. var vertexData = BABYLON.VertexData.CreatePlane(options);
  22554. vertexData.applyToMesh(plane, options.updatable);
  22555. if (options.sourcePlane) {
  22556. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  22557. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  22558. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  22559. plane.rotate(vectorProduct, product);
  22560. }
  22561. return plane;
  22562. };
  22563. /**
  22564. * Creates a ground mesh.
  22565. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22566. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22567. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22568. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22569. */
  22570. MeshBuilder.CreateGround = function (name, options, scene) {
  22571. var ground = new BABYLON.GroundMesh(name, scene);
  22572. ground._setReady(false);
  22573. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  22574. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  22575. ground._width = options.width || 1;
  22576. ground._height = options.height || 1;
  22577. ground._maxX = ground._width / 2;
  22578. ground._maxZ = ground._height / 2;
  22579. ground._minX = -ground._maxX;
  22580. ground._minZ = -ground._maxZ;
  22581. var vertexData = BABYLON.VertexData.CreateGround(options);
  22582. vertexData.applyToMesh(ground, options.updatable);
  22583. ground._setReady(true);
  22584. return ground;
  22585. };
  22586. /**
  22587. * Creates a tiled ground mesh.
  22588. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  22589. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22590. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22591. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22592. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22593. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22594. * numbers of subdivisions on the ground width and height of each tile.
  22595. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22596. */
  22597. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  22598. var tiledGround = new BABYLON.Mesh(name, scene);
  22599. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  22600. vertexData.applyToMesh(tiledGround, options.updatable);
  22601. return tiledGround;
  22602. };
  22603. /**
  22604. * Creates a ground mesh from a height map.
  22605. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22606. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  22607. * The parameter `url` sets the URL of the height map image resource.
  22608. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22609. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22610. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22611. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22612. * 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).
  22613. * This function is passed the newly built mesh :
  22614. * ```javascript
  22615. * function(mesh) { // do things
  22616. * return; }
  22617. * ```
  22618. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22619. */
  22620. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  22621. var width = options.width || 10.0;
  22622. var height = options.height || 10.0;
  22623. var subdivisions = options.subdivisions || 1 | 0;
  22624. var minHeight = options.minHeight || 0.0;
  22625. var maxHeight = options.maxHeight || 10.0;
  22626. var updatable = options.updatable;
  22627. var onReady = options.onReady;
  22628. var ground = new BABYLON.GroundMesh(name, scene);
  22629. ground._subdivisionsX = subdivisions;
  22630. ground._subdivisionsY = subdivisions;
  22631. ground._width = width;
  22632. ground._height = height;
  22633. ground._maxX = ground._width / 2.0;
  22634. ground._maxZ = ground._height / 2.0;
  22635. ground._minX = -ground._maxX;
  22636. ground._minZ = -ground._maxZ;
  22637. ground._setReady(false);
  22638. var onload = function (img) {
  22639. // Getting height map data
  22640. var canvas = document.createElement("canvas");
  22641. var context = canvas.getContext("2d");
  22642. var bufferWidth = img.width;
  22643. var bufferHeight = img.height;
  22644. canvas.width = bufferWidth;
  22645. canvas.height = bufferHeight;
  22646. context.drawImage(img, 0, 0);
  22647. // Create VertexData from map data
  22648. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22649. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  22650. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  22651. width: width, height: height,
  22652. subdivisions: subdivisions,
  22653. minHeight: minHeight, maxHeight: maxHeight,
  22654. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  22655. });
  22656. vertexData.applyToMesh(ground, updatable);
  22657. ground._setReady(true);
  22658. //execute ready callback, if set
  22659. if (onReady) {
  22660. onReady(ground);
  22661. }
  22662. };
  22663. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22664. return ground;
  22665. };
  22666. /**
  22667. * Creates a tube mesh.
  22668. * 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.
  22669. *
  22670. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  22671. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22672. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22673. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22674. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22675. * 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.
  22676. * It must return a radius value (positive float) :
  22677. * ```javascript
  22678. * var radiusFunction = function(i, distance) {
  22679. * // do things
  22680. * return radius; }
  22681. * ```
  22682. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  22683. * 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
  22684. * 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
  22685. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22686. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22687. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22688. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22689. */
  22690. MeshBuilder.CreateTube = function (name, options, scene) {
  22691. var path = options.path;
  22692. var radius = options.radius || 1.0;
  22693. var tessellation = options.tessellation || 64 | 0;
  22694. var radiusFunction = options.radiusFunction;
  22695. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22696. var invertUV = options.invertUV || false;
  22697. var updatable = options.updatable;
  22698. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22699. var instance = options.instance;
  22700. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  22701. // tube geometry
  22702. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  22703. var tangents = path3D.getTangents();
  22704. var normals = path3D.getNormals();
  22705. var distances = path3D.getDistances();
  22706. var pi2 = Math.PI * 2;
  22707. var step = pi2 / tessellation * arc;
  22708. var returnRadius = function () { return radius; };
  22709. var radiusFunctionFinal = radiusFunction || returnRadius;
  22710. var circlePath;
  22711. var rad;
  22712. var normal;
  22713. var rotated;
  22714. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22715. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22716. for (var i = 0; i < path.length; i++) {
  22717. rad = radiusFunctionFinal(i, distances[i]); // current radius
  22718. circlePath = Array(); // current circle array
  22719. normal = normals[i]; // current normal
  22720. for (var t = 0; t < tessellation; t++) {
  22721. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  22722. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  22723. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  22724. rotated.scaleInPlace(rad).addInPlace(path[i]);
  22725. circlePath[t] = rotated;
  22726. }
  22727. circlePaths[index] = circlePath;
  22728. index++;
  22729. }
  22730. // cap
  22731. var capPath = function (nbPoints, pathIndex) {
  22732. var pointCap = Array();
  22733. for (var i = 0; i < nbPoints; i++) {
  22734. pointCap.push(path[pathIndex]);
  22735. }
  22736. return pointCap;
  22737. };
  22738. switch (cap) {
  22739. case BABYLON.Mesh.NO_CAP:
  22740. break;
  22741. case BABYLON.Mesh.CAP_START:
  22742. circlePaths[0] = capPath(tessellation, 0);
  22743. circlePaths[1] = circlePaths[2].slice(0);
  22744. break;
  22745. case BABYLON.Mesh.CAP_END:
  22746. circlePaths[index] = circlePaths[index - 1].slice(0);
  22747. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22748. break;
  22749. case BABYLON.Mesh.CAP_ALL:
  22750. circlePaths[0] = capPath(tessellation, 0);
  22751. circlePaths[1] = circlePaths[2].slice(0);
  22752. circlePaths[index] = circlePaths[index - 1].slice(0);
  22753. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22754. break;
  22755. default:
  22756. break;
  22757. }
  22758. return circlePaths;
  22759. };
  22760. var path3D;
  22761. var pathArray;
  22762. if (instance) {
  22763. var arc = options.arc || instance.arc;
  22764. path3D = (instance.path3D).update(path);
  22765. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  22766. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  22767. instance.path3D = path3D;
  22768. instance.pathArray = pathArray;
  22769. instance.arc = arc;
  22770. return instance;
  22771. }
  22772. // tube creation
  22773. path3D = new BABYLON.Path3D(path);
  22774. var newPathArray = new Array();
  22775. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22776. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  22777. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  22778. tube.pathArray = pathArray;
  22779. tube.path3D = path3D;
  22780. tube.tessellation = tessellation;
  22781. tube.cap = cap;
  22782. tube.arc = options.arc;
  22783. return tube;
  22784. };
  22785. /**
  22786. * Creates a polyhedron mesh.
  22787. *
  22788. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  22789. * 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
  22790. * to choose the wanted type.
  22791. * The parameter `size` (positive float, default 1) sets the polygon size.
  22792. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22793. * 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`.
  22794. * 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
  22795. * 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)`).
  22796. * 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
  22797. * 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.
  22798. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22799. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22800. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22801. */
  22802. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  22803. var polyhedron = new BABYLON.Mesh(name, scene);
  22804. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22805. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  22806. vertexData.applyToMesh(polyhedron, options.updatable);
  22807. return polyhedron;
  22808. };
  22809. /**
  22810. * Creates a decal mesh.
  22811. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  22812. * 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.
  22813. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22814. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22815. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22816. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22817. */
  22818. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  22819. var indices = sourceMesh.getIndices();
  22820. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22821. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22822. var position = options.position || BABYLON.Vector3.Zero();
  22823. var normal = options.normal || BABYLON.Vector3.Up();
  22824. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  22825. var angle = options.angle || 0;
  22826. // Getting correct rotation
  22827. if (!normal) {
  22828. var target = new BABYLON.Vector3(0, 0, 1);
  22829. var camera = sourceMesh.getScene().activeCamera;
  22830. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  22831. normal = camera.globalPosition.subtract(cameraWorldTarget);
  22832. }
  22833. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  22834. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  22835. var pitch = Math.atan2(normal.y, len);
  22836. // Matrix
  22837. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  22838. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  22839. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  22840. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  22841. var vertexData = new BABYLON.VertexData();
  22842. vertexData.indices = [];
  22843. vertexData.positions = [];
  22844. vertexData.normals = [];
  22845. vertexData.uvs = [];
  22846. var currentVertexDataIndex = 0;
  22847. var extractDecalVector3 = function (indexId) {
  22848. var vertexId = indices[indexId];
  22849. var result = new BABYLON.PositionNormalVertex();
  22850. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  22851. // Send vector to decal local world
  22852. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  22853. // Get normal
  22854. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  22855. return result;
  22856. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  22857. var clip = function (vertices, axis) {
  22858. if (vertices.length === 0) {
  22859. return vertices;
  22860. }
  22861. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  22862. var clipVertices = function (v0, v1) {
  22863. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  22864. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  22865. };
  22866. var result = new Array();
  22867. for (var index = 0; index < vertices.length; index += 3) {
  22868. var v1Out;
  22869. var v2Out;
  22870. var v3Out;
  22871. var total = 0;
  22872. var nV1, nV2, nV3, nV4;
  22873. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  22874. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  22875. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  22876. v1Out = d1 > 0;
  22877. v2Out = d2 > 0;
  22878. v3Out = d3 > 0;
  22879. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  22880. switch (total) {
  22881. case 0:
  22882. result.push(vertices[index]);
  22883. result.push(vertices[index + 1]);
  22884. result.push(vertices[index + 2]);
  22885. break;
  22886. case 1:
  22887. if (v1Out) {
  22888. nV1 = vertices[index + 1];
  22889. nV2 = vertices[index + 2];
  22890. nV3 = clipVertices(vertices[index], nV1);
  22891. nV4 = clipVertices(vertices[index], nV2);
  22892. }
  22893. if (v2Out) {
  22894. nV1 = vertices[index];
  22895. nV2 = vertices[index + 2];
  22896. nV3 = clipVertices(vertices[index + 1], nV1);
  22897. nV4 = clipVertices(vertices[index + 1], nV2);
  22898. result.push(nV3);
  22899. result.push(nV2.clone());
  22900. result.push(nV1.clone());
  22901. result.push(nV2.clone());
  22902. result.push(nV3.clone());
  22903. result.push(nV4);
  22904. break;
  22905. }
  22906. if (v3Out) {
  22907. nV1 = vertices[index];
  22908. nV2 = vertices[index + 1];
  22909. nV3 = clipVertices(vertices[index + 2], nV1);
  22910. nV4 = clipVertices(vertices[index + 2], nV2);
  22911. }
  22912. result.push(nV1.clone());
  22913. result.push(nV2.clone());
  22914. result.push(nV3);
  22915. result.push(nV4);
  22916. result.push(nV3.clone());
  22917. result.push(nV2.clone());
  22918. break;
  22919. case 2:
  22920. if (!v1Out) {
  22921. nV1 = vertices[index].clone();
  22922. nV2 = clipVertices(nV1, vertices[index + 1]);
  22923. nV3 = clipVertices(nV1, vertices[index + 2]);
  22924. result.push(nV1);
  22925. result.push(nV2);
  22926. result.push(nV3);
  22927. }
  22928. if (!v2Out) {
  22929. nV1 = vertices[index + 1].clone();
  22930. nV2 = clipVertices(nV1, vertices[index + 2]);
  22931. nV3 = clipVertices(nV1, vertices[index]);
  22932. result.push(nV1);
  22933. result.push(nV2);
  22934. result.push(nV3);
  22935. }
  22936. if (!v3Out) {
  22937. nV1 = vertices[index + 2].clone();
  22938. nV2 = clipVertices(nV1, vertices[index]);
  22939. nV3 = clipVertices(nV1, vertices[index + 1]);
  22940. result.push(nV1);
  22941. result.push(nV2);
  22942. result.push(nV3);
  22943. }
  22944. break;
  22945. case 3:
  22946. break;
  22947. }
  22948. }
  22949. return result;
  22950. };
  22951. for (var index = 0; index < indices.length; index += 3) {
  22952. var faceVertices = new Array();
  22953. faceVertices.push(extractDecalVector3(index));
  22954. faceVertices.push(extractDecalVector3(index + 1));
  22955. faceVertices.push(extractDecalVector3(index + 2));
  22956. // Clip
  22957. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  22958. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  22959. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  22960. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  22961. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  22962. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  22963. if (faceVertices.length === 0) {
  22964. continue;
  22965. }
  22966. // Add UVs and get back to world
  22967. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  22968. var vertex = faceVertices[vIndex];
  22969. //TODO check for Int32Array
  22970. vertexData.indices.push(currentVertexDataIndex);
  22971. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  22972. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  22973. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  22974. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  22975. currentVertexDataIndex++;
  22976. }
  22977. }
  22978. // Return mesh
  22979. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  22980. vertexData.applyToMesh(decal);
  22981. decal.position = position.clone();
  22982. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  22983. return decal;
  22984. };
  22985. // Privates
  22986. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  22987. // extrusion geometry
  22988. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  22989. var tangents = path3D.getTangents();
  22990. var normals = path3D.getNormals();
  22991. var binormals = path3D.getBinormals();
  22992. var distances = path3D.getDistances();
  22993. var angle = 0;
  22994. var returnScale = function () { return scale; };
  22995. var returnRotation = function () { return rotation; };
  22996. var rotate = custom ? rotateFunction : returnRotation;
  22997. var scl = custom ? scaleFunction : returnScale;
  22998. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22999. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  23000. for (var i = 0; i < curve.length; i++) {
  23001. var shapePath = new Array();
  23002. var angleStep = rotate(i, distances[i]);
  23003. var scaleRatio = scl(i, distances[i]);
  23004. for (var p = 0; p < shape.length; p++) {
  23005. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  23006. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  23007. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  23008. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  23009. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  23010. shapePath[p] = rotated;
  23011. }
  23012. shapePaths[index] = shapePath;
  23013. angle += angleStep;
  23014. index++;
  23015. }
  23016. // cap
  23017. var capPath = function (shapePath) {
  23018. var pointCap = Array();
  23019. var barycenter = BABYLON.Vector3.Zero();
  23020. var i;
  23021. for (i = 0; i < shapePath.length; i++) {
  23022. barycenter.addInPlace(shapePath[i]);
  23023. }
  23024. barycenter.scaleInPlace(1 / shapePath.length);
  23025. for (i = 0; i < shapePath.length; i++) {
  23026. pointCap.push(barycenter);
  23027. }
  23028. return pointCap;
  23029. };
  23030. switch (cap) {
  23031. case BABYLON.Mesh.NO_CAP:
  23032. break;
  23033. case BABYLON.Mesh.CAP_START:
  23034. shapePaths[0] = capPath(shapePaths[2]);
  23035. shapePaths[1] = shapePaths[2].slice(0);
  23036. break;
  23037. case BABYLON.Mesh.CAP_END:
  23038. shapePaths[index] = shapePaths[index - 1];
  23039. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23040. break;
  23041. case BABYLON.Mesh.CAP_ALL:
  23042. shapePaths[0] = capPath(shapePaths[2]);
  23043. shapePaths[1] = shapePaths[2].slice(0);
  23044. shapePaths[index] = shapePaths[index - 1];
  23045. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23046. break;
  23047. default:
  23048. break;
  23049. }
  23050. return shapePaths;
  23051. };
  23052. var path3D;
  23053. var pathArray;
  23054. if (instance) {
  23055. path3D = (instance.path3D).update(curve);
  23056. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  23057. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  23058. return instance;
  23059. }
  23060. // extruded shape creation
  23061. path3D = new BABYLON.Path3D(curve);
  23062. var newShapePaths = new Array();
  23063. cap = (cap < 0 || cap > 3) ? 0 : cap;
  23064. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  23065. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  23066. extrudedGeneric.pathArray = pathArray;
  23067. extrudedGeneric.path3D = path3D;
  23068. extrudedGeneric.cap = cap;
  23069. return extrudedGeneric;
  23070. };
  23071. return MeshBuilder;
  23072. }());
  23073. BABYLON.MeshBuilder = MeshBuilder;
  23074. })(BABYLON || (BABYLON = {}));
  23075. //# sourceMappingURL=../Mesh/babylon.meshBuilder.js.map
  23076. var BABYLON;
  23077. (function (BABYLON) {
  23078. var BaseTexture = (function () {
  23079. function BaseTexture(scene) {
  23080. this.hasAlpha = false;
  23081. this.getAlphaFromRGB = false;
  23082. this.level = 1;
  23083. this.coordinatesIndex = 0;
  23084. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23085. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23086. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23087. this.anisotropicFilteringLevel = 4;
  23088. this.isCube = false;
  23089. this.isRenderTarget = false;
  23090. this.animations = new Array();
  23091. /**
  23092. * An event triggered when the texture is disposed.
  23093. * @type {BABYLON.Observable}
  23094. */
  23095. this.onDisposeObservable = new BABYLON.Observable();
  23096. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23097. this._scene = scene;
  23098. this._scene.textures.push(this);
  23099. this._uid = null;
  23100. }
  23101. Object.defineProperty(BaseTexture.prototype, "uid", {
  23102. get: function () {
  23103. if (!this._uid) {
  23104. this._uid = BABYLON.Tools.RandomId();
  23105. }
  23106. return this._uid;
  23107. },
  23108. enumerable: true,
  23109. configurable: true
  23110. });
  23111. BaseTexture.prototype.toString = function () {
  23112. return this.name;
  23113. };
  23114. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23115. set: function (callback) {
  23116. if (this._onDisposeObserver) {
  23117. this.onDisposeObservable.remove(this._onDisposeObserver);
  23118. }
  23119. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23120. },
  23121. enumerable: true,
  23122. configurable: true
  23123. });
  23124. BaseTexture.prototype.getScene = function () {
  23125. return this._scene;
  23126. };
  23127. BaseTexture.prototype.getTextureMatrix = function () {
  23128. return null;
  23129. };
  23130. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23131. return null;
  23132. };
  23133. BaseTexture.prototype.getInternalTexture = function () {
  23134. return this._texture;
  23135. };
  23136. BaseTexture.prototype.isReady = function () {
  23137. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23138. return true;
  23139. }
  23140. if (this._texture) {
  23141. return this._texture.isReady;
  23142. }
  23143. return false;
  23144. };
  23145. BaseTexture.prototype.getSize = function () {
  23146. if (this._texture._width) {
  23147. return new BABYLON.Size(this._texture._width, this._texture._height);
  23148. }
  23149. if (this._texture._size) {
  23150. return new BABYLON.Size(this._texture._size, this._texture._size);
  23151. }
  23152. return BABYLON.Size.Zero();
  23153. };
  23154. BaseTexture.prototype.getBaseSize = function () {
  23155. if (!this.isReady() || !this._texture)
  23156. return BABYLON.Size.Zero();
  23157. if (this._texture._size) {
  23158. return new BABYLON.Size(this._texture._size, this._texture._size);
  23159. }
  23160. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  23161. };
  23162. BaseTexture.prototype.scale = function (ratio) {
  23163. };
  23164. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  23165. get: function () {
  23166. return false;
  23167. },
  23168. enumerable: true,
  23169. configurable: true
  23170. });
  23171. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  23172. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23173. for (var index = 0; index < texturesCache.length; index++) {
  23174. var texturesCacheEntry = texturesCache[index];
  23175. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  23176. texturesCache.splice(index, 1);
  23177. return;
  23178. }
  23179. }
  23180. };
  23181. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  23182. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23183. for (var index = 0; index < texturesCache.length; index++) {
  23184. var texturesCacheEntry = texturesCache[index];
  23185. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  23186. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  23187. texturesCacheEntry.references++;
  23188. return texturesCacheEntry;
  23189. }
  23190. }
  23191. }
  23192. return null;
  23193. };
  23194. BaseTexture.prototype.delayLoad = function () {
  23195. };
  23196. BaseTexture.prototype.clone = function () {
  23197. return null;
  23198. };
  23199. BaseTexture.prototype.releaseInternalTexture = function () {
  23200. if (this._texture) {
  23201. this._scene.getEngine().releaseInternalTexture(this._texture);
  23202. delete this._texture;
  23203. }
  23204. };
  23205. BaseTexture.prototype.dispose = function () {
  23206. // Animations
  23207. this.getScene().stopAnimation(this);
  23208. // Remove from scene
  23209. var index = this._scene.textures.indexOf(this);
  23210. if (index >= 0) {
  23211. this._scene.textures.splice(index, 1);
  23212. }
  23213. if (this._texture === undefined) {
  23214. return;
  23215. }
  23216. // Release
  23217. this.releaseInternalTexture();
  23218. // Callback
  23219. this.onDisposeObservable.notifyObservers(this);
  23220. this.onDisposeObservable.clear();
  23221. };
  23222. BaseTexture.prototype.serialize = function () {
  23223. if (!this.name) {
  23224. return null;
  23225. }
  23226. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23227. // Animations
  23228. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23229. return serializationObject;
  23230. };
  23231. __decorate([
  23232. BABYLON.serialize()
  23233. ], BaseTexture.prototype, "name", void 0);
  23234. __decorate([
  23235. BABYLON.serialize()
  23236. ], BaseTexture.prototype, "hasAlpha", void 0);
  23237. __decorate([
  23238. BABYLON.serialize()
  23239. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  23240. __decorate([
  23241. BABYLON.serialize()
  23242. ], BaseTexture.prototype, "level", void 0);
  23243. __decorate([
  23244. BABYLON.serialize()
  23245. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  23246. __decorate([
  23247. BABYLON.serialize()
  23248. ], BaseTexture.prototype, "coordinatesMode", void 0);
  23249. __decorate([
  23250. BABYLON.serialize()
  23251. ], BaseTexture.prototype, "wrapU", void 0);
  23252. __decorate([
  23253. BABYLON.serialize()
  23254. ], BaseTexture.prototype, "wrapV", void 0);
  23255. __decorate([
  23256. BABYLON.serialize()
  23257. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  23258. __decorate([
  23259. BABYLON.serialize()
  23260. ], BaseTexture.prototype, "isCube", void 0);
  23261. __decorate([
  23262. BABYLON.serialize()
  23263. ], BaseTexture.prototype, "isRenderTarget", void 0);
  23264. return BaseTexture;
  23265. }());
  23266. BABYLON.BaseTexture = BaseTexture;
  23267. })(BABYLON || (BABYLON = {}));
  23268. //# sourceMappingURL=../../Materials/Textures/babylon.baseTexture.js.map
  23269. var BABYLON;
  23270. (function (BABYLON) {
  23271. var Texture = (function (_super) {
  23272. __extends(Texture, _super);
  23273. function Texture(urlOrList, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  23274. var _this = this;
  23275. if (noMipmap === void 0) { noMipmap = false; }
  23276. if (invertY === void 0) { invertY = true; }
  23277. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23278. if (onLoad === void 0) { onLoad = null; }
  23279. if (onError === void 0) { onError = null; }
  23280. if (buffer === void 0) { buffer = null; }
  23281. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23282. _super.call(this, scene);
  23283. this.uOffset = 0;
  23284. this.vOffset = 0;
  23285. this.uScale = 1.0;
  23286. this.vScale = 1.0;
  23287. this.uAng = 0;
  23288. this.vAng = 0;
  23289. this.wAng = 0;
  23290. var url = ((urlOrList instanceof Array) ? urlOrList[0] : urlOrList);
  23291. this.name = url;
  23292. this.url = url;
  23293. this._delayReloadData = urlOrList;
  23294. this._noMipmap = noMipmap;
  23295. this._invertY = invertY;
  23296. this._samplingMode = samplingMode;
  23297. this._buffer = buffer;
  23298. this._deleteBuffer = deleteBuffer;
  23299. if (!url) {
  23300. return;
  23301. }
  23302. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  23303. var load = function () {
  23304. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  23305. _this.onLoadObservable.notifyObservers(true);
  23306. }
  23307. if (onLoad) {
  23308. onLoad();
  23309. }
  23310. };
  23311. if (!this._texture) {
  23312. if (!scene.useDelayedTextureLoading) {
  23313. this._texture = scene.getEngine().createTexture(urlOrList, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  23314. if (deleteBuffer) {
  23315. delete this._buffer;
  23316. }
  23317. }
  23318. else {
  23319. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23320. this._delayedOnLoad = load;
  23321. this._delayedOnError = onError;
  23322. }
  23323. }
  23324. else {
  23325. if (this._texture.isReady) {
  23326. BABYLON.Tools.SetImmediate(function () { return load(); });
  23327. }
  23328. else {
  23329. this._texture.onLoadedCallbacks.push(load);
  23330. }
  23331. }
  23332. }
  23333. Object.defineProperty(Texture.prototype, "noMipmap", {
  23334. get: function () {
  23335. return this._noMipmap;
  23336. },
  23337. enumerable: true,
  23338. configurable: true
  23339. });
  23340. Texture.prototype.delayLoad = function () {
  23341. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23342. return;
  23343. }
  23344. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23345. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  23346. if (!this._texture) {
  23347. this._texture = this.getScene().getEngine().createTexture(this._delayReloadData, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  23348. if (this._deleteBuffer) {
  23349. delete this._buffer;
  23350. }
  23351. }
  23352. };
  23353. Texture.prototype.updateSamplingMode = function (samplingMode) {
  23354. if (!this._texture) {
  23355. return;
  23356. }
  23357. this._samplingMode = samplingMode;
  23358. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  23359. };
  23360. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  23361. x *= this.uScale;
  23362. y *= this.vScale;
  23363. x -= 0.5 * this.uScale;
  23364. y -= 0.5 * this.vScale;
  23365. z -= 0.5;
  23366. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  23367. t.x += 0.5 * this.uScale + this.uOffset;
  23368. t.y += 0.5 * this.vScale + this.vOffset;
  23369. t.z += 0.5;
  23370. };
  23371. Texture.prototype.getTextureMatrix = function () {
  23372. if (this.uOffset === this._cachedUOffset &&
  23373. this.vOffset === this._cachedVOffset &&
  23374. this.uScale === this._cachedUScale &&
  23375. this.vScale === this._cachedVScale &&
  23376. this.uAng === this._cachedUAng &&
  23377. this.vAng === this._cachedVAng &&
  23378. this.wAng === this._cachedWAng) {
  23379. return this._cachedTextureMatrix;
  23380. }
  23381. this._cachedUOffset = this.uOffset;
  23382. this._cachedVOffset = this.vOffset;
  23383. this._cachedUScale = this.uScale;
  23384. this._cachedVScale = this.vScale;
  23385. this._cachedUAng = this.uAng;
  23386. this._cachedVAng = this.vAng;
  23387. this._cachedWAng = this.wAng;
  23388. if (!this._cachedTextureMatrix) {
  23389. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23390. this._rowGenerationMatrix = new BABYLON.Matrix();
  23391. this._t0 = BABYLON.Vector3.Zero();
  23392. this._t1 = BABYLON.Vector3.Zero();
  23393. this._t2 = BABYLON.Vector3.Zero();
  23394. }
  23395. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  23396. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  23397. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  23398. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  23399. this._t1.subtractInPlace(this._t0);
  23400. this._t2.subtractInPlace(this._t0);
  23401. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23402. this._cachedTextureMatrix.m[0] = this._t1.x;
  23403. this._cachedTextureMatrix.m[1] = this._t1.y;
  23404. this._cachedTextureMatrix.m[2] = this._t1.z;
  23405. this._cachedTextureMatrix.m[4] = this._t2.x;
  23406. this._cachedTextureMatrix.m[5] = this._t2.y;
  23407. this._cachedTextureMatrix.m[6] = this._t2.z;
  23408. this._cachedTextureMatrix.m[8] = this._t0.x;
  23409. this._cachedTextureMatrix.m[9] = this._t0.y;
  23410. this._cachedTextureMatrix.m[10] = this._t0.z;
  23411. return this._cachedTextureMatrix;
  23412. };
  23413. Texture.prototype.getReflectionTextureMatrix = function () {
  23414. if (this.uOffset === this._cachedUOffset &&
  23415. this.vOffset === this._cachedVOffset &&
  23416. this.uScale === this._cachedUScale &&
  23417. this.vScale === this._cachedVScale &&
  23418. this.coordinatesMode === this._cachedCoordinatesMode) {
  23419. return this._cachedTextureMatrix;
  23420. }
  23421. if (!this._cachedTextureMatrix) {
  23422. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23423. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  23424. }
  23425. this._cachedCoordinatesMode = this.coordinatesMode;
  23426. switch (this.coordinatesMode) {
  23427. case Texture.PLANAR_MODE:
  23428. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23429. this._cachedTextureMatrix[0] = this.uScale;
  23430. this._cachedTextureMatrix[5] = this.vScale;
  23431. this._cachedTextureMatrix[12] = this.uOffset;
  23432. this._cachedTextureMatrix[13] = this.vOffset;
  23433. break;
  23434. case Texture.PROJECTION_MODE:
  23435. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  23436. this._projectionModeMatrix.m[0] = 0.5;
  23437. this._projectionModeMatrix.m[5] = -0.5;
  23438. this._projectionModeMatrix.m[10] = 0.0;
  23439. this._projectionModeMatrix.m[12] = 0.5;
  23440. this._projectionModeMatrix.m[13] = 0.5;
  23441. this._projectionModeMatrix.m[14] = 1.0;
  23442. this._projectionModeMatrix.m[15] = 1.0;
  23443. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  23444. break;
  23445. default:
  23446. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23447. break;
  23448. }
  23449. return this._cachedTextureMatrix;
  23450. };
  23451. Texture.prototype.clone = function () {
  23452. var _this = this;
  23453. return BABYLON.SerializationHelper.Clone(function () {
  23454. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  23455. }, this);
  23456. };
  23457. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  23458. get: function () {
  23459. if (!this._onLoadObservarble) {
  23460. this._onLoadObservarble = new BABYLON.Observable();
  23461. }
  23462. return this._onLoadObservarble;
  23463. },
  23464. enumerable: true,
  23465. configurable: true
  23466. });
  23467. // Statics
  23468. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  23469. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23470. if (onLoad === void 0) { onLoad = null; }
  23471. if (onError === void 0) { onError = null; }
  23472. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  23473. };
  23474. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  23475. if (parsedTexture.customType) {
  23476. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  23477. return customTexture.Parse(parsedTexture, scene, rootUrl);
  23478. }
  23479. if (parsedTexture.isCube) {
  23480. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  23481. }
  23482. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  23483. return null;
  23484. }
  23485. var texture = BABYLON.SerializationHelper.Parse(function () {
  23486. if (parsedTexture.mirrorPlane) {
  23487. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23488. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  23489. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  23490. return mirrorTexture;
  23491. }
  23492. else if (parsedTexture.isRenderTarget) {
  23493. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23494. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  23495. return renderTargetTexture;
  23496. }
  23497. else {
  23498. var texture;
  23499. if (parsedTexture.base64String) {
  23500. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  23501. }
  23502. else if (parsedTexture.name instanceof Array) {
  23503. for (var i = 0, len = parsedTexture.name.length; i < len; i++) {
  23504. parsedTexture.name[i] = rootUrl + parsedTexture.name[i];
  23505. }
  23506. texture = new Texture(parsedTexture.name, scene);
  23507. }
  23508. else {
  23509. texture = new Texture(rootUrl + parsedTexture.name, scene);
  23510. }
  23511. return texture;
  23512. }
  23513. }, parsedTexture, scene);
  23514. // Animations
  23515. if (parsedTexture.animations) {
  23516. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23517. var parsedAnimation = parsedTexture.animations[animationIndex];
  23518. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23519. }
  23520. }
  23521. return texture;
  23522. };
  23523. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError) {
  23524. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23525. if (noMipmap === void 0) { noMipmap = false; }
  23526. if (invertY === void 0) { invertY = true; }
  23527. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23528. if (onLoad === void 0) { onLoad = null; }
  23529. if (onError === void 0) { onError = null; }
  23530. if (name.substr(0, 5) !== "data:") {
  23531. name = "data:" + name;
  23532. }
  23533. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer);
  23534. };
  23535. // Constants
  23536. Texture.NEAREST_SAMPLINGMODE = 1;
  23537. Texture.BILINEAR_SAMPLINGMODE = 2;
  23538. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23539. Texture.EXPLICIT_MODE = 0;
  23540. Texture.SPHERICAL_MODE = 1;
  23541. Texture.PLANAR_MODE = 2;
  23542. Texture.CUBIC_MODE = 3;
  23543. Texture.PROJECTION_MODE = 4;
  23544. Texture.SKYBOX_MODE = 5;
  23545. Texture.INVCUBIC_MODE = 6;
  23546. Texture.EQUIRECTANGULAR_MODE = 7;
  23547. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23548. Texture.CLAMP_ADDRESSMODE = 0;
  23549. Texture.WRAP_ADDRESSMODE = 1;
  23550. Texture.MIRROR_ADDRESSMODE = 2;
  23551. __decorate([
  23552. BABYLON.serialize()
  23553. ], Texture.prototype, "url", void 0);
  23554. __decorate([
  23555. BABYLON.serialize()
  23556. ], Texture.prototype, "uOffset", void 0);
  23557. __decorate([
  23558. BABYLON.serialize()
  23559. ], Texture.prototype, "vOffset", void 0);
  23560. __decorate([
  23561. BABYLON.serialize()
  23562. ], Texture.prototype, "uScale", void 0);
  23563. __decorate([
  23564. BABYLON.serialize()
  23565. ], Texture.prototype, "vScale", void 0);
  23566. __decorate([
  23567. BABYLON.serialize()
  23568. ], Texture.prototype, "uAng", void 0);
  23569. __decorate([
  23570. BABYLON.serialize()
  23571. ], Texture.prototype, "vAng", void 0);
  23572. __decorate([
  23573. BABYLON.serialize()
  23574. ], Texture.prototype, "wAng", void 0);
  23575. return Texture;
  23576. }(BABYLON.BaseTexture));
  23577. BABYLON.Texture = Texture;
  23578. })(BABYLON || (BABYLON = {}));
  23579. //# sourceMappingURL=../../Materials/Textures/babylon.texture.js.map
  23580. var BABYLON;
  23581. (function (BABYLON) {
  23582. var CubeTexture = (function (_super) {
  23583. __extends(CubeTexture, _super);
  23584. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  23585. if (onLoad === void 0) { onLoad = null; }
  23586. if (onError === void 0) { onError = null; }
  23587. _super.call(this, scene);
  23588. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  23589. this.name = rootUrl;
  23590. this.url = rootUrl;
  23591. this._noMipmap = noMipmap;
  23592. this.hasAlpha = false;
  23593. if (!rootUrl && !files) {
  23594. return;
  23595. }
  23596. this._texture = this._getFromCache(rootUrl, noMipmap);
  23597. if (!files) {
  23598. if (!extensions) {
  23599. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  23600. }
  23601. files = [];
  23602. for (var index = 0; index < extensions.length; index++) {
  23603. files.push(rootUrl + extensions[index]);
  23604. }
  23605. this._extensions = extensions;
  23606. }
  23607. this._files = files;
  23608. if (!this._texture) {
  23609. if (!scene.useDelayedTextureLoading) {
  23610. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  23611. }
  23612. else {
  23613. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23614. }
  23615. }
  23616. else if (onLoad) {
  23617. if (this._texture.isReady) {
  23618. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  23619. }
  23620. else {
  23621. this._texture.onLoadedCallbacks.push(onLoad);
  23622. }
  23623. }
  23624. this.isCube = true;
  23625. this._textureMatrix = BABYLON.Matrix.Identity();
  23626. }
  23627. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  23628. return new CubeTexture("", scene, null, noMipmap, files);
  23629. };
  23630. // Methods
  23631. CubeTexture.prototype.delayLoad = function () {
  23632. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23633. return;
  23634. }
  23635. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23636. this._texture = this._getFromCache(this.url, this._noMipmap);
  23637. if (!this._texture) {
  23638. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  23639. }
  23640. };
  23641. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  23642. return this._textureMatrix;
  23643. };
  23644. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  23645. var texture = BABYLON.SerializationHelper.Parse(function () {
  23646. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  23647. }, parsedTexture, scene);
  23648. // Animations
  23649. if (parsedTexture.animations) {
  23650. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23651. var parsedAnimation = parsedTexture.animations[animationIndex];
  23652. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23653. }
  23654. }
  23655. return texture;
  23656. };
  23657. CubeTexture.prototype.clone = function () {
  23658. var _this = this;
  23659. return BABYLON.SerializationHelper.Clone(function () {
  23660. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  23661. }, this);
  23662. };
  23663. return CubeTexture;
  23664. }(BABYLON.BaseTexture));
  23665. BABYLON.CubeTexture = CubeTexture;
  23666. })(BABYLON || (BABYLON = {}));
  23667. //# sourceMappingURL=../../Materials/Textures/babylon.cubeTexture.js.map
  23668. var BABYLON;
  23669. (function (BABYLON) {
  23670. var RenderTargetTexture = (function (_super) {
  23671. __extends(RenderTargetTexture, _super);
  23672. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  23673. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  23674. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23675. if (isCube === void 0) { isCube = false; }
  23676. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23677. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  23678. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  23679. _super.call(this, null, scene, !generateMipMaps);
  23680. this.isCube = isCube;
  23681. /**
  23682. * Use this list to define the list of mesh you want to render.
  23683. */
  23684. this.renderList = new Array();
  23685. this.renderParticles = true;
  23686. this.renderSprites = false;
  23687. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  23688. // Events
  23689. /**
  23690. * An event triggered when the texture is unbind.
  23691. * @type {BABYLON.Observable}
  23692. */
  23693. this.onAfterUnbindObservable = new BABYLON.Observable();
  23694. /**
  23695. * An event triggered before rendering the texture
  23696. * @type {BABYLON.Observable}
  23697. */
  23698. this.onBeforeRenderObservable = new BABYLON.Observable();
  23699. /**
  23700. * An event triggered after rendering the texture
  23701. * @type {BABYLON.Observable}
  23702. */
  23703. this.onAfterRenderObservable = new BABYLON.Observable();
  23704. /**
  23705. * An event triggered after the texture clear
  23706. * @type {BABYLON.Observable}
  23707. */
  23708. this.onClearObservable = new BABYLON.Observable();
  23709. this._currentRefreshId = -1;
  23710. this._refreshRate = 1;
  23711. this.name = name;
  23712. this.isRenderTarget = true;
  23713. this._size = size;
  23714. this._generateMipMaps = generateMipMaps;
  23715. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  23716. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  23717. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23718. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23719. }
  23720. if (isCube) {
  23721. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  23722. generateMipMaps: generateMipMaps,
  23723. samplingMode: samplingMode,
  23724. generateDepthBuffer: generateDepthBuffer,
  23725. generateStencilBuffer: generateStencilBuffer
  23726. });
  23727. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  23728. this._textureMatrix = BABYLON.Matrix.Identity();
  23729. }
  23730. else {
  23731. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  23732. generateMipMaps: generateMipMaps,
  23733. type: type,
  23734. samplingMode: samplingMode,
  23735. generateDepthBuffer: generateDepthBuffer,
  23736. generateStencilBuffer: generateStencilBuffer
  23737. });
  23738. }
  23739. // Rendering groups
  23740. this._renderingManager = new BABYLON.RenderingManager(scene);
  23741. }
  23742. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  23743. get: function () {
  23744. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  23745. },
  23746. enumerable: true,
  23747. configurable: true
  23748. });
  23749. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  23750. get: function () {
  23751. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  23752. },
  23753. enumerable: true,
  23754. configurable: true
  23755. });
  23756. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  23757. get: function () {
  23758. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  23759. },
  23760. enumerable: true,
  23761. configurable: true
  23762. });
  23763. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  23764. set: function (callback) {
  23765. if (this._onAfterUnbindObserver) {
  23766. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  23767. }
  23768. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  23769. },
  23770. enumerable: true,
  23771. configurable: true
  23772. });
  23773. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  23774. set: function (callback) {
  23775. if (this._onBeforeRenderObserver) {
  23776. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23777. }
  23778. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23779. },
  23780. enumerable: true,
  23781. configurable: true
  23782. });
  23783. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  23784. set: function (callback) {
  23785. if (this._onAfterRenderObserver) {
  23786. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23787. }
  23788. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23789. },
  23790. enumerable: true,
  23791. configurable: true
  23792. });
  23793. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  23794. set: function (callback) {
  23795. if (this._onClearObserver) {
  23796. this.onClearObservable.remove(this._onClearObserver);
  23797. }
  23798. this._onClearObserver = this.onClearObservable.add(callback);
  23799. },
  23800. enumerable: true,
  23801. configurable: true
  23802. });
  23803. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  23804. this._currentRefreshId = -1;
  23805. };
  23806. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  23807. get: function () {
  23808. return this._refreshRate;
  23809. },
  23810. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23811. set: function (value) {
  23812. this._refreshRate = value;
  23813. this.resetRefreshCounter();
  23814. },
  23815. enumerable: true,
  23816. configurable: true
  23817. });
  23818. RenderTargetTexture.prototype._shouldRender = function () {
  23819. if (this._currentRefreshId === -1) {
  23820. this._currentRefreshId = 1;
  23821. return true;
  23822. }
  23823. if (this.refreshRate === this._currentRefreshId) {
  23824. this._currentRefreshId = 1;
  23825. return true;
  23826. }
  23827. this._currentRefreshId++;
  23828. return false;
  23829. };
  23830. RenderTargetTexture.prototype.isReady = function () {
  23831. if (!this.getScene().renderTargetsEnabled) {
  23832. return false;
  23833. }
  23834. return _super.prototype.isReady.call(this);
  23835. };
  23836. RenderTargetTexture.prototype.getRenderSize = function () {
  23837. return this._size;
  23838. };
  23839. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  23840. get: function () {
  23841. return true;
  23842. },
  23843. enumerable: true,
  23844. configurable: true
  23845. });
  23846. RenderTargetTexture.prototype.scale = function (ratio) {
  23847. var newSize = this._size * ratio;
  23848. this.resize(newSize, this._generateMipMaps);
  23849. };
  23850. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  23851. if (this.isCube) {
  23852. return this._textureMatrix;
  23853. }
  23854. return _super.prototype.getReflectionTextureMatrix.call(this);
  23855. };
  23856. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  23857. this.releaseInternalTexture();
  23858. if (this.isCube) {
  23859. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  23860. }
  23861. else {
  23862. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23863. }
  23864. };
  23865. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  23866. var scene = this.getScene();
  23867. if (this.useCameraPostProcesses !== undefined) {
  23868. useCameraPostProcess = this.useCameraPostProcesses;
  23869. }
  23870. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23871. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  23872. }
  23873. if (this._waitingRenderList) {
  23874. this.renderList = [];
  23875. for (var index = 0; index < this._waitingRenderList.length; index++) {
  23876. var id = this._waitingRenderList[index];
  23877. this.renderList.push(scene.getMeshByID(id));
  23878. }
  23879. delete this._waitingRenderList;
  23880. }
  23881. // Is predicate defined?
  23882. if (this.renderListPredicate) {
  23883. this.renderList.splice(0); // Clear previous renderList
  23884. var sceneMeshes = this.getScene().meshes;
  23885. for (var index = 0; index < sceneMeshes.length; index++) {
  23886. var mesh = sceneMeshes[index];
  23887. if (this.renderListPredicate(mesh)) {
  23888. this.renderList.push(mesh);
  23889. }
  23890. }
  23891. }
  23892. if (this.renderList && this.renderList.length === 0) {
  23893. return;
  23894. }
  23895. // Prepare renderingManager
  23896. this._renderingManager.reset();
  23897. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  23898. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  23899. var sceneRenderId = scene.getRenderId();
  23900. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  23901. var mesh = currentRenderList[meshIndex];
  23902. if (mesh) {
  23903. if (!mesh.isReady()) {
  23904. // Reset _currentRefreshId
  23905. this.resetRefreshCounter();
  23906. continue;
  23907. }
  23908. mesh._preActivateForIntermediateRendering(sceneRenderId);
  23909. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  23910. mesh._activate(sceneRenderId);
  23911. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23912. var subMesh = mesh.subMeshes[subIndex];
  23913. scene._activeIndices.addCount(subMesh.indexCount, false);
  23914. this._renderingManager.dispatch(subMesh);
  23915. }
  23916. }
  23917. }
  23918. }
  23919. if (this.isCube) {
  23920. for (var face = 0; face < 6; face++) {
  23921. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23922. scene.incrementRenderId();
  23923. scene.resetCachedMaterial();
  23924. }
  23925. }
  23926. else {
  23927. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23928. }
  23929. this.onAfterUnbindObservable.notifyObservers(this);
  23930. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23931. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  23932. }
  23933. scene.resetCachedMaterial();
  23934. };
  23935. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  23936. var scene = this.getScene();
  23937. var engine = scene.getEngine();
  23938. // Bind
  23939. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  23940. if (this.isCube) {
  23941. engine.bindFramebuffer(this._texture, faceIndex);
  23942. }
  23943. else {
  23944. engine.bindFramebuffer(this._texture);
  23945. }
  23946. }
  23947. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  23948. // Clear
  23949. if (this.onClearObservable.hasObservers()) {
  23950. this.onClearObservable.notifyObservers(engine);
  23951. }
  23952. else {
  23953. engine.clear(scene.clearColor, true, true, true);
  23954. }
  23955. if (!this._doNotChangeAspectRatio) {
  23956. scene.updateTransformMatrix(true);
  23957. }
  23958. // Render
  23959. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  23960. if (useCameraPostProcess) {
  23961. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  23962. }
  23963. if (!this._doNotChangeAspectRatio) {
  23964. scene.updateTransformMatrix(true);
  23965. }
  23966. this.onAfterRenderObservable.notifyObservers(faceIndex);
  23967. // Dump ?
  23968. if (dumpForDebug) {
  23969. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  23970. }
  23971. // Unbind
  23972. if (!this.isCube || faceIndex === 5) {
  23973. if (this.isCube) {
  23974. if (faceIndex === 5) {
  23975. engine.generateMipMapsForCubemap(this._texture);
  23976. }
  23977. }
  23978. engine.unBindFramebuffer(this._texture, this.isCube);
  23979. }
  23980. };
  23981. /**
  23982. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23983. * This allowed control for front to back rendering or reversly depending of the special needs.
  23984. *
  23985. * @param renderingGroupId The rendering group id corresponding to its index
  23986. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23987. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23988. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23989. */
  23990. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23991. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23992. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23993. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23994. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23995. };
  23996. /**
  23997. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23998. *
  23999. * @param renderingGroupId The rendering group id corresponding to its index
  24000. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24001. */
  24002. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  24003. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  24004. };
  24005. RenderTargetTexture.prototype.clone = function () {
  24006. var textureSize = this.getSize();
  24007. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24008. // Base texture
  24009. newTexture.hasAlpha = this.hasAlpha;
  24010. newTexture.level = this.level;
  24011. // RenderTarget Texture
  24012. newTexture.coordinatesMode = this.coordinatesMode;
  24013. newTexture.renderList = this.renderList.slice(0);
  24014. return newTexture;
  24015. };
  24016. RenderTargetTexture.prototype.serialize = function () {
  24017. if (!this.name) {
  24018. return null;
  24019. }
  24020. var serializationObject = _super.prototype.serialize.call(this);
  24021. serializationObject.renderTargetSize = this.getRenderSize();
  24022. serializationObject.renderList = [];
  24023. for (var index = 0; index < this.renderList.length; index++) {
  24024. serializationObject.renderList.push(this.renderList[index].id);
  24025. }
  24026. return serializationObject;
  24027. };
  24028. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  24029. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  24030. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  24031. return RenderTargetTexture;
  24032. }(BABYLON.Texture));
  24033. BABYLON.RenderTargetTexture = RenderTargetTexture;
  24034. })(BABYLON || (BABYLON = {}));
  24035. //# sourceMappingURL=../../Materials/Textures/babylon.renderTargetTexture.js.map
  24036. var BABYLON;
  24037. (function (BABYLON) {
  24038. var ProceduralTexture = (function (_super) {
  24039. __extends(ProceduralTexture, _super);
  24040. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  24041. if (generateMipMaps === void 0) { generateMipMaps = true; }
  24042. if (isCube === void 0) { isCube = false; }
  24043. _super.call(this, null, scene, !generateMipMaps);
  24044. this.isCube = isCube;
  24045. this.isEnabled = true;
  24046. this._currentRefreshId = -1;
  24047. this._refreshRate = 1;
  24048. this._vertexBuffers = {};
  24049. this._uniforms = new Array();
  24050. this._samplers = new Array();
  24051. this._textures = new Array();
  24052. this._floats = new Array();
  24053. this._floatsArrays = {};
  24054. this._colors3 = new Array();
  24055. this._colors4 = new Array();
  24056. this._vectors2 = new Array();
  24057. this._vectors3 = new Array();
  24058. this._matrices = new Array();
  24059. this._fallbackTextureUsed = false;
  24060. scene._proceduralTextures.push(this);
  24061. this.name = name;
  24062. this.isRenderTarget = true;
  24063. this._size = size;
  24064. this._generateMipMaps = generateMipMaps;
  24065. this.setFragment(fragment);
  24066. this._fallbackTexture = fallbackTexture;
  24067. var engine = scene.getEngine();
  24068. if (isCube) {
  24069. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  24070. this.setFloat("face", 0);
  24071. }
  24072. else {
  24073. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  24074. }
  24075. // VBO
  24076. var vertices = [];
  24077. vertices.push(1, 1);
  24078. vertices.push(-1, 1);
  24079. vertices.push(-1, -1);
  24080. vertices.push(1, -1);
  24081. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  24082. // Indices
  24083. var indices = [];
  24084. indices.push(0);
  24085. indices.push(1);
  24086. indices.push(2);
  24087. indices.push(0);
  24088. indices.push(2);
  24089. indices.push(3);
  24090. this._indexBuffer = engine.createIndexBuffer(indices);
  24091. }
  24092. ProceduralTexture.prototype.reset = function () {
  24093. if (this._effect === undefined) {
  24094. return;
  24095. }
  24096. var engine = this.getScene().getEngine();
  24097. engine._releaseEffect(this._effect);
  24098. };
  24099. ProceduralTexture.prototype.isReady = function () {
  24100. var _this = this;
  24101. var engine = this.getScene().getEngine();
  24102. var shaders;
  24103. if (!this._fragment) {
  24104. return false;
  24105. }
  24106. if (this._fallbackTextureUsed) {
  24107. return true;
  24108. }
  24109. if (this._fragment.fragmentElement !== undefined) {
  24110. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  24111. }
  24112. else {
  24113. shaders = { vertex: "procedural", fragment: this._fragment };
  24114. }
  24115. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  24116. _this.releaseInternalTexture();
  24117. if (_this._fallbackTexture) {
  24118. _this._texture = _this._fallbackTexture._texture;
  24119. _this._texture.references++;
  24120. }
  24121. _this._fallbackTextureUsed = true;
  24122. });
  24123. return this._effect.isReady();
  24124. };
  24125. ProceduralTexture.prototype.resetRefreshCounter = function () {
  24126. this._currentRefreshId = -1;
  24127. };
  24128. ProceduralTexture.prototype.setFragment = function (fragment) {
  24129. this._fragment = fragment;
  24130. };
  24131. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  24132. get: function () {
  24133. return this._refreshRate;
  24134. },
  24135. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  24136. set: function (value) {
  24137. this._refreshRate = value;
  24138. this.resetRefreshCounter();
  24139. },
  24140. enumerable: true,
  24141. configurable: true
  24142. });
  24143. ProceduralTexture.prototype._shouldRender = function () {
  24144. if (!this.isEnabled || !this.isReady() || !this._texture) {
  24145. return false;
  24146. }
  24147. if (this._fallbackTextureUsed) {
  24148. return false;
  24149. }
  24150. if (this._currentRefreshId === -1) {
  24151. this._currentRefreshId = 1;
  24152. return true;
  24153. }
  24154. if (this.refreshRate === this._currentRefreshId) {
  24155. this._currentRefreshId = 1;
  24156. return true;
  24157. }
  24158. this._currentRefreshId++;
  24159. return false;
  24160. };
  24161. ProceduralTexture.prototype.getRenderSize = function () {
  24162. return this._size;
  24163. };
  24164. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  24165. if (this._fallbackTextureUsed) {
  24166. return;
  24167. }
  24168. this.releaseInternalTexture();
  24169. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  24170. };
  24171. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  24172. if (this._uniforms.indexOf(uniformName) === -1) {
  24173. this._uniforms.push(uniformName);
  24174. }
  24175. };
  24176. ProceduralTexture.prototype.setTexture = function (name, texture) {
  24177. if (this._samplers.indexOf(name) === -1) {
  24178. this._samplers.push(name);
  24179. }
  24180. this._textures[name] = texture;
  24181. return this;
  24182. };
  24183. ProceduralTexture.prototype.setFloat = function (name, value) {
  24184. this._checkUniform(name);
  24185. this._floats[name] = value;
  24186. return this;
  24187. };
  24188. ProceduralTexture.prototype.setFloats = function (name, value) {
  24189. this._checkUniform(name);
  24190. this._floatsArrays[name] = value;
  24191. return this;
  24192. };
  24193. ProceduralTexture.prototype.setColor3 = function (name, value) {
  24194. this._checkUniform(name);
  24195. this._colors3[name] = value;
  24196. return this;
  24197. };
  24198. ProceduralTexture.prototype.setColor4 = function (name, value) {
  24199. this._checkUniform(name);
  24200. this._colors4[name] = value;
  24201. return this;
  24202. };
  24203. ProceduralTexture.prototype.setVector2 = function (name, value) {
  24204. this._checkUniform(name);
  24205. this._vectors2[name] = value;
  24206. return this;
  24207. };
  24208. ProceduralTexture.prototype.setVector3 = function (name, value) {
  24209. this._checkUniform(name);
  24210. this._vectors3[name] = value;
  24211. return this;
  24212. };
  24213. ProceduralTexture.prototype.setMatrix = function (name, value) {
  24214. this._checkUniform(name);
  24215. this._matrices[name] = value;
  24216. return this;
  24217. };
  24218. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24219. var scene = this.getScene();
  24220. var engine = scene.getEngine();
  24221. // Render
  24222. engine.enableEffect(this._effect);
  24223. engine.setState(false);
  24224. // Texture
  24225. for (var name in this._textures) {
  24226. this._effect.setTexture(name, this._textures[name]);
  24227. }
  24228. // Float
  24229. for (name in this._floats) {
  24230. this._effect.setFloat(name, this._floats[name]);
  24231. }
  24232. // Floats
  24233. for (name in this._floatsArrays) {
  24234. this._effect.setArray(name, this._floatsArrays[name]);
  24235. }
  24236. // Color3
  24237. for (name in this._colors3) {
  24238. this._effect.setColor3(name, this._colors3[name]);
  24239. }
  24240. // Color4
  24241. for (name in this._colors4) {
  24242. var color = this._colors4[name];
  24243. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  24244. }
  24245. // Vector2
  24246. for (name in this._vectors2) {
  24247. this._effect.setVector2(name, this._vectors2[name]);
  24248. }
  24249. // Vector3
  24250. for (name in this._vectors3) {
  24251. this._effect.setVector3(name, this._vectors3[name]);
  24252. }
  24253. // Matrix
  24254. for (name in this._matrices) {
  24255. this._effect.setMatrix(name, this._matrices[name]);
  24256. }
  24257. // VBOs
  24258. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  24259. if (this.isCube) {
  24260. for (var face = 0; face < 6; face++) {
  24261. engine.bindFramebuffer(this._texture, face);
  24262. this._effect.setFloat("face", face);
  24263. // Clear
  24264. engine.clear(scene.clearColor, true, true, true);
  24265. // Draw order
  24266. engine.draw(true, 0, 6);
  24267. // Mipmaps
  24268. if (face === 5) {
  24269. engine.generateMipMapsForCubemap(this._texture);
  24270. }
  24271. }
  24272. }
  24273. else {
  24274. engine.bindFramebuffer(this._texture);
  24275. // Clear
  24276. engine.clear(scene.clearColor, true, true, true);
  24277. // Draw order
  24278. engine.draw(true, 0, 6);
  24279. }
  24280. // Unbind
  24281. engine.unBindFramebuffer(this._texture, this.isCube);
  24282. if (this.onGenerated) {
  24283. this.onGenerated();
  24284. }
  24285. };
  24286. ProceduralTexture.prototype.clone = function () {
  24287. var textureSize = this.getSize();
  24288. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  24289. // Base texture
  24290. newTexture.hasAlpha = this.hasAlpha;
  24291. newTexture.level = this.level;
  24292. // RenderTarget Texture
  24293. newTexture.coordinatesMode = this.coordinatesMode;
  24294. return newTexture;
  24295. };
  24296. ProceduralTexture.prototype.dispose = function () {
  24297. var index = this.getScene()._proceduralTextures.indexOf(this);
  24298. if (index >= 0) {
  24299. this.getScene()._proceduralTextures.splice(index, 1);
  24300. }
  24301. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  24302. if (vertexBuffer) {
  24303. vertexBuffer.dispose();
  24304. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  24305. }
  24306. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  24307. this._indexBuffer = null;
  24308. }
  24309. _super.prototype.dispose.call(this);
  24310. };
  24311. return ProceduralTexture;
  24312. }(BABYLON.Texture));
  24313. BABYLON.ProceduralTexture = ProceduralTexture;
  24314. })(BABYLON || (BABYLON = {}));
  24315. //# sourceMappingURL=../../../Materials/Textures/Procedurals/babylon.proceduralTexture.js.map
  24316. var BABYLON;
  24317. (function (BABYLON) {
  24318. var MirrorTexture = (function (_super) {
  24319. __extends(MirrorTexture, _super);
  24320. function MirrorTexture(name, size, scene, generateMipMaps) {
  24321. var _this = this;
  24322. _super.call(this, name, size, scene, generateMipMaps, true);
  24323. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  24324. this._transformMatrix = BABYLON.Matrix.Zero();
  24325. this._mirrorMatrix = BABYLON.Matrix.Zero();
  24326. this.onBeforeRenderObservable.add(function () {
  24327. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  24328. _this._savedViewMatrix = scene.getViewMatrix();
  24329. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  24330. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  24331. scene.clipPlane = _this.mirrorPlane;
  24332. scene.getEngine().cullBackFaces = false;
  24333. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  24334. });
  24335. this.onAfterRenderObservable.add(function () {
  24336. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  24337. scene.getEngine().cullBackFaces = true;
  24338. scene._mirroredCameraPosition = null;
  24339. delete scene.clipPlane;
  24340. });
  24341. }
  24342. MirrorTexture.prototype.clone = function () {
  24343. var textureSize = this.getSize();
  24344. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24345. // Base texture
  24346. newTexture.hasAlpha = this.hasAlpha;
  24347. newTexture.level = this.level;
  24348. // Mirror Texture
  24349. newTexture.mirrorPlane = this.mirrorPlane.clone();
  24350. newTexture.renderList = this.renderList.slice(0);
  24351. return newTexture;
  24352. };
  24353. MirrorTexture.prototype.serialize = function () {
  24354. if (!this.name) {
  24355. return null;
  24356. }
  24357. var serializationObject = _super.prototype.serialize.call(this);
  24358. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  24359. return serializationObject;
  24360. };
  24361. return MirrorTexture;
  24362. }(BABYLON.RenderTargetTexture));
  24363. BABYLON.MirrorTexture = MirrorTexture;
  24364. })(BABYLON || (BABYLON = {}));
  24365. //# sourceMappingURL=../../Materials/Textures/babylon.mirrorTexture.js.map
  24366. var BABYLON;
  24367. (function (BABYLON) {
  24368. /**
  24369. * Creates a refraction texture used by refraction channel of the standard material.
  24370. * @param name the texture name
  24371. * @param size size of the underlying texture
  24372. * @param scene root scene
  24373. */
  24374. var RefractionTexture = (function (_super) {
  24375. __extends(RefractionTexture, _super);
  24376. function RefractionTexture(name, size, scene, generateMipMaps) {
  24377. var _this = this;
  24378. _super.call(this, name, size, scene, generateMipMaps, true);
  24379. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  24380. this.depth = 2.0;
  24381. this.onBeforeRenderObservable.add(function () {
  24382. scene.clipPlane = _this.refractionPlane;
  24383. });
  24384. this.onAfterRenderObservable.add(function () {
  24385. delete scene.clipPlane;
  24386. });
  24387. }
  24388. RefractionTexture.prototype.clone = function () {
  24389. var textureSize = this.getSize();
  24390. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24391. // Base texture
  24392. newTexture.hasAlpha = this.hasAlpha;
  24393. newTexture.level = this.level;
  24394. // Refraction Texture
  24395. newTexture.refractionPlane = this.refractionPlane.clone();
  24396. newTexture.renderList = this.renderList.slice(0);
  24397. newTexture.depth = this.depth;
  24398. return newTexture;
  24399. };
  24400. RefractionTexture.prototype.serialize = function () {
  24401. if (!this.name) {
  24402. return null;
  24403. }
  24404. var serializationObject = _super.prototype.serialize.call(this);
  24405. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  24406. serializationObject.depth = this.depth;
  24407. return serializationObject;
  24408. };
  24409. return RefractionTexture;
  24410. }(BABYLON.RenderTargetTexture));
  24411. BABYLON.RefractionTexture = RefractionTexture;
  24412. })(BABYLON || (BABYLON = {}));
  24413. //# sourceMappingURL=../../Materials/Textures/babylon.refractionTexture.js.map
  24414. var BABYLON;
  24415. (function (BABYLON) {
  24416. var DynamicTexture = (function (_super) {
  24417. __extends(DynamicTexture, _super);
  24418. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  24419. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24420. _super.call(this, null, scene, !generateMipMaps);
  24421. this.name = name;
  24422. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24423. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24424. this._generateMipMaps = generateMipMaps;
  24425. if (options.getContext) {
  24426. this._canvas = options;
  24427. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24428. }
  24429. else {
  24430. this._canvas = document.createElement("canvas");
  24431. if (options.width) {
  24432. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24433. }
  24434. else {
  24435. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  24436. }
  24437. }
  24438. var textureSize = this.getSize();
  24439. this._canvas.width = textureSize.width;
  24440. this._canvas.height = textureSize.height;
  24441. this._context = this._canvas.getContext("2d");
  24442. }
  24443. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  24444. get: function () {
  24445. return true;
  24446. },
  24447. enumerable: true,
  24448. configurable: true
  24449. });
  24450. DynamicTexture.prototype.scale = function (ratio) {
  24451. var textureSize = this.getSize();
  24452. textureSize.width *= ratio;
  24453. textureSize.height *= ratio;
  24454. this._canvas.width = textureSize.width;
  24455. this._canvas.height = textureSize.height;
  24456. this.releaseInternalTexture();
  24457. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  24458. };
  24459. DynamicTexture.prototype.getContext = function () {
  24460. return this._context;
  24461. };
  24462. DynamicTexture.prototype.clear = function () {
  24463. var size = this.getSize();
  24464. this._context.fillRect(0, 0, size.width, size.height);
  24465. };
  24466. DynamicTexture.prototype.update = function (invertY) {
  24467. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  24468. };
  24469. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  24470. if (update === void 0) { update = true; }
  24471. var size = this.getSize();
  24472. if (clearColor) {
  24473. this._context.fillStyle = clearColor;
  24474. this._context.fillRect(0, 0, size.width, size.height);
  24475. }
  24476. this._context.font = font;
  24477. if (x === null) {
  24478. var textSize = this._context.measureText(text);
  24479. x = (size.width - textSize.width) / 2;
  24480. }
  24481. this._context.fillStyle = color;
  24482. this._context.fillText(text, x, y);
  24483. if (update) {
  24484. this.update(invertY);
  24485. }
  24486. };
  24487. DynamicTexture.prototype.clone = function () {
  24488. var textureSize = this.getSize();
  24489. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  24490. // Base texture
  24491. newTexture.hasAlpha = this.hasAlpha;
  24492. newTexture.level = this.level;
  24493. // Dynamic Texture
  24494. newTexture.wrapU = this.wrapU;
  24495. newTexture.wrapV = this.wrapV;
  24496. return newTexture;
  24497. };
  24498. return DynamicTexture;
  24499. }(BABYLON.Texture));
  24500. BABYLON.DynamicTexture = DynamicTexture;
  24501. })(BABYLON || (BABYLON = {}));
  24502. //# sourceMappingURL=../../Materials/Textures/babylon.dynamicTexture.js.map
  24503. var BABYLON;
  24504. (function (BABYLON) {
  24505. var VideoTexture = (function (_super) {
  24506. __extends(VideoTexture, _super);
  24507. /**
  24508. * Creates a video texture.
  24509. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  24510. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  24511. * @param {BABYLON.Scene} scene is obviously the current scene.
  24512. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  24513. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  24514. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  24515. */
  24516. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  24517. var _this = this;
  24518. if (generateMipMaps === void 0) { generateMipMaps = false; }
  24519. if (invertY === void 0) { invertY = false; }
  24520. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24521. _super.call(this, null, scene, !generateMipMaps, invertY);
  24522. this._autoLaunch = true;
  24523. var urls;
  24524. this.name = name;
  24525. if (urlsOrVideo instanceof HTMLVideoElement) {
  24526. this.video = urlsOrVideo;
  24527. }
  24528. else {
  24529. urls = urlsOrVideo;
  24530. this.video = document.createElement("video");
  24531. this.video.autoplay = false;
  24532. this.video.loop = true;
  24533. }
  24534. this._generateMipMaps = generateMipMaps;
  24535. this._samplingMode = samplingMode;
  24536. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  24537. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24538. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24539. }
  24540. else {
  24541. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24542. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24543. this._generateMipMaps = false;
  24544. }
  24545. if (urls) {
  24546. this.video.addEventListener("canplaythrough", function () {
  24547. _this._createTexture();
  24548. });
  24549. urls.forEach(function (url) {
  24550. var source = document.createElement("source");
  24551. source.src = url;
  24552. _this.video.appendChild(source);
  24553. });
  24554. }
  24555. else {
  24556. this._createTexture();
  24557. }
  24558. this._lastUpdate = BABYLON.Tools.Now;
  24559. }
  24560. VideoTexture.prototype._createTexture = function () {
  24561. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  24562. this._texture.isReady = true;
  24563. };
  24564. VideoTexture.prototype.update = function () {
  24565. if (this._autoLaunch) {
  24566. this._autoLaunch = false;
  24567. this.video.play();
  24568. }
  24569. var now = BABYLON.Tools.Now;
  24570. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  24571. return false;
  24572. }
  24573. this._lastUpdate = now;
  24574. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  24575. return true;
  24576. };
  24577. return VideoTexture;
  24578. }(BABYLON.Texture));
  24579. BABYLON.VideoTexture = VideoTexture;
  24580. })(BABYLON || (BABYLON = {}));
  24581. //# sourceMappingURL=../../Materials/Textures/babylon.videoTexture.js.map
  24582. var BABYLON;
  24583. (function (BABYLON) {
  24584. var CustomProceduralTexture = (function (_super) {
  24585. __extends(CustomProceduralTexture, _super);
  24586. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  24587. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  24588. this._animate = true;
  24589. this._time = 0;
  24590. this._texturePath = texturePath;
  24591. //Try to load json
  24592. this.loadJson(texturePath);
  24593. this.refreshRate = 1;
  24594. }
  24595. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  24596. var _this = this;
  24597. var that = this;
  24598. function noConfigFile() {
  24599. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  24600. try {
  24601. that.setFragment(that._texturePath);
  24602. }
  24603. catch (ex) {
  24604. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  24605. }
  24606. }
  24607. var configFileUrl = jsonUrl + "/config.json";
  24608. var xhr = new XMLHttpRequest();
  24609. xhr.open("GET", configFileUrl, true);
  24610. xhr.addEventListener("load", function () {
  24611. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  24612. try {
  24613. _this._config = JSON.parse(xhr.response);
  24614. _this.updateShaderUniforms();
  24615. _this.updateTextures();
  24616. _this.setFragment(_this._texturePath + "/custom");
  24617. _this._animate = _this._config.animate;
  24618. _this.refreshRate = _this._config.refreshrate;
  24619. }
  24620. catch (ex) {
  24621. noConfigFile();
  24622. }
  24623. }
  24624. else {
  24625. noConfigFile();
  24626. }
  24627. }, false);
  24628. xhr.addEventListener("error", function () {
  24629. noConfigFile();
  24630. }, false);
  24631. try {
  24632. xhr.send();
  24633. }
  24634. catch (ex) {
  24635. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  24636. }
  24637. };
  24638. CustomProceduralTexture.prototype.isReady = function () {
  24639. if (!_super.prototype.isReady.call(this)) {
  24640. return false;
  24641. }
  24642. for (var name in this._textures) {
  24643. var texture = this._textures[name];
  24644. if (!texture.isReady()) {
  24645. return false;
  24646. }
  24647. }
  24648. return true;
  24649. };
  24650. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24651. if (this._animate) {
  24652. this._time += this.getScene().getAnimationRatio() * 0.03;
  24653. this.updateShaderUniforms();
  24654. }
  24655. _super.prototype.render.call(this, useCameraPostProcess);
  24656. };
  24657. CustomProceduralTexture.prototype.updateTextures = function () {
  24658. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  24659. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  24660. }
  24661. };
  24662. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  24663. if (this._config) {
  24664. for (var j = 0; j < this._config.uniforms.length; j++) {
  24665. var uniform = this._config.uniforms[j];
  24666. switch (uniform.type) {
  24667. case "float":
  24668. this.setFloat(uniform.name, uniform.value);
  24669. break;
  24670. case "color3":
  24671. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  24672. break;
  24673. case "color4":
  24674. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  24675. break;
  24676. case "vector2":
  24677. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  24678. break;
  24679. case "vector3":
  24680. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  24681. break;
  24682. }
  24683. }
  24684. }
  24685. this.setFloat("time", this._time);
  24686. };
  24687. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  24688. get: function () {
  24689. return this._animate;
  24690. },
  24691. set: function (value) {
  24692. this._animate = value;
  24693. },
  24694. enumerable: true,
  24695. configurable: true
  24696. });
  24697. return CustomProceduralTexture;
  24698. }(BABYLON.ProceduralTexture));
  24699. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  24700. })(BABYLON || (BABYLON = {}));
  24701. //# sourceMappingURL=../../../Materials/Textures/Procedurals/babylon.customProceduralTexture.js.map
  24702. var BABYLON;
  24703. (function (BABYLON) {
  24704. var EffectFallbacks = (function () {
  24705. function EffectFallbacks() {
  24706. this._defines = {};
  24707. this._currentRank = 32;
  24708. this._maxRank = -1;
  24709. }
  24710. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24711. if (!this._defines[rank]) {
  24712. if (rank < this._currentRank) {
  24713. this._currentRank = rank;
  24714. }
  24715. if (rank > this._maxRank) {
  24716. this._maxRank = rank;
  24717. }
  24718. this._defines[rank] = new Array();
  24719. }
  24720. this._defines[rank].push(define);
  24721. };
  24722. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24723. this._meshRank = rank;
  24724. this._mesh = mesh;
  24725. if (rank > this._maxRank) {
  24726. this._maxRank = rank;
  24727. }
  24728. };
  24729. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24730. get: function () {
  24731. return this._currentRank <= this._maxRank;
  24732. },
  24733. enumerable: true,
  24734. configurable: true
  24735. });
  24736. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24737. var currentFallbacks = this._defines[this._currentRank];
  24738. for (var index = 0; index < currentFallbacks.length; index++) {
  24739. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24740. }
  24741. if (this._mesh && this._currentRank === this._meshRank) {
  24742. this._mesh.computeBonesUsingShaders = false;
  24743. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24744. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24745. }
  24746. this._currentRank++;
  24747. return currentDefines;
  24748. };
  24749. return EffectFallbacks;
  24750. }());
  24751. BABYLON.EffectFallbacks = EffectFallbacks;
  24752. var Effect = (function () {
  24753. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24754. var _this = this;
  24755. this._isReady = false;
  24756. this._compilationError = "";
  24757. this._valueCache = {};
  24758. this._engine = engine;
  24759. this.name = baseName;
  24760. this.defines = defines;
  24761. this._uniformsNames = uniformsNames.concat(samplers);
  24762. this._samplers = samplers;
  24763. this._attributesNames = attributesNames;
  24764. this.onError = onError;
  24765. this.onCompiled = onCompiled;
  24766. this._indexParameters = indexParameters;
  24767. var vertexSource;
  24768. var fragmentSource;
  24769. if (baseName.vertexElement) {
  24770. vertexSource = document.getElementById(baseName.vertexElement);
  24771. if (!vertexSource) {
  24772. vertexSource = baseName.vertexElement;
  24773. }
  24774. }
  24775. else {
  24776. vertexSource = baseName.vertex || baseName;
  24777. }
  24778. if (baseName.fragmentElement) {
  24779. fragmentSource = document.getElementById(baseName.fragmentElement);
  24780. if (!fragmentSource) {
  24781. fragmentSource = baseName.fragmentElement;
  24782. }
  24783. }
  24784. else {
  24785. fragmentSource = baseName.fragment || baseName;
  24786. }
  24787. this._loadVertexShader(vertexSource, function (vertexCode) {
  24788. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24789. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24790. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24791. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  24792. });
  24793. });
  24794. });
  24795. });
  24796. }
  24797. // Properties
  24798. Effect.prototype.isReady = function () {
  24799. return this._isReady;
  24800. };
  24801. Effect.prototype.getProgram = function () {
  24802. return this._program;
  24803. };
  24804. Effect.prototype.getAttributesNames = function () {
  24805. return this._attributesNames;
  24806. };
  24807. Effect.prototype.getAttributeLocation = function (index) {
  24808. return this._attributes[index];
  24809. };
  24810. Effect.prototype.getAttributeLocationByName = function (name) {
  24811. var index = this._attributesNames.indexOf(name);
  24812. return this._attributes[index];
  24813. };
  24814. Effect.prototype.getAttributesCount = function () {
  24815. return this._attributes.length;
  24816. };
  24817. Effect.prototype.getUniformIndex = function (uniformName) {
  24818. return this._uniformsNames.indexOf(uniformName);
  24819. };
  24820. Effect.prototype.getUniform = function (uniformName) {
  24821. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24822. };
  24823. Effect.prototype.getSamplers = function () {
  24824. return this._samplers;
  24825. };
  24826. Effect.prototype.getCompilationError = function () {
  24827. return this._compilationError;
  24828. };
  24829. Effect.prototype.getVertexShaderSource = function () {
  24830. return this._engine.getVertexShaderSource(this._program);
  24831. };
  24832. Effect.prototype.getFragmentShaderSource = function () {
  24833. return this._engine.getFragmentShaderSource(this._program);
  24834. };
  24835. // Methods
  24836. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24837. // DOM element ?
  24838. if (vertex instanceof HTMLElement) {
  24839. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24840. callback(vertexCode);
  24841. return;
  24842. }
  24843. // Base64 encoded ?
  24844. if (vertex.substr(0, 7) === "base64:") {
  24845. var vertexBinary = window.atob(vertex.substr(7));
  24846. callback(vertexBinary);
  24847. return;
  24848. }
  24849. // Is in local store ?
  24850. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24851. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24852. return;
  24853. }
  24854. var vertexShaderUrl;
  24855. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24856. vertexShaderUrl = vertex;
  24857. }
  24858. else {
  24859. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24860. }
  24861. // Vertex shader
  24862. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24863. };
  24864. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24865. // DOM element ?
  24866. if (fragment instanceof HTMLElement) {
  24867. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24868. callback(fragmentCode);
  24869. return;
  24870. }
  24871. // Base64 encoded ?
  24872. if (fragment.substr(0, 7) === "base64:") {
  24873. var fragmentBinary = window.atob(fragment.substr(7));
  24874. callback(fragmentBinary);
  24875. return;
  24876. }
  24877. // Is in local store ?
  24878. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24879. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24880. return;
  24881. }
  24882. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24883. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24884. return;
  24885. }
  24886. var fragmentShaderUrl;
  24887. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24888. fragmentShaderUrl = fragment;
  24889. }
  24890. else {
  24891. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24892. }
  24893. // Fragment shader
  24894. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24895. };
  24896. Effect.prototype._dumpShadersName = function () {
  24897. if (this.name.vertexElement) {
  24898. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  24899. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  24900. }
  24901. else if (this.name.vertex) {
  24902. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  24903. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  24904. }
  24905. else {
  24906. BABYLON.Tools.Error("Vertex shader:" + this.name);
  24907. BABYLON.Tools.Error("Fragment shader:" + this.name);
  24908. }
  24909. };
  24910. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24911. var _this = this;
  24912. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24913. var match = regex.exec(sourceCode);
  24914. var returnValue = new String(sourceCode);
  24915. while (match != null) {
  24916. var includeFile = match[1];
  24917. if (Effect.IncludesShadersStore[includeFile]) {
  24918. // Substitution
  24919. var includeContent = Effect.IncludesShadersStore[includeFile];
  24920. if (match[2]) {
  24921. var splits = match[3].split(",");
  24922. for (var index = 0; index < splits.length; index += 2) {
  24923. var source = new RegExp(splits[index], "g");
  24924. var dest = splits[index + 1];
  24925. includeContent = includeContent.replace(source, dest);
  24926. }
  24927. }
  24928. if (match[4]) {
  24929. var indexString = match[5];
  24930. if (indexString.indexOf("..") !== -1) {
  24931. var indexSplits = indexString.split("..");
  24932. var minIndex = parseInt(indexSplits[0]);
  24933. var maxIndex = parseInt(indexSplits[1]);
  24934. var sourceIncludeContent = includeContent.slice(0);
  24935. includeContent = "";
  24936. if (isNaN(maxIndex)) {
  24937. maxIndex = this._indexParameters[indexSplits[1]];
  24938. }
  24939. for (var i = minIndex; i <= maxIndex; i++) {
  24940. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24941. }
  24942. }
  24943. else {
  24944. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24945. }
  24946. }
  24947. // Replace
  24948. returnValue = returnValue.replace(match[0], includeContent);
  24949. }
  24950. else {
  24951. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24952. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24953. Effect.IncludesShadersStore[includeFile] = fileContent;
  24954. _this._processIncludes(returnValue, callback);
  24955. });
  24956. return;
  24957. }
  24958. match = regex.exec(sourceCode);
  24959. }
  24960. callback(returnValue);
  24961. };
  24962. Effect.prototype._processPrecision = function (source) {
  24963. if (source.indexOf("precision highp float") === -1) {
  24964. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24965. source = "precision mediump float;\n" + source;
  24966. }
  24967. else {
  24968. source = "precision highp float;\n" + source;
  24969. }
  24970. }
  24971. else {
  24972. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24973. source = source.replace("precision highp float", "precision mediump float");
  24974. }
  24975. }
  24976. return source;
  24977. };
  24978. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  24979. try {
  24980. var engine = this._engine;
  24981. // Precision
  24982. vertexSourceCode = this._processPrecision(vertexSourceCode);
  24983. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  24984. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  24985. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24986. this._attributes = engine.getAttributes(this._program, attributesNames);
  24987. var index;
  24988. for (index = 0; index < this._samplers.length; index++) {
  24989. var sampler = this.getUniform(this._samplers[index]);
  24990. if (sampler == null) {
  24991. this._samplers.splice(index, 1);
  24992. index--;
  24993. }
  24994. }
  24995. engine.bindSamplers(this);
  24996. this._compilationError = "";
  24997. this._isReady = true;
  24998. if (this.onCompiled) {
  24999. this.onCompiled(this);
  25000. }
  25001. }
  25002. catch (e) {
  25003. this._compilationError = e.message;
  25004. // Let's go through fallbacks then
  25005. BABYLON.Tools.Error("Unable to compile effect: ");
  25006. BABYLON.Tools.Error("Defines: " + defines);
  25007. BABYLON.Tools.Error("Error: " + this._compilationError);
  25008. this._dumpShadersName();
  25009. if (fallbacks && fallbacks.isMoreFallbacks) {
  25010. BABYLON.Tools.Error("Trying next fallback.");
  25011. defines = fallbacks.reduce(defines);
  25012. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  25013. }
  25014. else {
  25015. if (this.onError) {
  25016. this.onError(this, this._compilationError);
  25017. }
  25018. }
  25019. }
  25020. };
  25021. Object.defineProperty(Effect.prototype, "isSupported", {
  25022. get: function () {
  25023. return this._compilationError === "";
  25024. },
  25025. enumerable: true,
  25026. configurable: true
  25027. });
  25028. Effect.prototype._bindTexture = function (channel, texture) {
  25029. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  25030. };
  25031. Effect.prototype.setTexture = function (channel, texture) {
  25032. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  25033. };
  25034. Effect.prototype.setTextureArray = function (channel, textures) {
  25035. if (this._samplers.indexOf(channel + "Ex") === -1) {
  25036. var initialPos = this._samplers.indexOf(channel);
  25037. for (var index = 1; index < textures.length; index++) {
  25038. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  25039. }
  25040. }
  25041. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  25042. };
  25043. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  25044. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  25045. };
  25046. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  25047. var changed = false;
  25048. var cache = this._valueCache[uniformName];
  25049. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  25050. changed = true;
  25051. cache = new BABYLON.Matrix();
  25052. }
  25053. var tm = cache.m;
  25054. var om = matrix.m;
  25055. for (var index = 0; index < 16; index++) {
  25056. if (tm[index] !== om[index]) {
  25057. tm[index] = om[index];
  25058. changed = true;
  25059. }
  25060. }
  25061. this._valueCache[uniformName] = cache;
  25062. return changed;
  25063. };
  25064. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  25065. var cache = this._valueCache[uniformName];
  25066. if (!cache) {
  25067. cache = [x, y];
  25068. this._valueCache[uniformName] = cache;
  25069. return true;
  25070. }
  25071. var changed = false;
  25072. if (cache[0] !== x) {
  25073. cache[0] = x;
  25074. changed = true;
  25075. }
  25076. if (cache[1] !== y) {
  25077. cache[1] = y;
  25078. changed = true;
  25079. }
  25080. return changed;
  25081. };
  25082. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  25083. var cache = this._valueCache[uniformName];
  25084. if (!cache) {
  25085. cache = [x, y, z];
  25086. this._valueCache[uniformName] = cache;
  25087. return true;
  25088. }
  25089. var changed = false;
  25090. if (cache[0] !== x) {
  25091. cache[0] = x;
  25092. changed = true;
  25093. }
  25094. if (cache[1] !== y) {
  25095. cache[1] = y;
  25096. changed = true;
  25097. }
  25098. if (cache[2] !== z) {
  25099. cache[2] = z;
  25100. changed = true;
  25101. }
  25102. return changed;
  25103. };
  25104. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  25105. var cache = this._valueCache[uniformName];
  25106. if (!cache) {
  25107. cache = [x, y, z, w];
  25108. this._valueCache[uniformName] = cache;
  25109. return true;
  25110. }
  25111. var changed = false;
  25112. if (cache[0] !== x) {
  25113. cache[0] = x;
  25114. changed = true;
  25115. }
  25116. if (cache[1] !== y) {
  25117. cache[1] = y;
  25118. changed = true;
  25119. }
  25120. if (cache[2] !== z) {
  25121. cache[2] = z;
  25122. changed = true;
  25123. }
  25124. if (cache[3] !== w) {
  25125. cache[3] = w;
  25126. changed = true;
  25127. }
  25128. return changed;
  25129. };
  25130. Effect.prototype.setIntArray = function (uniformName, array) {
  25131. this._valueCache[uniformName] = null;
  25132. this._engine.setIntArray(this.getUniform(uniformName), array);
  25133. return this;
  25134. };
  25135. Effect.prototype.setIntArray2 = function (uniformName, array) {
  25136. this._valueCache[uniformName] = null;
  25137. this._engine.setIntArray2(this.getUniform(uniformName), array);
  25138. return this;
  25139. };
  25140. Effect.prototype.setIntArray3 = function (uniformName, array) {
  25141. this._valueCache[uniformName] = null;
  25142. this._engine.setIntArray3(this.getUniform(uniformName), array);
  25143. return this;
  25144. };
  25145. Effect.prototype.setIntArray4 = function (uniformName, array) {
  25146. this._valueCache[uniformName] = null;
  25147. this._engine.setIntArray4(this.getUniform(uniformName), array);
  25148. return this;
  25149. };
  25150. Effect.prototype.setFloatArray = function (uniformName, array) {
  25151. this._valueCache[uniformName] = null;
  25152. this._engine.setFloatArray(this.getUniform(uniformName), array);
  25153. return this;
  25154. };
  25155. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  25156. this._valueCache[uniformName] = null;
  25157. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  25158. return this;
  25159. };
  25160. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  25161. this._valueCache[uniformName] = null;
  25162. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  25163. return this;
  25164. };
  25165. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  25166. this._valueCache[uniformName] = null;
  25167. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  25168. return this;
  25169. };
  25170. Effect.prototype.setArray = function (uniformName, array) {
  25171. this._valueCache[uniformName] = null;
  25172. this._engine.setArray(this.getUniform(uniformName), array);
  25173. return this;
  25174. };
  25175. Effect.prototype.setArray2 = function (uniformName, array) {
  25176. this._valueCache[uniformName] = null;
  25177. this._engine.setArray2(this.getUniform(uniformName), array);
  25178. return this;
  25179. };
  25180. Effect.prototype.setArray3 = function (uniformName, array) {
  25181. this._valueCache[uniformName] = null;
  25182. this._engine.setArray3(this.getUniform(uniformName), array);
  25183. return this;
  25184. };
  25185. Effect.prototype.setArray4 = function (uniformName, array) {
  25186. this._valueCache[uniformName] = null;
  25187. this._engine.setArray4(this.getUniform(uniformName), array);
  25188. return this;
  25189. };
  25190. Effect.prototype.setMatrices = function (uniformName, matrices) {
  25191. this._valueCache[uniformName] = null;
  25192. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  25193. return this;
  25194. };
  25195. Effect.prototype.setMatrix = function (uniformName, matrix) {
  25196. if (this._cacheMatrix(uniformName, matrix)) {
  25197. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  25198. }
  25199. return this;
  25200. };
  25201. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  25202. this._valueCache[uniformName] = null;
  25203. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  25204. return this;
  25205. };
  25206. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  25207. this._valueCache[uniformName] = null;
  25208. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  25209. return this;
  25210. };
  25211. Effect.prototype.setFloat = function (uniformName, value) {
  25212. var cache = this._valueCache[uniformName];
  25213. if (cache !== undefined && cache === value)
  25214. return this;
  25215. this._valueCache[uniformName] = value;
  25216. this._engine.setFloat(this.getUniform(uniformName), value);
  25217. return this;
  25218. };
  25219. Effect.prototype.setBool = function (uniformName, bool) {
  25220. var cache = this._valueCache[uniformName];
  25221. if (cache !== undefined && cache === bool)
  25222. return this;
  25223. this._valueCache[uniformName] = bool;
  25224. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  25225. return this;
  25226. };
  25227. Effect.prototype.setVector2 = function (uniformName, vector2) {
  25228. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  25229. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  25230. }
  25231. return this;
  25232. };
  25233. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  25234. if (this._cacheFloat2(uniformName, x, y)) {
  25235. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  25236. }
  25237. return this;
  25238. };
  25239. Effect.prototype.setVector3 = function (uniformName, vector3) {
  25240. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  25241. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  25242. }
  25243. return this;
  25244. };
  25245. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  25246. if (this._cacheFloat3(uniformName, x, y, z)) {
  25247. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  25248. }
  25249. return this;
  25250. };
  25251. Effect.prototype.setVector4 = function (uniformName, vector4) {
  25252. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  25253. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  25254. }
  25255. return this;
  25256. };
  25257. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  25258. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  25259. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  25260. }
  25261. return this;
  25262. };
  25263. Effect.prototype.setColor3 = function (uniformName, color3) {
  25264. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  25265. this._engine.setColor3(this.getUniform(uniformName), color3);
  25266. }
  25267. return this;
  25268. };
  25269. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  25270. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  25271. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25272. }
  25273. return this;
  25274. };
  25275. // Statics
  25276. Effect.ShadersStore = {};
  25277. Effect.IncludesShadersStore = {};
  25278. return Effect;
  25279. }());
  25280. BABYLON.Effect = Effect;
  25281. })(BABYLON || (BABYLON = {}));
  25282. //# sourceMappingURL=../Materials/babylon.effect.js.map
  25283. var BABYLON;
  25284. (function (BABYLON) {
  25285. var MaterialHelper = (function () {
  25286. function MaterialHelper() {
  25287. }
  25288. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  25289. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25290. var lightIndex = 0;
  25291. var needNormals = false;
  25292. var needRebuild = false;
  25293. var needShadows = false;
  25294. var lightmapMode = false;
  25295. for (var index = 0; index < scene.lights.length; index++) {
  25296. var light = scene.lights[index];
  25297. if (!light.isEnabled()) {
  25298. continue;
  25299. }
  25300. // Excluded check
  25301. if (light._excludedMeshesIds.length > 0) {
  25302. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  25303. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  25304. if (excludedMesh) {
  25305. light.excludedMeshes.push(excludedMesh);
  25306. }
  25307. }
  25308. light._excludedMeshesIds = [];
  25309. }
  25310. // Included check
  25311. if (light._includedOnlyMeshesIds.length > 0) {
  25312. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  25313. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  25314. if (includedOnlyMesh) {
  25315. light.includedOnlyMeshes.push(includedOnlyMesh);
  25316. }
  25317. }
  25318. light._includedOnlyMeshesIds = [];
  25319. }
  25320. if (!light.canAffectMesh(mesh)) {
  25321. continue;
  25322. }
  25323. needNormals = true;
  25324. if (defines["LIGHT" + lightIndex] === undefined) {
  25325. needRebuild = true;
  25326. }
  25327. defines["LIGHT" + lightIndex] = true;
  25328. var type;
  25329. if (light instanceof BABYLON.SpotLight) {
  25330. type = "SPOTLIGHT" + lightIndex;
  25331. }
  25332. else if (light instanceof BABYLON.HemisphericLight) {
  25333. type = "HEMILIGHT" + lightIndex;
  25334. }
  25335. else if (light instanceof BABYLON.PointLight) {
  25336. type = "POINTLIGHT" + lightIndex;
  25337. }
  25338. else {
  25339. type = "DIRLIGHT" + lightIndex;
  25340. }
  25341. if (defines[type] === undefined) {
  25342. needRebuild = true;
  25343. }
  25344. defines[type] = true;
  25345. // Specular
  25346. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  25347. defines["SPECULARTERM"] = true;
  25348. }
  25349. // Shadows
  25350. if (scene.shadowsEnabled) {
  25351. var shadowGenerator = light.getShadowGenerator();
  25352. if (mesh && mesh.receiveShadows && shadowGenerator) {
  25353. if (defines["SHADOW" + lightIndex] === undefined) {
  25354. needRebuild = true;
  25355. }
  25356. defines["SHADOW" + lightIndex] = true;
  25357. defines["SHADOWS"] = true;
  25358. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  25359. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  25360. needRebuild = true;
  25361. }
  25362. defines["SHADOWVSM" + lightIndex] = true;
  25363. }
  25364. if (shadowGenerator.usePoissonSampling) {
  25365. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  25366. needRebuild = true;
  25367. }
  25368. defines["SHADOWPCF" + lightIndex] = true;
  25369. }
  25370. needShadows = true;
  25371. }
  25372. }
  25373. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25374. lightmapMode = true;
  25375. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  25376. needRebuild = true;
  25377. }
  25378. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  25379. needRebuild = true;
  25380. }
  25381. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25382. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  25383. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  25384. }
  25385. }
  25386. lightIndex++;
  25387. if (lightIndex === maxSimultaneousLights)
  25388. break;
  25389. }
  25390. var caps = scene.getEngine().getCaps();
  25391. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  25392. if (defines["SHADOWFULLFLOAT"] === undefined) {
  25393. needRebuild = true;
  25394. }
  25395. defines["SHADOWFULLFLOAT"] = true;
  25396. }
  25397. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  25398. needRebuild = true;
  25399. }
  25400. if (lightmapMode) {
  25401. defines["LIGHTMAPEXCLUDED"] = true;
  25402. }
  25403. if (needRebuild) {
  25404. defines.rebuild();
  25405. }
  25406. return needNormals;
  25407. };
  25408. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  25409. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25410. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25411. if (!defines["LIGHT" + lightIndex]) {
  25412. break;
  25413. }
  25414. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  25415. samplersList.push("shadowSampler" + lightIndex);
  25416. }
  25417. };
  25418. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25419. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25420. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25421. if (!defines["LIGHT" + lightIndex]) {
  25422. break;
  25423. }
  25424. if (lightIndex > 0) {
  25425. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25426. }
  25427. if (defines["SHADOW" + lightIndex]) {
  25428. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25429. }
  25430. if (defines["SHADOWPCF" + lightIndex]) {
  25431. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25432. }
  25433. if (defines["SHADOWVSM" + lightIndex]) {
  25434. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  25435. }
  25436. }
  25437. };
  25438. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25439. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25440. fallbacks.addCPUSkinningFallback(0, mesh);
  25441. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25442. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25443. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25444. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25445. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25446. }
  25447. }
  25448. };
  25449. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25450. if (defines["INSTANCES"]) {
  25451. attribs.push("world0");
  25452. attribs.push("world1");
  25453. attribs.push("world2");
  25454. attribs.push("world3");
  25455. }
  25456. };
  25457. // Bindings
  25458. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  25459. var shadowGenerator = light.getShadowGenerator();
  25460. if (mesh.receiveShadows && shadowGenerator) {
  25461. if (!light.needCube()) {
  25462. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  25463. }
  25464. else {
  25465. if (!depthValuesAlreadySet) {
  25466. depthValuesAlreadySet = true;
  25467. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  25468. }
  25469. }
  25470. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  25471. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  25472. }
  25473. return depthValuesAlreadySet;
  25474. };
  25475. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25476. if (light instanceof BABYLON.PointLight) {
  25477. // Point Light
  25478. light.transferToEffect(effect, "vLightData" + lightIndex);
  25479. }
  25480. else if (light instanceof BABYLON.DirectionalLight) {
  25481. // Directional Light
  25482. light.transferToEffect(effect, "vLightData" + lightIndex);
  25483. }
  25484. else if (light instanceof BABYLON.SpotLight) {
  25485. // Spot Light
  25486. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  25487. }
  25488. else if (light instanceof BABYLON.HemisphericLight) {
  25489. // Hemispheric Light
  25490. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  25491. }
  25492. };
  25493. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  25494. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25495. var lightIndex = 0;
  25496. var depthValuesAlreadySet = false;
  25497. for (var index = 0; index < scene.lights.length; index++) {
  25498. var light = scene.lights[index];
  25499. if (!light.isEnabled()) {
  25500. continue;
  25501. }
  25502. if (!light.canAffectMesh(mesh)) {
  25503. continue;
  25504. }
  25505. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25506. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  25507. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  25508. if (defines["SPECULARTERM"]) {
  25509. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  25510. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  25511. }
  25512. // Shadows
  25513. if (scene.shadowsEnabled) {
  25514. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  25515. }
  25516. lightIndex++;
  25517. if (lightIndex === maxSimultaneousLights)
  25518. break;
  25519. }
  25520. };
  25521. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25522. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25523. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25524. effect.setColor3("vFogColor", scene.fogColor);
  25525. }
  25526. };
  25527. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25528. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25529. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25530. if (matrices) {
  25531. effect.setMatrices("mBones", matrices);
  25532. }
  25533. }
  25534. };
  25535. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25536. if (defines["LOGARITHMICDEPTH"]) {
  25537. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25538. }
  25539. };
  25540. MaterialHelper.BindClipPlane = function (effect, scene) {
  25541. if (scene.clipPlane) {
  25542. var clipPlane = scene.clipPlane;
  25543. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25544. }
  25545. };
  25546. return MaterialHelper;
  25547. }());
  25548. BABYLON.MaterialHelper = MaterialHelper;
  25549. })(BABYLON || (BABYLON = {}));
  25550. //# sourceMappingURL=../Materials/babylon.materialHelper.js.map
  25551. var BABYLON;
  25552. (function (BABYLON) {
  25553. var FresnelParameters = (function () {
  25554. function FresnelParameters() {
  25555. this.isEnabled = true;
  25556. this.leftColor = BABYLON.Color3.White();
  25557. this.rightColor = BABYLON.Color3.Black();
  25558. this.bias = 0;
  25559. this.power = 1;
  25560. }
  25561. FresnelParameters.prototype.clone = function () {
  25562. var newFresnelParameters = new FresnelParameters();
  25563. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  25564. return newFresnelParameters;
  25565. };
  25566. FresnelParameters.prototype.serialize = function () {
  25567. var serializationObject = {};
  25568. serializationObject.isEnabled = this.isEnabled;
  25569. serializationObject.leftColor = this.leftColor;
  25570. serializationObject.rightColor = this.rightColor;
  25571. serializationObject.bias = this.bias;
  25572. serializationObject.power = this.power;
  25573. return serializationObject;
  25574. };
  25575. FresnelParameters.Parse = function (parsedFresnelParameters) {
  25576. var fresnelParameters = new FresnelParameters();
  25577. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  25578. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  25579. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  25580. fresnelParameters.bias = parsedFresnelParameters.bias;
  25581. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  25582. return fresnelParameters;
  25583. };
  25584. return FresnelParameters;
  25585. }());
  25586. BABYLON.FresnelParameters = FresnelParameters;
  25587. })(BABYLON || (BABYLON = {}));
  25588. //# sourceMappingURL=../Materials/babylon.fresnelParameters.js.map
  25589. var BABYLON;
  25590. (function (BABYLON) {
  25591. var MaterialDefines = (function () {
  25592. function MaterialDefines() {
  25593. }
  25594. MaterialDefines.prototype.rebuild = function () {
  25595. if (this._keys) {
  25596. delete this._keys;
  25597. }
  25598. this._keys = Object.keys(this);
  25599. };
  25600. MaterialDefines.prototype.isEqual = function (other) {
  25601. if (this._keys.length !== other._keys.length) {
  25602. return false;
  25603. }
  25604. for (var index = 0; index < this._keys.length; index++) {
  25605. var prop = this._keys[index];
  25606. if (this[prop] !== other[prop]) {
  25607. return false;
  25608. }
  25609. }
  25610. return true;
  25611. };
  25612. MaterialDefines.prototype.cloneTo = function (other) {
  25613. if (this._keys.length !== other._keys.length) {
  25614. other._keys = this._keys.slice(0);
  25615. }
  25616. for (var index = 0; index < this._keys.length; index++) {
  25617. var prop = this._keys[index];
  25618. other[prop] = this[prop];
  25619. }
  25620. };
  25621. MaterialDefines.prototype.reset = function () {
  25622. for (var index = 0; index < this._keys.length; index++) {
  25623. var prop = this._keys[index];
  25624. if (typeof (this[prop]) === "number") {
  25625. this[prop] = 0;
  25626. }
  25627. else {
  25628. this[prop] = false;
  25629. }
  25630. }
  25631. };
  25632. MaterialDefines.prototype.toString = function () {
  25633. var result = "";
  25634. for (var index = 0; index < this._keys.length; index++) {
  25635. var prop = this._keys[index];
  25636. if (typeof (this[prop]) === "number") {
  25637. result += "#define " + prop + " " + this[prop] + "\n";
  25638. }
  25639. else if (this[prop]) {
  25640. result += "#define " + prop + "\n";
  25641. }
  25642. }
  25643. return result;
  25644. };
  25645. return MaterialDefines;
  25646. }());
  25647. BABYLON.MaterialDefines = MaterialDefines;
  25648. var Material = (function () {
  25649. function Material(name, scene, doNotAdd) {
  25650. this.checkReadyOnEveryCall = false;
  25651. this.checkReadyOnlyOnce = false;
  25652. this.state = "";
  25653. this.alpha = 1.0;
  25654. this.backFaceCulling = true;
  25655. this.doNotSerialize = false;
  25656. /**
  25657. * An event triggered when the material is disposed.
  25658. * @type {BABYLON.Observable}
  25659. */
  25660. this.onDisposeObservable = new BABYLON.Observable();
  25661. /**
  25662. * An event triggered when the material is bound.
  25663. * @type {BABYLON.Observable}
  25664. */
  25665. this.onBindObservable = new BABYLON.Observable();
  25666. /**
  25667. * An event triggered when the material is unbound.
  25668. * @type {BABYLON.Observable}
  25669. */
  25670. this.onUnBindObservable = new BABYLON.Observable();
  25671. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25672. this.disableDepthWrite = false;
  25673. this.fogEnabled = true;
  25674. this.pointSize = 1.0;
  25675. this.zOffset = 0;
  25676. this._wasPreviouslyReady = false;
  25677. this._fillMode = Material.TriangleFillMode;
  25678. this.name = name;
  25679. this.id = name;
  25680. this._scene = scene;
  25681. if (scene.useRightHandedSystem) {
  25682. this.sideOrientation = Material.ClockWiseSideOrientation;
  25683. }
  25684. else {
  25685. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25686. }
  25687. if (!doNotAdd) {
  25688. scene.materials.push(this);
  25689. }
  25690. }
  25691. Object.defineProperty(Material, "TriangleFillMode", {
  25692. get: function () {
  25693. return Material._TriangleFillMode;
  25694. },
  25695. enumerable: true,
  25696. configurable: true
  25697. });
  25698. Object.defineProperty(Material, "WireFrameFillMode", {
  25699. get: function () {
  25700. return Material._WireFrameFillMode;
  25701. },
  25702. enumerable: true,
  25703. configurable: true
  25704. });
  25705. Object.defineProperty(Material, "PointFillMode", {
  25706. get: function () {
  25707. return Material._PointFillMode;
  25708. },
  25709. enumerable: true,
  25710. configurable: true
  25711. });
  25712. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25713. get: function () {
  25714. return Material._ClockWiseSideOrientation;
  25715. },
  25716. enumerable: true,
  25717. configurable: true
  25718. });
  25719. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25720. get: function () {
  25721. return Material._CounterClockWiseSideOrientation;
  25722. },
  25723. enumerable: true,
  25724. configurable: true
  25725. });
  25726. Object.defineProperty(Material.prototype, "onDispose", {
  25727. set: function (callback) {
  25728. if (this._onDisposeObserver) {
  25729. this.onDisposeObservable.remove(this._onDisposeObserver);
  25730. }
  25731. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25732. },
  25733. enumerable: true,
  25734. configurable: true
  25735. });
  25736. Object.defineProperty(Material.prototype, "onBind", {
  25737. set: function (callback) {
  25738. if (this._onBindObserver) {
  25739. this.onBindObservable.remove(this._onBindObserver);
  25740. }
  25741. this._onBindObserver = this.onBindObservable.add(callback);
  25742. },
  25743. enumerable: true,
  25744. configurable: true
  25745. });
  25746. Object.defineProperty(Material.prototype, "wireframe", {
  25747. get: function () {
  25748. return this._fillMode === Material.WireFrameFillMode;
  25749. },
  25750. set: function (value) {
  25751. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25752. },
  25753. enumerable: true,
  25754. configurable: true
  25755. });
  25756. Object.defineProperty(Material.prototype, "pointsCloud", {
  25757. get: function () {
  25758. return this._fillMode === Material.PointFillMode;
  25759. },
  25760. set: function (value) {
  25761. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25762. },
  25763. enumerable: true,
  25764. configurable: true
  25765. });
  25766. Object.defineProperty(Material.prototype, "fillMode", {
  25767. get: function () {
  25768. return this._fillMode;
  25769. },
  25770. set: function (value) {
  25771. this._fillMode = value;
  25772. },
  25773. enumerable: true,
  25774. configurable: true
  25775. });
  25776. /**
  25777. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25778. * subclasses should override adding information pertainent to themselves
  25779. */
  25780. Material.prototype.toString = function (fullDetails) {
  25781. var ret = "Name: " + this.name;
  25782. if (fullDetails) {
  25783. }
  25784. return ret;
  25785. };
  25786. Object.defineProperty(Material.prototype, "isFrozen", {
  25787. get: function () {
  25788. return this.checkReadyOnlyOnce;
  25789. },
  25790. enumerable: true,
  25791. configurable: true
  25792. });
  25793. Material.prototype.freeze = function () {
  25794. this.checkReadyOnlyOnce = true;
  25795. };
  25796. Material.prototype.unfreeze = function () {
  25797. this.checkReadyOnlyOnce = false;
  25798. };
  25799. Material.prototype.isReady = function (mesh, useInstances) {
  25800. return true;
  25801. };
  25802. Material.prototype.getEffect = function () {
  25803. return this._effect;
  25804. };
  25805. Material.prototype.getScene = function () {
  25806. return this._scene;
  25807. };
  25808. Material.prototype.needAlphaBlending = function () {
  25809. return (this.alpha < 1.0);
  25810. };
  25811. Material.prototype.needAlphaTesting = function () {
  25812. return false;
  25813. };
  25814. Material.prototype.getAlphaTestTexture = function () {
  25815. return null;
  25816. };
  25817. Material.prototype.markDirty = function () {
  25818. this._wasPreviouslyReady = false;
  25819. };
  25820. Material.prototype._preBind = function () {
  25821. var engine = this._scene.getEngine();
  25822. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25823. engine.enableEffect(this._effect);
  25824. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25825. };
  25826. Material.prototype.bind = function (world, mesh) {
  25827. this._scene._cachedMaterial = this;
  25828. this.onBindObservable.notifyObservers(mesh);
  25829. if (this.disableDepthWrite) {
  25830. var engine = this._scene.getEngine();
  25831. this._cachedDepthWriteState = engine.getDepthWrite();
  25832. engine.setDepthWrite(false);
  25833. }
  25834. };
  25835. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25836. };
  25837. Material.prototype.unbind = function () {
  25838. this.onUnBindObservable.notifyObservers(this);
  25839. if (this.disableDepthWrite) {
  25840. var engine = this._scene.getEngine();
  25841. engine.setDepthWrite(this._cachedDepthWriteState);
  25842. }
  25843. };
  25844. Material.prototype.clone = function (name) {
  25845. return null;
  25846. };
  25847. Material.prototype.getBindedMeshes = function () {
  25848. var result = new Array();
  25849. for (var index = 0; index < this._scene.meshes.length; index++) {
  25850. var mesh = this._scene.meshes[index];
  25851. if (mesh.material === this) {
  25852. result.push(mesh);
  25853. }
  25854. }
  25855. return result;
  25856. };
  25857. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25858. // Animations
  25859. this.getScene().stopAnimation(this);
  25860. // Remove from scene
  25861. var index = this._scene.materials.indexOf(this);
  25862. if (index >= 0) {
  25863. this._scene.materials.splice(index, 1);
  25864. }
  25865. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25866. if (forceDisposeEffect && this._effect) {
  25867. this._scene.getEngine()._releaseEffect(this._effect);
  25868. this._effect = null;
  25869. }
  25870. // Remove from meshes
  25871. for (index = 0; index < this._scene.meshes.length; index++) {
  25872. var mesh = this._scene.meshes[index];
  25873. if (mesh.material === this) {
  25874. mesh.material = null;
  25875. }
  25876. }
  25877. // Callback
  25878. this.onDisposeObservable.notifyObservers(this);
  25879. this.onDisposeObservable.clear();
  25880. this.onBindObservable.clear();
  25881. this.onUnBindObservable.clear();
  25882. };
  25883. Material.prototype.serialize = function () {
  25884. return BABYLON.SerializationHelper.Serialize(this);
  25885. };
  25886. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25887. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25888. multiMaterial.id = parsedMultiMaterial.id;
  25889. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25890. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25891. var subMatId = parsedMultiMaterial.materials[matIndex];
  25892. if (subMatId) {
  25893. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25894. }
  25895. else {
  25896. multiMaterial.subMaterials.push(null);
  25897. }
  25898. }
  25899. return multiMaterial;
  25900. };
  25901. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25902. if (!parsedMaterial.customType) {
  25903. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25904. }
  25905. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25906. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25907. ;
  25908. };
  25909. Material._TriangleFillMode = 0;
  25910. Material._WireFrameFillMode = 1;
  25911. Material._PointFillMode = 2;
  25912. Material._ClockWiseSideOrientation = 0;
  25913. Material._CounterClockWiseSideOrientation = 1;
  25914. __decorate([
  25915. BABYLON.serialize()
  25916. ], Material.prototype, "id", void 0);
  25917. __decorate([
  25918. BABYLON.serialize()
  25919. ], Material.prototype, "name", void 0);
  25920. __decorate([
  25921. BABYLON.serialize()
  25922. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25923. __decorate([
  25924. BABYLON.serialize()
  25925. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25926. __decorate([
  25927. BABYLON.serialize()
  25928. ], Material.prototype, "state", void 0);
  25929. __decorate([
  25930. BABYLON.serialize()
  25931. ], Material.prototype, "alpha", void 0);
  25932. __decorate([
  25933. BABYLON.serialize()
  25934. ], Material.prototype, "backFaceCulling", void 0);
  25935. __decorate([
  25936. BABYLON.serialize()
  25937. ], Material.prototype, "sideOrientation", void 0);
  25938. __decorate([
  25939. BABYLON.serialize()
  25940. ], Material.prototype, "alphaMode", void 0);
  25941. __decorate([
  25942. BABYLON.serialize()
  25943. ], Material.prototype, "disableDepthWrite", void 0);
  25944. __decorate([
  25945. BABYLON.serialize()
  25946. ], Material.prototype, "fogEnabled", void 0);
  25947. __decorate([
  25948. BABYLON.serialize()
  25949. ], Material.prototype, "pointSize", void 0);
  25950. __decorate([
  25951. BABYLON.serialize()
  25952. ], Material.prototype, "zOffset", void 0);
  25953. __decorate([
  25954. BABYLON.serialize()
  25955. ], Material.prototype, "wireframe", null);
  25956. __decorate([
  25957. BABYLON.serialize()
  25958. ], Material.prototype, "pointsCloud", null);
  25959. __decorate([
  25960. BABYLON.serialize()
  25961. ], Material.prototype, "fillMode", null);
  25962. return Material;
  25963. }());
  25964. BABYLON.Material = Material;
  25965. })(BABYLON || (BABYLON = {}));
  25966. //# sourceMappingURL=../Materials/babylon.material.js.map
  25967. var BABYLON;
  25968. (function (BABYLON) {
  25969. var StandardMaterialDefines = (function (_super) {
  25970. __extends(StandardMaterialDefines, _super);
  25971. function StandardMaterialDefines() {
  25972. _super.call(this);
  25973. this.DIFFUSE = false;
  25974. this.AMBIENT = false;
  25975. this.OPACITY = false;
  25976. this.OPACITYRGB = false;
  25977. this.REFLECTION = false;
  25978. this.EMISSIVE = false;
  25979. this.SPECULAR = false;
  25980. this.BUMP = false;
  25981. this.PARALLAX = false;
  25982. this.PARALLAXOCCLUSION = false;
  25983. this.SPECULAROVERALPHA = false;
  25984. this.CLIPPLANE = false;
  25985. this.ALPHATEST = false;
  25986. this.ALPHAFROMDIFFUSE = false;
  25987. this.POINTSIZE = false;
  25988. this.FOG = false;
  25989. this.SPECULARTERM = false;
  25990. this.DIFFUSEFRESNEL = false;
  25991. this.OPACITYFRESNEL = false;
  25992. this.REFLECTIONFRESNEL = false;
  25993. this.REFRACTIONFRESNEL = false;
  25994. this.EMISSIVEFRESNEL = false;
  25995. this.FRESNEL = false;
  25996. this.NORMAL = false;
  25997. this.UV1 = false;
  25998. this.UV2 = false;
  25999. this.VERTEXCOLOR = false;
  26000. this.VERTEXALPHA = false;
  26001. this.NUM_BONE_INFLUENCERS = 0;
  26002. this.BonesPerMesh = 0;
  26003. this.INSTANCES = false;
  26004. this.GLOSSINESS = false;
  26005. this.ROUGHNESS = false;
  26006. this.EMISSIVEASILLUMINATION = false;
  26007. this.LINKEMISSIVEWITHDIFFUSE = false;
  26008. this.REFLECTIONFRESNELFROMSPECULAR = false;
  26009. this.LIGHTMAP = false;
  26010. this.USELIGHTMAPASSHADOWMAP = false;
  26011. this.REFLECTIONMAP_3D = false;
  26012. this.REFLECTIONMAP_SPHERICAL = false;
  26013. this.REFLECTIONMAP_PLANAR = false;
  26014. this.REFLECTIONMAP_CUBIC = false;
  26015. this.REFLECTIONMAP_PROJECTION = false;
  26016. this.REFLECTIONMAP_SKYBOX = false;
  26017. this.REFLECTIONMAP_EXPLICIT = false;
  26018. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  26019. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  26020. this.INVERTCUBICMAP = false;
  26021. this.LOGARITHMICDEPTH = false;
  26022. this.REFRACTION = false;
  26023. this.REFRACTIONMAP_3D = false;
  26024. this.REFLECTIONOVERALPHA = false;
  26025. this.INVERTNORMALMAPX = false;
  26026. this.INVERTNORMALMAPY = false;
  26027. this.SHADOWFULLFLOAT = false;
  26028. this.CAMERACOLORGRADING = false;
  26029. this.CAMERACOLORCURVES = false;
  26030. this.rebuild();
  26031. }
  26032. return StandardMaterialDefines;
  26033. }(BABYLON.MaterialDefines));
  26034. var StandardMaterial = (function (_super) {
  26035. __extends(StandardMaterial, _super);
  26036. function StandardMaterial(name, scene) {
  26037. var _this = this;
  26038. _super.call(this, name, scene);
  26039. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  26040. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  26041. this.specularColor = new BABYLON.Color3(1, 1, 1);
  26042. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  26043. this.specularPower = 64;
  26044. this.useAlphaFromDiffuseTexture = false;
  26045. this.useEmissiveAsIllumination = false;
  26046. this.linkEmissiveWithDiffuse = false;
  26047. this.useReflectionFresnelFromSpecular = false;
  26048. this.useSpecularOverAlpha = false;
  26049. this.useReflectionOverAlpha = false;
  26050. this.disableLighting = false;
  26051. this.useParallax = false;
  26052. this.useParallaxOcclusion = false;
  26053. this.parallaxScaleBias = 0.05;
  26054. this.roughness = 0;
  26055. this.indexOfRefraction = 0.98;
  26056. this.invertRefractionY = true;
  26057. this.useLightmapAsShadowmap = false;
  26058. this.useGlossinessFromSpecularMapAlpha = false;
  26059. this.maxSimultaneousLights = 4;
  26060. /**
  26061. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  26062. */
  26063. this.invertNormalMapX = false;
  26064. /**
  26065. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  26066. */
  26067. this.invertNormalMapY = false;
  26068. /**
  26069. * Color Grading 2D Lookup Texture.
  26070. * This allows special effects like sepia, black and white to sixties rendering style.
  26071. */
  26072. this.cameraColorGradingTexture = null;
  26073. /**
  26074. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  26075. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  26076. * 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;
  26077. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  26078. */
  26079. this.cameraColorCurves = null;
  26080. this._renderTargets = new BABYLON.SmartArray(16);
  26081. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  26082. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  26083. this._defines = new StandardMaterialDefines();
  26084. this._cachedDefines = new StandardMaterialDefines();
  26085. this._cachedDefines.BonesPerMesh = -1;
  26086. this.getRenderTargetTextures = function () {
  26087. _this._renderTargets.reset();
  26088. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  26089. _this._renderTargets.push(_this.reflectionTexture);
  26090. }
  26091. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  26092. _this._renderTargets.push(_this.refractionTexture);
  26093. }
  26094. return _this._renderTargets;
  26095. };
  26096. }
  26097. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  26098. get: function () {
  26099. return this._useLogarithmicDepth;
  26100. },
  26101. set: function (value) {
  26102. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  26103. },
  26104. enumerable: true,
  26105. configurable: true
  26106. });
  26107. StandardMaterial.prototype.needAlphaBlending = function () {
  26108. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  26109. };
  26110. StandardMaterial.prototype.needAlphaTesting = function () {
  26111. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  26112. };
  26113. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  26114. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  26115. };
  26116. StandardMaterial.prototype.getAlphaTestTexture = function () {
  26117. return this.diffuseTexture;
  26118. };
  26119. // Methods
  26120. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  26121. if (!mesh) {
  26122. return true;
  26123. }
  26124. if (this._defines.INSTANCES !== useInstances) {
  26125. return false;
  26126. }
  26127. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  26128. return true;
  26129. }
  26130. return false;
  26131. };
  26132. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  26133. if (this.isFrozen) {
  26134. if (this._wasPreviouslyReady) {
  26135. return true;
  26136. }
  26137. }
  26138. var scene = this.getScene();
  26139. var engine = scene.getEngine();
  26140. var needUVs = false;
  26141. var needNormals = false;
  26142. this._defines.reset();
  26143. // Lights
  26144. if (scene.lightsEnabled && !this.disableLighting) {
  26145. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  26146. }
  26147. if (!this.checkReadyOnEveryCall) {
  26148. if (this._renderId === scene.getRenderId()) {
  26149. if (this._checkCache(scene, mesh, useInstances)) {
  26150. return true;
  26151. }
  26152. }
  26153. }
  26154. // Textures
  26155. if (scene.texturesEnabled) {
  26156. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26157. if (!this.diffuseTexture.isReady()) {
  26158. return false;
  26159. }
  26160. else {
  26161. needUVs = true;
  26162. this._defines.DIFFUSE = true;
  26163. }
  26164. }
  26165. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26166. if (!this.ambientTexture.isReady()) {
  26167. return false;
  26168. }
  26169. else {
  26170. needUVs = true;
  26171. this._defines.AMBIENT = true;
  26172. }
  26173. }
  26174. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26175. if (!this.opacityTexture.isReady()) {
  26176. return false;
  26177. }
  26178. else {
  26179. needUVs = true;
  26180. this._defines.OPACITY = true;
  26181. if (this.opacityTexture.getAlphaFromRGB) {
  26182. this._defines.OPACITYRGB = true;
  26183. }
  26184. }
  26185. }
  26186. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26187. if (!this.reflectionTexture.isReady()) {
  26188. return false;
  26189. }
  26190. else {
  26191. needNormals = true;
  26192. this._defines.REFLECTION = true;
  26193. if (this.roughness > 0) {
  26194. this._defines.ROUGHNESS = true;
  26195. }
  26196. if (this.useReflectionOverAlpha) {
  26197. this._defines.REFLECTIONOVERALPHA = true;
  26198. }
  26199. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  26200. this._defines.INVERTCUBICMAP = true;
  26201. }
  26202. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  26203. switch (this.reflectionTexture.coordinatesMode) {
  26204. case BABYLON.Texture.CUBIC_MODE:
  26205. case BABYLON.Texture.INVCUBIC_MODE:
  26206. this._defines.REFLECTIONMAP_CUBIC = true;
  26207. break;
  26208. case BABYLON.Texture.EXPLICIT_MODE:
  26209. this._defines.REFLECTIONMAP_EXPLICIT = true;
  26210. break;
  26211. case BABYLON.Texture.PLANAR_MODE:
  26212. this._defines.REFLECTIONMAP_PLANAR = true;
  26213. break;
  26214. case BABYLON.Texture.PROJECTION_MODE:
  26215. this._defines.REFLECTIONMAP_PROJECTION = true;
  26216. break;
  26217. case BABYLON.Texture.SKYBOX_MODE:
  26218. this._defines.REFLECTIONMAP_SKYBOX = true;
  26219. break;
  26220. case BABYLON.Texture.SPHERICAL_MODE:
  26221. this._defines.REFLECTIONMAP_SPHERICAL = true;
  26222. break;
  26223. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  26224. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  26225. break;
  26226. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  26227. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  26228. break;
  26229. }
  26230. }
  26231. }
  26232. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26233. if (!this.emissiveTexture.isReady()) {
  26234. return false;
  26235. }
  26236. else {
  26237. needUVs = true;
  26238. this._defines.EMISSIVE = true;
  26239. }
  26240. }
  26241. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26242. if (!this.lightmapTexture.isReady()) {
  26243. return false;
  26244. }
  26245. else {
  26246. needUVs = true;
  26247. this._defines.LIGHTMAP = true;
  26248. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  26249. }
  26250. }
  26251. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26252. if (!this.specularTexture.isReady()) {
  26253. return false;
  26254. }
  26255. else {
  26256. needUVs = true;
  26257. this._defines.SPECULAR = true;
  26258. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  26259. }
  26260. }
  26261. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  26262. if (!this.bumpTexture.isReady()) {
  26263. return false;
  26264. }
  26265. else {
  26266. needUVs = true;
  26267. this._defines.BUMP = true;
  26268. if (this.useParallax) {
  26269. this._defines.PARALLAX = true;
  26270. if (this.useParallaxOcclusion) {
  26271. this._defines.PARALLAXOCCLUSION = true;
  26272. }
  26273. }
  26274. if (this.invertNormalMapX) {
  26275. this._defines.INVERTNORMALMAPX = true;
  26276. }
  26277. if (this.invertNormalMapY) {
  26278. this._defines.INVERTNORMALMAPY = true;
  26279. }
  26280. }
  26281. }
  26282. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26283. if (!this.refractionTexture.isReady()) {
  26284. return false;
  26285. }
  26286. else {
  26287. needUVs = true;
  26288. this._defines.REFRACTION = true;
  26289. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  26290. }
  26291. }
  26292. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26293. if (!this.cameraColorGradingTexture.isReady()) {
  26294. return false;
  26295. }
  26296. else {
  26297. this._defines.CAMERACOLORGRADING = true;
  26298. }
  26299. }
  26300. }
  26301. // Effect
  26302. if (scene.clipPlane) {
  26303. this._defines.CLIPPLANE = true;
  26304. }
  26305. if (engine.getAlphaTesting()) {
  26306. this._defines.ALPHATEST = true;
  26307. }
  26308. if (this._shouldUseAlphaFromDiffuseTexture()) {
  26309. this._defines.ALPHAFROMDIFFUSE = true;
  26310. }
  26311. if (this.useEmissiveAsIllumination) {
  26312. this._defines.EMISSIVEASILLUMINATION = true;
  26313. }
  26314. if (this.linkEmissiveWithDiffuse) {
  26315. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  26316. }
  26317. if (this.useLogarithmicDepth) {
  26318. this._defines.LOGARITHMICDEPTH = true;
  26319. }
  26320. if (this.cameraColorCurves) {
  26321. this._defines.CAMERACOLORCURVES = true;
  26322. }
  26323. // Point size
  26324. if (this.pointsCloud || scene.forcePointsCloud) {
  26325. this._defines.POINTSIZE = true;
  26326. }
  26327. // Fog
  26328. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26329. this._defines.FOG = true;
  26330. }
  26331. if (StandardMaterial.FresnelEnabled) {
  26332. // Fresnel
  26333. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  26334. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  26335. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  26336. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  26337. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26338. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26339. this._defines.DIFFUSEFRESNEL = true;
  26340. }
  26341. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26342. this._defines.OPACITYFRESNEL = true;
  26343. }
  26344. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26345. this._defines.REFLECTIONFRESNEL = true;
  26346. if (this.useReflectionFresnelFromSpecular) {
  26347. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  26348. }
  26349. }
  26350. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26351. this._defines.REFRACTIONFRESNEL = true;
  26352. }
  26353. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26354. this._defines.EMISSIVEFRESNEL = true;
  26355. }
  26356. needNormals = true;
  26357. this._defines.FRESNEL = true;
  26358. }
  26359. }
  26360. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  26361. this._defines.SPECULAROVERALPHA = true;
  26362. }
  26363. // Attribs
  26364. if (mesh) {
  26365. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26366. this._defines.NORMAL = true;
  26367. }
  26368. if (needUVs) {
  26369. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26370. this._defines.UV1 = true;
  26371. }
  26372. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26373. this._defines.UV2 = true;
  26374. }
  26375. }
  26376. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26377. this._defines.VERTEXCOLOR = true;
  26378. if (mesh.hasVertexAlpha) {
  26379. this._defines.VERTEXALPHA = true;
  26380. }
  26381. }
  26382. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  26383. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  26384. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  26385. }
  26386. // Instances
  26387. if (useInstances) {
  26388. this._defines.INSTANCES = true;
  26389. }
  26390. }
  26391. // Get correct effect
  26392. if (!this._defines.isEqual(this._cachedDefines)) {
  26393. this._defines.cloneTo(this._cachedDefines);
  26394. scene.resetCachedMaterial();
  26395. // Fallbacks
  26396. var fallbacks = new BABYLON.EffectFallbacks();
  26397. if (this._defines.REFLECTION) {
  26398. fallbacks.addFallback(0, "REFLECTION");
  26399. }
  26400. if (this._defines.SPECULAR) {
  26401. fallbacks.addFallback(0, "SPECULAR");
  26402. }
  26403. if (this._defines.BUMP) {
  26404. fallbacks.addFallback(0, "BUMP");
  26405. }
  26406. if (this._defines.PARALLAX) {
  26407. fallbacks.addFallback(1, "PARALLAX");
  26408. }
  26409. if (this._defines.PARALLAXOCCLUSION) {
  26410. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  26411. }
  26412. if (this._defines.SPECULAROVERALPHA) {
  26413. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  26414. }
  26415. if (this._defines.FOG) {
  26416. fallbacks.addFallback(1, "FOG");
  26417. }
  26418. if (this._defines.POINTSIZE) {
  26419. fallbacks.addFallback(0, "POINTSIZE");
  26420. }
  26421. if (this._defines.LOGARITHMICDEPTH) {
  26422. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  26423. }
  26424. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  26425. if (this._defines.SPECULARTERM) {
  26426. fallbacks.addFallback(0, "SPECULARTERM");
  26427. }
  26428. if (this._defines.DIFFUSEFRESNEL) {
  26429. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  26430. }
  26431. if (this._defines.OPACITYFRESNEL) {
  26432. fallbacks.addFallback(2, "OPACITYFRESNEL");
  26433. }
  26434. if (this._defines.REFLECTIONFRESNEL) {
  26435. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  26436. }
  26437. if (this._defines.EMISSIVEFRESNEL) {
  26438. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  26439. }
  26440. if (this._defines.FRESNEL) {
  26441. fallbacks.addFallback(4, "FRESNEL");
  26442. }
  26443. //Attributes
  26444. var attribs = [BABYLON.VertexBuffer.PositionKind];
  26445. if (this._defines.NORMAL) {
  26446. attribs.push(BABYLON.VertexBuffer.NormalKind);
  26447. }
  26448. if (this._defines.UV1) {
  26449. attribs.push(BABYLON.VertexBuffer.UVKind);
  26450. }
  26451. if (this._defines.UV2) {
  26452. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26453. }
  26454. if (this._defines.VERTEXCOLOR) {
  26455. attribs.push(BABYLON.VertexBuffer.ColorKind);
  26456. }
  26457. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  26458. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  26459. var shaderName = "default";
  26460. var join = this._defines.toString();
  26461. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  26462. "vFogInfos", "vFogColor", "pointSize",
  26463. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  26464. "mBones",
  26465. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  26466. "depthValues",
  26467. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  26468. "logarithmicDepthConstant"
  26469. ];
  26470. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  26471. if (this._defines.CAMERACOLORCURVES) {
  26472. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  26473. }
  26474. if (this._defines.CAMERACOLORGRADING) {
  26475. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  26476. }
  26477. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  26478. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  26479. }
  26480. if (!this._effect.isReady()) {
  26481. return false;
  26482. }
  26483. this._renderId = scene.getRenderId();
  26484. this._wasPreviouslyReady = true;
  26485. if (mesh) {
  26486. if (!mesh._materialDefines) {
  26487. mesh._materialDefines = new StandardMaterialDefines();
  26488. }
  26489. this._defines.cloneTo(mesh._materialDefines);
  26490. }
  26491. return true;
  26492. };
  26493. StandardMaterial.prototype.unbind = function () {
  26494. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  26495. this._effect.setTexture("reflection2DSampler", null);
  26496. }
  26497. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  26498. this._effect.setTexture("refraction2DSampler", null);
  26499. }
  26500. _super.prototype.unbind.call(this);
  26501. };
  26502. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26503. this._effect.setMatrix("world", world);
  26504. };
  26505. StandardMaterial.prototype.bind = function (world, mesh) {
  26506. var scene = this.getScene();
  26507. // Matrices
  26508. this.bindOnlyWorldMatrix(world);
  26509. // Bones
  26510. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  26511. if (scene.getCachedMaterial() !== this) {
  26512. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26513. if (StandardMaterial.FresnelEnabled) {
  26514. // Fresnel
  26515. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26516. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  26517. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  26518. }
  26519. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26520. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  26521. }
  26522. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26523. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  26524. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  26525. }
  26526. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26527. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  26528. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  26529. }
  26530. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26531. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  26532. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  26533. }
  26534. }
  26535. // Textures
  26536. if (scene.texturesEnabled) {
  26537. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26538. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  26539. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  26540. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  26541. }
  26542. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26543. this._effect.setTexture("ambientSampler", this.ambientTexture);
  26544. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  26545. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  26546. }
  26547. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26548. this._effect.setTexture("opacitySampler", this.opacityTexture);
  26549. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  26550. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  26551. }
  26552. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26553. if (this.reflectionTexture.isCube) {
  26554. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  26555. }
  26556. else {
  26557. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  26558. }
  26559. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  26560. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  26561. }
  26562. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26563. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  26564. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  26565. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  26566. }
  26567. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26568. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  26569. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  26570. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  26571. }
  26572. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26573. this._effect.setTexture("specularSampler", this.specularTexture);
  26574. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  26575. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  26576. }
  26577. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  26578. this._effect.setTexture("bumpSampler", this.bumpTexture);
  26579. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  26580. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  26581. }
  26582. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26583. var depth = 1.0;
  26584. if (this.refractionTexture.isCube) {
  26585. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  26586. }
  26587. else {
  26588. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  26589. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  26590. if (this.refractionTexture.depth) {
  26591. depth = this.refractionTexture.depth;
  26592. }
  26593. }
  26594. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  26595. }
  26596. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26597. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  26598. }
  26599. }
  26600. // Clip plane
  26601. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  26602. // Point size
  26603. if (this.pointsCloud) {
  26604. this._effect.setFloat("pointSize", this.pointSize);
  26605. }
  26606. // Colors
  26607. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  26608. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  26609. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  26610. if (this._defines.SPECULARTERM) {
  26611. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  26612. }
  26613. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  26614. }
  26615. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  26616. // Diffuse
  26617. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  26618. // Lights
  26619. if (scene.lightsEnabled && !this.disableLighting) {
  26620. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  26621. }
  26622. // View
  26623. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  26624. this._effect.setMatrix("view", scene.getViewMatrix());
  26625. }
  26626. // Fog
  26627. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  26628. // Log. depth
  26629. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  26630. // Color Curves
  26631. if (this.cameraColorCurves) {
  26632. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  26633. }
  26634. }
  26635. _super.prototype.bind.call(this, world, mesh);
  26636. };
  26637. StandardMaterial.prototype.getAnimatables = function () {
  26638. var results = [];
  26639. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  26640. results.push(this.diffuseTexture);
  26641. }
  26642. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  26643. results.push(this.ambientTexture);
  26644. }
  26645. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  26646. results.push(this.opacityTexture);
  26647. }
  26648. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  26649. results.push(this.reflectionTexture);
  26650. }
  26651. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  26652. results.push(this.emissiveTexture);
  26653. }
  26654. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  26655. results.push(this.specularTexture);
  26656. }
  26657. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  26658. results.push(this.bumpTexture);
  26659. }
  26660. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  26661. results.push(this.lightmapTexture);
  26662. }
  26663. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  26664. results.push(this.refractionTexture);
  26665. }
  26666. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  26667. results.push(this.cameraColorGradingTexture);
  26668. }
  26669. return results;
  26670. };
  26671. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26672. if (forceDisposeTextures) {
  26673. if (this.diffuseTexture) {
  26674. this.diffuseTexture.dispose();
  26675. }
  26676. if (this.ambientTexture) {
  26677. this.ambientTexture.dispose();
  26678. }
  26679. if (this.opacityTexture) {
  26680. this.opacityTexture.dispose();
  26681. }
  26682. if (this.reflectionTexture) {
  26683. this.reflectionTexture.dispose();
  26684. }
  26685. if (this.emissiveTexture) {
  26686. this.emissiveTexture.dispose();
  26687. }
  26688. if (this.specularTexture) {
  26689. this.specularTexture.dispose();
  26690. }
  26691. if (this.bumpTexture) {
  26692. this.bumpTexture.dispose();
  26693. }
  26694. if (this.lightmapTexture) {
  26695. this.lightmapTexture.dispose();
  26696. }
  26697. if (this.refractionTexture) {
  26698. this.refractionTexture.dispose();
  26699. }
  26700. if (this.cameraColorGradingTexture) {
  26701. this.cameraColorGradingTexture.dispose();
  26702. }
  26703. }
  26704. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  26705. };
  26706. StandardMaterial.prototype.clone = function (name) {
  26707. var _this = this;
  26708. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  26709. };
  26710. StandardMaterial.prototype.serialize = function () {
  26711. return BABYLON.SerializationHelper.Serialize(this);
  26712. };
  26713. // Statics
  26714. StandardMaterial.Parse = function (source, scene, rootUrl) {
  26715. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  26716. };
  26717. // Flags used to enable or disable a type of texture for all Standard Materials
  26718. StandardMaterial.DiffuseTextureEnabled = true;
  26719. StandardMaterial.AmbientTextureEnabled = true;
  26720. StandardMaterial.OpacityTextureEnabled = true;
  26721. StandardMaterial.ReflectionTextureEnabled = true;
  26722. StandardMaterial.EmissiveTextureEnabled = true;
  26723. StandardMaterial.SpecularTextureEnabled = true;
  26724. StandardMaterial.BumpTextureEnabled = true;
  26725. StandardMaterial.FresnelEnabled = true;
  26726. StandardMaterial.LightmapTextureEnabled = true;
  26727. StandardMaterial.RefractionTextureEnabled = true;
  26728. StandardMaterial.ColorGradingTextureEnabled = true;
  26729. __decorate([
  26730. BABYLON.serializeAsTexture()
  26731. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  26732. __decorate([
  26733. BABYLON.serializeAsTexture()
  26734. ], StandardMaterial.prototype, "ambientTexture", void 0);
  26735. __decorate([
  26736. BABYLON.serializeAsTexture()
  26737. ], StandardMaterial.prototype, "opacityTexture", void 0);
  26738. __decorate([
  26739. BABYLON.serializeAsTexture()
  26740. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  26741. __decorate([
  26742. BABYLON.serializeAsTexture()
  26743. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  26744. __decorate([
  26745. BABYLON.serializeAsTexture()
  26746. ], StandardMaterial.prototype, "specularTexture", void 0);
  26747. __decorate([
  26748. BABYLON.serializeAsTexture()
  26749. ], StandardMaterial.prototype, "bumpTexture", void 0);
  26750. __decorate([
  26751. BABYLON.serializeAsTexture()
  26752. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  26753. __decorate([
  26754. BABYLON.serializeAsTexture()
  26755. ], StandardMaterial.prototype, "refractionTexture", void 0);
  26756. __decorate([
  26757. BABYLON.serializeAsColor3("ambient")
  26758. ], StandardMaterial.prototype, "ambientColor", void 0);
  26759. __decorate([
  26760. BABYLON.serializeAsColor3("diffuse")
  26761. ], StandardMaterial.prototype, "diffuseColor", void 0);
  26762. __decorate([
  26763. BABYLON.serializeAsColor3("specular")
  26764. ], StandardMaterial.prototype, "specularColor", void 0);
  26765. __decorate([
  26766. BABYLON.serializeAsColor3("emissive")
  26767. ], StandardMaterial.prototype, "emissiveColor", void 0);
  26768. __decorate([
  26769. BABYLON.serialize()
  26770. ], StandardMaterial.prototype, "specularPower", void 0);
  26771. __decorate([
  26772. BABYLON.serialize()
  26773. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  26774. __decorate([
  26775. BABYLON.serialize()
  26776. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  26777. __decorate([
  26778. BABYLON.serialize()
  26779. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  26780. __decorate([
  26781. BABYLON.serialize()
  26782. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  26783. __decorate([
  26784. BABYLON.serialize()
  26785. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  26786. __decorate([
  26787. BABYLON.serialize()
  26788. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  26789. __decorate([
  26790. BABYLON.serialize()
  26791. ], StandardMaterial.prototype, "disableLighting", void 0);
  26792. __decorate([
  26793. BABYLON.serialize()
  26794. ], StandardMaterial.prototype, "useParallax", void 0);
  26795. __decorate([
  26796. BABYLON.serialize()
  26797. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  26798. __decorate([
  26799. BABYLON.serialize()
  26800. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  26801. __decorate([
  26802. BABYLON.serialize()
  26803. ], StandardMaterial.prototype, "roughness", void 0);
  26804. __decorate([
  26805. BABYLON.serialize()
  26806. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  26807. __decorate([
  26808. BABYLON.serialize()
  26809. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  26810. __decorate([
  26811. BABYLON.serialize()
  26812. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  26813. __decorate([
  26814. BABYLON.serializeAsFresnelParameters()
  26815. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  26816. __decorate([
  26817. BABYLON.serializeAsFresnelParameters()
  26818. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  26819. __decorate([
  26820. BABYLON.serializeAsFresnelParameters()
  26821. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  26822. __decorate([
  26823. BABYLON.serializeAsFresnelParameters()
  26824. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  26825. __decorate([
  26826. BABYLON.serializeAsFresnelParameters()
  26827. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  26828. __decorate([
  26829. BABYLON.serialize()
  26830. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  26831. __decorate([
  26832. BABYLON.serialize()
  26833. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  26834. __decorate([
  26835. BABYLON.serialize()
  26836. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  26837. __decorate([
  26838. BABYLON.serialize()
  26839. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  26840. __decorate([
  26841. BABYLON.serializeAsTexture()
  26842. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  26843. __decorate([
  26844. BABYLON.serializeAsColorCurves()
  26845. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  26846. __decorate([
  26847. BABYLON.serialize()
  26848. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  26849. return StandardMaterial;
  26850. }(BABYLON.Material));
  26851. BABYLON.StandardMaterial = StandardMaterial;
  26852. })(BABYLON || (BABYLON = {}));
  26853. //# sourceMappingURL=../Materials/babylon.standardMaterial.js.map
  26854. var BABYLON;
  26855. (function (BABYLON) {
  26856. var MultiMaterial = (function (_super) {
  26857. __extends(MultiMaterial, _super);
  26858. function MultiMaterial(name, scene) {
  26859. _super.call(this, name, scene, true);
  26860. this.subMaterials = new Array();
  26861. scene.multiMaterials.push(this);
  26862. }
  26863. // Properties
  26864. MultiMaterial.prototype.getSubMaterial = function (index) {
  26865. if (index < 0 || index >= this.subMaterials.length) {
  26866. return this.getScene().defaultMaterial;
  26867. }
  26868. return this.subMaterials[index];
  26869. };
  26870. // Methods
  26871. MultiMaterial.prototype.isReady = function (mesh) {
  26872. for (var index = 0; index < this.subMaterials.length; index++) {
  26873. var subMaterial = this.subMaterials[index];
  26874. if (subMaterial) {
  26875. if (!this.subMaterials[index].isReady(mesh)) {
  26876. return false;
  26877. }
  26878. }
  26879. }
  26880. return true;
  26881. };
  26882. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  26883. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  26884. for (var index = 0; index < this.subMaterials.length; index++) {
  26885. var subMaterial = null;
  26886. if (cloneChildren) {
  26887. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  26888. }
  26889. else {
  26890. subMaterial = this.subMaterials[index];
  26891. }
  26892. newMultiMaterial.subMaterials.push(subMaterial);
  26893. }
  26894. return newMultiMaterial;
  26895. };
  26896. MultiMaterial.prototype.serialize = function () {
  26897. var serializationObject = {};
  26898. serializationObject.name = this.name;
  26899. serializationObject.id = this.id;
  26900. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26901. serializationObject.materials = [];
  26902. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  26903. var subMat = this.subMaterials[matIndex];
  26904. if (subMat) {
  26905. serializationObject.materials.push(subMat.id);
  26906. }
  26907. else {
  26908. serializationObject.materials.push(null);
  26909. }
  26910. }
  26911. return serializationObject;
  26912. };
  26913. return MultiMaterial;
  26914. }(BABYLON.Material));
  26915. BABYLON.MultiMaterial = MultiMaterial;
  26916. })(BABYLON || (BABYLON = {}));
  26917. //# sourceMappingURL=../Materials/babylon.multiMaterial.js.map
  26918. var BABYLON;
  26919. (function (BABYLON) {
  26920. var SceneLoader = (function () {
  26921. function SceneLoader() {
  26922. }
  26923. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  26924. get: function () {
  26925. return 0;
  26926. },
  26927. enumerable: true,
  26928. configurable: true
  26929. });
  26930. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  26931. get: function () {
  26932. return 1;
  26933. },
  26934. enumerable: true,
  26935. configurable: true
  26936. });
  26937. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  26938. get: function () {
  26939. return 2;
  26940. },
  26941. enumerable: true,
  26942. configurable: true
  26943. });
  26944. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  26945. get: function () {
  26946. return 3;
  26947. },
  26948. enumerable: true,
  26949. configurable: true
  26950. });
  26951. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  26952. get: function () {
  26953. return SceneLoader._ForceFullSceneLoadingForIncremental;
  26954. },
  26955. set: function (value) {
  26956. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  26957. },
  26958. enumerable: true,
  26959. configurable: true
  26960. });
  26961. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  26962. get: function () {
  26963. return SceneLoader._ShowLoadingScreen;
  26964. },
  26965. set: function (value) {
  26966. SceneLoader._ShowLoadingScreen = value;
  26967. },
  26968. enumerable: true,
  26969. configurable: true
  26970. });
  26971. Object.defineProperty(SceneLoader, "loggingLevel", {
  26972. get: function () {
  26973. return SceneLoader._loggingLevel;
  26974. },
  26975. set: function (value) {
  26976. SceneLoader._loggingLevel = value;
  26977. },
  26978. enumerable: true,
  26979. configurable: true
  26980. });
  26981. SceneLoader._getDefaultPlugin = function () {
  26982. return SceneLoader._registeredPlugins[".babylon"];
  26983. };
  26984. SceneLoader._getPluginForExtension = function (extension) {
  26985. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  26986. if (registeredPlugin) {
  26987. return registeredPlugin;
  26988. }
  26989. return SceneLoader._getDefaultPlugin();
  26990. };
  26991. SceneLoader._getPluginForFilename = function (sceneFilename) {
  26992. if (sceneFilename.name) {
  26993. sceneFilename = sceneFilename.name;
  26994. }
  26995. var dotPosition = sceneFilename.lastIndexOf(".");
  26996. var queryStringPosition = sceneFilename.indexOf("?");
  26997. if (queryStringPosition === -1) {
  26998. queryStringPosition = sceneFilename.length;
  26999. }
  27000. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  27001. return SceneLoader._getPluginForExtension(extension);
  27002. };
  27003. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  27004. SceneLoader._getDirectLoad = function (sceneFilename) {
  27005. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  27006. return sceneFilename.substr(5);
  27007. }
  27008. return null;
  27009. };
  27010. // Public functions
  27011. SceneLoader.GetPluginForExtension = function (extension) {
  27012. return SceneLoader._getPluginForExtension(extension).plugin;
  27013. };
  27014. SceneLoader.RegisterPlugin = function (plugin) {
  27015. if (typeof plugin.extensions === "string") {
  27016. var extension = plugin.extensions;
  27017. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  27018. plugin: plugin,
  27019. isBinary: false
  27020. };
  27021. }
  27022. else {
  27023. var extensions = plugin.extensions;
  27024. Object.keys(extensions).forEach(function (extension) {
  27025. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  27026. plugin: plugin,
  27027. isBinary: extensions[extension].isBinary
  27028. };
  27029. });
  27030. }
  27031. };
  27032. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  27033. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27034. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27035. return;
  27036. }
  27037. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27038. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27039. return;
  27040. }
  27041. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  27042. var loadingToken = {};
  27043. scene._addPendingData(loadingToken);
  27044. var manifestChecked = function (success) {
  27045. scene.database = database;
  27046. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  27047. var plugin = registeredPlugin.plugin;
  27048. var useArrayBuffer = registeredPlugin.isBinary;
  27049. var importMeshFromData = function (data) {
  27050. var meshes = [];
  27051. var particleSystems = [];
  27052. var skeletons = [];
  27053. try {
  27054. if (plugin.importMesh) {
  27055. var syncedPlugin = plugin;
  27056. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  27057. if (onerror) {
  27058. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  27059. }
  27060. scene._removePendingData(loadingToken);
  27061. return;
  27062. }
  27063. if (onsuccess) {
  27064. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  27065. onsuccess(meshes, particleSystems, skeletons);
  27066. scene._removePendingData(loadingToken);
  27067. }
  27068. }
  27069. else {
  27070. var asyncedPlugin = plugin;
  27071. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  27072. if (onsuccess) {
  27073. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  27074. onsuccess(meshes, particleSystems, skeletons);
  27075. scene._removePendingData(loadingToken);
  27076. }
  27077. }, function () {
  27078. if (onerror) {
  27079. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  27080. }
  27081. scene._removePendingData(loadingToken);
  27082. });
  27083. }
  27084. }
  27085. catch (e) {
  27086. if (onerror) {
  27087. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  27088. }
  27089. scene._removePendingData(loadingToken);
  27090. }
  27091. };
  27092. if (directLoad) {
  27093. importMeshFromData(directLoad);
  27094. return;
  27095. }
  27096. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  27097. importMeshFromData(data);
  27098. }, progressCallBack, database, useArrayBuffer);
  27099. };
  27100. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  27101. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  27102. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  27103. }
  27104. else {
  27105. // If the scene is a data stream or offline support is not enabled, it's a direct load
  27106. manifestChecked(true);
  27107. }
  27108. };
  27109. /**
  27110. * Load a scene
  27111. * @param rootUrl a string that defines the root url for scene and resources
  27112. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  27113. * @param engine is the instance of BABYLON.Engine to use to create the scene
  27114. */
  27115. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  27116. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  27117. };
  27118. /**
  27119. * Append a scene
  27120. * @param rootUrl a string that defines the root url for scene and resources
  27121. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  27122. * @param scene is the instance of BABYLON.Scene to append to
  27123. */
  27124. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  27125. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27126. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27127. return;
  27128. }
  27129. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  27130. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  27131. var plugin = registeredPlugin.plugin;
  27132. var useArrayBuffer = registeredPlugin.isBinary;
  27133. var database;
  27134. var loadingToken = {};
  27135. scene._addPendingData(loadingToken);
  27136. if (SceneLoader.ShowLoadingScreen) {
  27137. scene.getEngine().displayLoadingUI();
  27138. }
  27139. var loadSceneFromData = function (data) {
  27140. scene.database = database;
  27141. if (plugin.load) {
  27142. var syncedPlugin = plugin;
  27143. if (!syncedPlugin.load(scene, data, rootUrl)) {
  27144. if (onerror) {
  27145. onerror(scene);
  27146. }
  27147. scene._removePendingData(loadingToken);
  27148. scene.getEngine().hideLoadingUI();
  27149. return;
  27150. }
  27151. if (onsuccess) {
  27152. onsuccess(scene);
  27153. }
  27154. scene._removePendingData(loadingToken);
  27155. }
  27156. else {
  27157. var asyncedPlugin = plugin;
  27158. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  27159. if (onsuccess) {
  27160. onsuccess(scene);
  27161. }
  27162. scene._removePendingData(loadingToken);
  27163. }, function () {
  27164. if (onerror) {
  27165. onerror(scene);
  27166. }
  27167. scene._removePendingData(loadingToken);
  27168. scene.getEngine().hideLoadingUI();
  27169. });
  27170. }
  27171. if (SceneLoader.ShowLoadingScreen) {
  27172. scene.executeWhenReady(function () {
  27173. scene.getEngine().hideLoadingUI();
  27174. });
  27175. }
  27176. };
  27177. var manifestChecked = function (success) {
  27178. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  27179. };
  27180. if (directLoad) {
  27181. loadSceneFromData(directLoad);
  27182. return;
  27183. }
  27184. if (rootUrl.indexOf("file:") === -1) {
  27185. if (scene.getEngine().enableOfflineSupport) {
  27186. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  27187. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  27188. }
  27189. else {
  27190. manifestChecked(true);
  27191. }
  27192. }
  27193. else {
  27194. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  27195. }
  27196. };
  27197. // Flags
  27198. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  27199. SceneLoader._ShowLoadingScreen = true;
  27200. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  27201. // Members
  27202. SceneLoader._registeredPlugins = {};
  27203. return SceneLoader;
  27204. }());
  27205. BABYLON.SceneLoader = SceneLoader;
  27206. ;
  27207. })(BABYLON || (BABYLON = {}));
  27208. //# sourceMappingURL=../Loading/babylon.sceneLoader.js.map
  27209. var BABYLON;
  27210. (function (BABYLON) {
  27211. var Internals;
  27212. (function (Internals) {
  27213. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  27214. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27215. var parsedMaterial = parsedData.materials[index];
  27216. if (parsedMaterial.id === id) {
  27217. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27218. }
  27219. }
  27220. return null;
  27221. };
  27222. var isDescendantOf = function (mesh, names, hierarchyIds) {
  27223. names = (names instanceof Array) ? names : [names];
  27224. for (var i in names) {
  27225. if (mesh.name === names[i]) {
  27226. hierarchyIds.push(mesh.id);
  27227. return true;
  27228. }
  27229. }
  27230. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  27231. hierarchyIds.push(mesh.id);
  27232. return true;
  27233. }
  27234. return false;
  27235. };
  27236. var logOperation = function (operation, producer) {
  27237. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  27238. };
  27239. BABYLON.SceneLoader.RegisterPlugin({
  27240. extensions: ".babylon",
  27241. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  27242. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27243. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27244. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27245. // and avoid problems with multiple concurrent .babylon loads.
  27246. var log = "importMesh has failed JSON parse";
  27247. try {
  27248. var parsedData = JSON.parse(data);
  27249. log = "";
  27250. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27251. var loadedSkeletonsIds = [];
  27252. var loadedMaterialsIds = [];
  27253. var hierarchyIds = [];
  27254. var index;
  27255. var cache;
  27256. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27257. var parsedMesh = parsedData.meshes[index];
  27258. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  27259. if (meshesNames instanceof Array) {
  27260. // Remove found mesh name from list.
  27261. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  27262. }
  27263. //Geometry?
  27264. if (parsedMesh.geometryId) {
  27265. //does the file contain geometries?
  27266. if (parsedData.geometries) {
  27267. //find the correct geometry and add it to the scene
  27268. var found = false;
  27269. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  27270. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  27271. return;
  27272. }
  27273. else {
  27274. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  27275. if (parsedGeometryData.id === parsedMesh.geometryId) {
  27276. switch (geometryType) {
  27277. case "boxes":
  27278. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  27279. break;
  27280. case "spheres":
  27281. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  27282. break;
  27283. case "cylinders":
  27284. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  27285. break;
  27286. case "toruses":
  27287. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  27288. break;
  27289. case "grounds":
  27290. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  27291. break;
  27292. case "planes":
  27293. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  27294. break;
  27295. case "torusKnots":
  27296. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  27297. break;
  27298. case "vertexData":
  27299. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  27300. break;
  27301. }
  27302. found = true;
  27303. }
  27304. });
  27305. }
  27306. });
  27307. if (!found) {
  27308. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  27309. }
  27310. }
  27311. }
  27312. // Material ?
  27313. if (parsedMesh.materialId) {
  27314. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  27315. if (!materialFound && parsedData.multiMaterials) {
  27316. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  27317. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  27318. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  27319. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  27320. var subMatId = parsedMultiMaterial.materials[matIndex];
  27321. loadedMaterialsIds.push(subMatId);
  27322. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  27323. log += "\n\tMaterial " + mat.toString(fullDetails);
  27324. }
  27325. loadedMaterialsIds.push(parsedMultiMaterial.id);
  27326. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27327. materialFound = true;
  27328. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  27329. break;
  27330. }
  27331. }
  27332. }
  27333. if (!materialFound) {
  27334. loadedMaterialsIds.push(parsedMesh.materialId);
  27335. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  27336. if (!mat) {
  27337. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  27338. }
  27339. else {
  27340. log += "\n\tMaterial " + mat.toString(fullDetails);
  27341. }
  27342. }
  27343. }
  27344. // Skeleton ?
  27345. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  27346. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  27347. if (!skeletonAlreadyLoaded) {
  27348. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  27349. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  27350. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  27351. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27352. skeletons.push(skeleton);
  27353. loadedSkeletonsIds.push(parsedSkeleton.id);
  27354. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  27355. }
  27356. }
  27357. }
  27358. }
  27359. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27360. meshes.push(mesh);
  27361. log += "\n\tMesh " + mesh.toString(fullDetails);
  27362. }
  27363. }
  27364. // Connecting parents
  27365. var currentMesh;
  27366. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27367. currentMesh = scene.meshes[index];
  27368. if (currentMesh._waitingParentId) {
  27369. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  27370. currentMesh._waitingParentId = undefined;
  27371. }
  27372. }
  27373. // freeze and compute world matrix application
  27374. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27375. currentMesh = scene.meshes[index];
  27376. if (currentMesh._waitingFreezeWorldMatrix) {
  27377. currentMesh.freezeWorldMatrix();
  27378. currentMesh._waitingFreezeWorldMatrix = undefined;
  27379. }
  27380. else {
  27381. currentMesh.computeWorldMatrix(true);
  27382. }
  27383. }
  27384. // Particles
  27385. if (parsedData.particleSystems) {
  27386. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27387. var parsedParticleSystem = parsedData.particleSystems[index];
  27388. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  27389. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  27390. }
  27391. }
  27392. }
  27393. return true;
  27394. }
  27395. catch (err) {
  27396. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  27397. log = null;
  27398. throw err;
  27399. }
  27400. finally {
  27401. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27402. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27403. }
  27404. }
  27405. },
  27406. load: function (scene, data, rootUrl) {
  27407. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27408. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27409. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27410. // and avoid problems with multiple concurrent .babylon loads.
  27411. var log = "importScene has failed JSON parse";
  27412. try {
  27413. var parsedData = JSON.parse(data);
  27414. log = "";
  27415. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27416. // Scene
  27417. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  27418. scene.autoClear = parsedData.autoClear;
  27419. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  27420. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  27421. if (parsedData.gravity) {
  27422. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  27423. }
  27424. // Fog
  27425. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  27426. scene.fogMode = parsedData.fogMode;
  27427. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  27428. scene.fogStart = parsedData.fogStart;
  27429. scene.fogEnd = parsedData.fogEnd;
  27430. scene.fogDensity = parsedData.fogDensity;
  27431. log += "\tFog mode for scene: ";
  27432. switch (scene.fogMode) {
  27433. // getters not compiling, so using hardcoded
  27434. case 1:
  27435. log += "exp\n";
  27436. break;
  27437. case 2:
  27438. log += "exp2\n";
  27439. break;
  27440. case 3:
  27441. log += "linear\n";
  27442. break;
  27443. }
  27444. }
  27445. //Physics
  27446. if (parsedData.physicsEnabled) {
  27447. var physicsPlugin;
  27448. if (parsedData.physicsEngine === "cannon") {
  27449. physicsPlugin = new BABYLON.CannonJSPlugin();
  27450. }
  27451. else if (parsedData.physicsEngine === "oimo") {
  27452. physicsPlugin = new BABYLON.OimoJSPlugin();
  27453. }
  27454. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  27455. //else - default engine, which is currently oimo
  27456. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  27457. scene.enablePhysics(physicsGravity, physicsPlugin);
  27458. }
  27459. // Metadata
  27460. if (parsedData.metadata !== undefined) {
  27461. scene.metadata = parsedData.metadata;
  27462. }
  27463. //collisions, if defined. otherwise, default is true
  27464. if (parsedData.collisionsEnabled != undefined) {
  27465. scene.collisionsEnabled = parsedData.collisionsEnabled;
  27466. }
  27467. scene.workerCollisions = !!parsedData.workerCollisions;
  27468. var index;
  27469. var cache;
  27470. // Lights
  27471. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  27472. var parsedLight = parsedData.lights[index];
  27473. var light = BABYLON.Light.Parse(parsedLight, scene);
  27474. log += (index === 0 ? "\n\tLights:" : "");
  27475. log += "\n\t\t" + light.toString(fullDetails);
  27476. }
  27477. // Animations
  27478. if (parsedData.animations) {
  27479. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  27480. var parsedAnimation = parsedData.animations[index];
  27481. var animation = BABYLON.Animation.Parse(parsedAnimation);
  27482. scene.animations.push(animation);
  27483. log += (index === 0 ? "\n\tAnimations:" : "");
  27484. log += "\n\t\t" + animation.toString(fullDetails);
  27485. }
  27486. }
  27487. if (parsedData.autoAnimate) {
  27488. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  27489. }
  27490. // Materials
  27491. if (parsedData.materials) {
  27492. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27493. var parsedMaterial = parsedData.materials[index];
  27494. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27495. log += (index === 0 ? "\n\tMaterials:" : "");
  27496. log += "\n\t\t" + mat.toString(fullDetails);
  27497. }
  27498. }
  27499. if (parsedData.multiMaterials) {
  27500. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  27501. var parsedMultiMaterial = parsedData.multiMaterials[index];
  27502. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27503. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  27504. log += "\n\t\t" + mmat.toString(fullDetails);
  27505. }
  27506. }
  27507. // Skeletons
  27508. if (parsedData.skeletons) {
  27509. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  27510. var parsedSkeleton = parsedData.skeletons[index];
  27511. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27512. log += (index === 0 ? "\n\tSkeletons:" : "");
  27513. log += "\n\t\t" + skeleton.toString(fullDetails);
  27514. }
  27515. }
  27516. // Geometries
  27517. var geometries = parsedData.geometries;
  27518. if (geometries) {
  27519. // Boxes
  27520. var boxes = geometries.boxes;
  27521. if (boxes) {
  27522. for (index = 0, cache = boxes.length; index < cache; index++) {
  27523. var parsedBox = boxes[index];
  27524. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  27525. }
  27526. }
  27527. // Spheres
  27528. var spheres = geometries.spheres;
  27529. if (spheres) {
  27530. for (index = 0, cache = spheres.length; index < cache; index++) {
  27531. var parsedSphere = spheres[index];
  27532. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  27533. }
  27534. }
  27535. // Cylinders
  27536. var cylinders = geometries.cylinders;
  27537. if (cylinders) {
  27538. for (index = 0, cache = cylinders.length; index < cache; index++) {
  27539. var parsedCylinder = cylinders[index];
  27540. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  27541. }
  27542. }
  27543. // Toruses
  27544. var toruses = geometries.toruses;
  27545. if (toruses) {
  27546. for (index = 0, cache = toruses.length; index < cache; index++) {
  27547. var parsedTorus = toruses[index];
  27548. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  27549. }
  27550. }
  27551. // Grounds
  27552. var grounds = geometries.grounds;
  27553. if (grounds) {
  27554. for (index = 0, cache = grounds.length; index < cache; index++) {
  27555. var parsedGround = grounds[index];
  27556. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  27557. }
  27558. }
  27559. // Planes
  27560. var planes = geometries.planes;
  27561. if (planes) {
  27562. for (index = 0, cache = planes.length; index < cache; index++) {
  27563. var parsedPlane = planes[index];
  27564. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  27565. }
  27566. }
  27567. // TorusKnots
  27568. var torusKnots = geometries.torusKnots;
  27569. if (torusKnots) {
  27570. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  27571. var parsedTorusKnot = torusKnots[index];
  27572. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  27573. }
  27574. }
  27575. // VertexData
  27576. var vertexData = geometries.vertexData;
  27577. if (vertexData) {
  27578. for (index = 0, cache = vertexData.length; index < cache; index++) {
  27579. var parsedVertexData = vertexData[index];
  27580. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  27581. }
  27582. }
  27583. }
  27584. // Meshes
  27585. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27586. var parsedMesh = parsedData.meshes[index];
  27587. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27588. log += (index === 0 ? "\n\tMeshes:" : "");
  27589. log += "\n\t\t" + mesh.toString(fullDetails);
  27590. }
  27591. // Cameras
  27592. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  27593. var parsedCamera = parsedData.cameras[index];
  27594. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  27595. log += (index === 0 ? "\n\tCameras:" : "");
  27596. log += "\n\t\t" + camera.toString(fullDetails);
  27597. }
  27598. if (parsedData.activeCameraID) {
  27599. scene.setActiveCameraByID(parsedData.activeCameraID);
  27600. }
  27601. // Browsing all the graph to connect the dots
  27602. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  27603. var camera = scene.cameras[index];
  27604. if (camera._waitingParentId) {
  27605. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  27606. camera._waitingParentId = undefined;
  27607. }
  27608. }
  27609. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  27610. var light = scene.lights[index];
  27611. if (light._waitingParentId) {
  27612. light.parent = scene.getLastEntryByID(light._waitingParentId);
  27613. light._waitingParentId = undefined;
  27614. }
  27615. }
  27616. // Sounds
  27617. var loadedSounds = [];
  27618. var loadedSound;
  27619. if (BABYLON.AudioEngine && parsedData.sounds) {
  27620. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  27621. var parsedSound = parsedData.sounds[index];
  27622. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27623. if (!parsedSound.url)
  27624. parsedSound.url = parsedSound.name;
  27625. if (!loadedSounds[parsedSound.url]) {
  27626. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  27627. loadedSounds[parsedSound.url] = loadedSound;
  27628. }
  27629. else {
  27630. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  27631. }
  27632. }
  27633. else {
  27634. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  27635. }
  27636. }
  27637. }
  27638. loadedSounds = [];
  27639. // Connect parents & children and parse actions
  27640. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27641. var mesh = scene.meshes[index];
  27642. if (mesh._waitingParentId) {
  27643. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  27644. mesh._waitingParentId = undefined;
  27645. }
  27646. if (mesh._waitingActions) {
  27647. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  27648. mesh._waitingActions = undefined;
  27649. }
  27650. }
  27651. // freeze world matrix application
  27652. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27653. var currentMesh = scene.meshes[index];
  27654. if (currentMesh._waitingFreezeWorldMatrix) {
  27655. currentMesh.freezeWorldMatrix();
  27656. currentMesh._waitingFreezeWorldMatrix = undefined;
  27657. }
  27658. else {
  27659. currentMesh.computeWorldMatrix(true);
  27660. }
  27661. }
  27662. // Particles Systems
  27663. if (parsedData.particleSystems) {
  27664. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27665. var parsedParticleSystem = parsedData.particleSystems[index];
  27666. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  27667. }
  27668. }
  27669. // Lens flares
  27670. if (parsedData.lensFlareSystems) {
  27671. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  27672. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  27673. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  27674. }
  27675. }
  27676. // Shadows
  27677. if (parsedData.shadowGenerators) {
  27678. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  27679. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  27680. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  27681. }
  27682. }
  27683. // Actions (scene)
  27684. if (parsedData.actions) {
  27685. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  27686. }
  27687. // Finish
  27688. return true;
  27689. }
  27690. catch (err) {
  27691. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  27692. log = null;
  27693. throw err;
  27694. }
  27695. finally {
  27696. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27697. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27698. }
  27699. }
  27700. }
  27701. });
  27702. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27703. })(BABYLON || (BABYLON = {}));
  27704. //# sourceMappingURL=../../Loading/Plugins/babylon.babylonFileLoader.js.map
  27705. var BABYLON;
  27706. (function (BABYLON) {
  27707. var SpriteManager = (function () {
  27708. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  27709. if (epsilon === void 0) { epsilon = 0.01; }
  27710. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27711. this.name = name;
  27712. this.sprites = new Array();
  27713. this.renderingGroupId = 0;
  27714. this.layerMask = 0x0FFFFFFF;
  27715. this.fogEnabled = true;
  27716. this.isPickable = false;
  27717. /**
  27718. * An event triggered when the manager is disposed.
  27719. * @type {BABYLON.Observable}
  27720. */
  27721. this.onDisposeObservable = new BABYLON.Observable();
  27722. this._vertexBuffers = {};
  27723. this._capacity = capacity;
  27724. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  27725. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27726. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27727. if (cellSize.width && cellSize.height) {
  27728. this.cellWidth = cellSize.width;
  27729. this.cellHeight = cellSize.height;
  27730. }
  27731. else if (cellSize !== undefined) {
  27732. this.cellWidth = cellSize;
  27733. this.cellHeight = cellSize;
  27734. }
  27735. else {
  27736. return;
  27737. }
  27738. this._epsilon = epsilon;
  27739. this._scene = scene;
  27740. this._scene.spriteManagers.push(this);
  27741. var indices = [];
  27742. var index = 0;
  27743. for (var count = 0; count < capacity; count++) {
  27744. indices.push(index);
  27745. indices.push(index + 1);
  27746. indices.push(index + 2);
  27747. indices.push(index);
  27748. indices.push(index + 2);
  27749. indices.push(index + 3);
  27750. index += 4;
  27751. }
  27752. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27753. // VBO
  27754. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  27755. this._vertexData = new Float32Array(capacity * 16 * 4);
  27756. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  27757. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  27758. var options = this._buffer.createVertexBuffer("options", 4, 4);
  27759. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  27760. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  27761. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27762. this._vertexBuffers["options"] = options;
  27763. this._vertexBuffers["cellInfo"] = cellInfo;
  27764. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27765. // Effects
  27766. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  27767. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  27768. }
  27769. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  27770. set: function (callback) {
  27771. if (this._onDisposeObserver) {
  27772. this.onDisposeObservable.remove(this._onDisposeObserver);
  27773. }
  27774. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27775. },
  27776. enumerable: true,
  27777. configurable: true
  27778. });
  27779. Object.defineProperty(SpriteManager.prototype, "texture", {
  27780. get: function () {
  27781. return this._spriteTexture;
  27782. },
  27783. set: function (value) {
  27784. this._spriteTexture = value;
  27785. },
  27786. enumerable: true,
  27787. configurable: true
  27788. });
  27789. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  27790. var arrayOffset = index * 16;
  27791. if (offsetX === 0)
  27792. offsetX = this._epsilon;
  27793. else if (offsetX === 1)
  27794. offsetX = 1 - this._epsilon;
  27795. if (offsetY === 0)
  27796. offsetY = this._epsilon;
  27797. else if (offsetY === 1)
  27798. offsetY = 1 - this._epsilon;
  27799. this._vertexData[arrayOffset] = sprite.position.x;
  27800. this._vertexData[arrayOffset + 1] = sprite.position.y;
  27801. this._vertexData[arrayOffset + 2] = sprite.position.z;
  27802. this._vertexData[arrayOffset + 3] = sprite.angle;
  27803. this._vertexData[arrayOffset + 4] = sprite.width;
  27804. this._vertexData[arrayOffset + 5] = sprite.height;
  27805. this._vertexData[arrayOffset + 6] = offsetX;
  27806. this._vertexData[arrayOffset + 7] = offsetY;
  27807. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  27808. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  27809. var offset = (sprite.cellIndex / rowSize) >> 0;
  27810. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  27811. this._vertexData[arrayOffset + 11] = offset;
  27812. // Color
  27813. this._vertexData[arrayOffset + 12] = sprite.color.r;
  27814. this._vertexData[arrayOffset + 13] = sprite.color.g;
  27815. this._vertexData[arrayOffset + 14] = sprite.color.b;
  27816. this._vertexData[arrayOffset + 15] = sprite.color.a;
  27817. };
  27818. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  27819. var count = Math.min(this._capacity, this.sprites.length);
  27820. var min = BABYLON.Vector3.Zero();
  27821. var max = BABYLON.Vector3.Zero();
  27822. var distance = Number.MAX_VALUE;
  27823. var currentSprite;
  27824. var cameraSpacePosition = BABYLON.Vector3.Zero();
  27825. var cameraView = camera.getViewMatrix();
  27826. for (var index = 0; index < count; index++) {
  27827. var sprite = this.sprites[index];
  27828. if (!sprite) {
  27829. continue;
  27830. }
  27831. if (predicate) {
  27832. if (!predicate(sprite)) {
  27833. continue;
  27834. }
  27835. }
  27836. else if (!sprite.isPickable) {
  27837. continue;
  27838. }
  27839. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  27840. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  27841. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  27842. if (ray.intersectsBoxMinMax(min, max)) {
  27843. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  27844. if (distance > currentDistance) {
  27845. distance = currentDistance;
  27846. currentSprite = sprite;
  27847. if (fastCheck) {
  27848. break;
  27849. }
  27850. }
  27851. }
  27852. }
  27853. if (currentSprite) {
  27854. var result = new BABYLON.PickingInfo();
  27855. result.hit = true;
  27856. result.pickedSprite = currentSprite;
  27857. result.distance = distance;
  27858. return result;
  27859. }
  27860. return null;
  27861. };
  27862. SpriteManager.prototype.render = function () {
  27863. // Check
  27864. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  27865. return;
  27866. var engine = this._scene.getEngine();
  27867. var baseSize = this._spriteTexture.getBaseSize();
  27868. // Sprites
  27869. var deltaTime = engine.getDeltaTime();
  27870. var max = Math.min(this._capacity, this.sprites.length);
  27871. var rowSize = baseSize.width / this.cellWidth;
  27872. var offset = 0;
  27873. for (var index = 0; index < max; index++) {
  27874. var sprite = this.sprites[index];
  27875. if (!sprite) {
  27876. continue;
  27877. }
  27878. sprite._animate(deltaTime);
  27879. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  27880. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  27881. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  27882. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  27883. }
  27884. this._buffer.update(this._vertexData);
  27885. // Render
  27886. var effect = this._effectBase;
  27887. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27888. effect = this._effectFog;
  27889. }
  27890. engine.enableEffect(effect);
  27891. var viewMatrix = this._scene.getViewMatrix();
  27892. effect.setTexture("diffuseSampler", this._spriteTexture);
  27893. effect.setMatrix("view", viewMatrix);
  27894. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27895. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  27896. // Fog
  27897. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27898. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  27899. effect.setColor3("vFogColor", this._scene.fogColor);
  27900. }
  27901. // VBOs
  27902. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27903. // Draw order
  27904. engine.setDepthFunctionToLessOrEqual();
  27905. effect.setBool("alphaTest", true);
  27906. engine.setColorWrite(false);
  27907. engine.draw(true, 0, max * 6);
  27908. engine.setColorWrite(true);
  27909. effect.setBool("alphaTest", false);
  27910. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27911. engine.draw(true, 0, max * 6);
  27912. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27913. };
  27914. SpriteManager.prototype.dispose = function () {
  27915. if (this._buffer) {
  27916. this._buffer.dispose();
  27917. this._buffer = null;
  27918. }
  27919. if (this._indexBuffer) {
  27920. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27921. this._indexBuffer = null;
  27922. }
  27923. if (this._spriteTexture) {
  27924. this._spriteTexture.dispose();
  27925. this._spriteTexture = null;
  27926. }
  27927. // Remove from scene
  27928. var index = this._scene.spriteManagers.indexOf(this);
  27929. this._scene.spriteManagers.splice(index, 1);
  27930. // Callback
  27931. this.onDisposeObservable.notifyObservers(this);
  27932. this.onDisposeObservable.clear();
  27933. };
  27934. return SpriteManager;
  27935. }());
  27936. BABYLON.SpriteManager = SpriteManager;
  27937. })(BABYLON || (BABYLON = {}));
  27938. //# sourceMappingURL=../Sprites/babylon.spriteManager.js.map
  27939. var BABYLON;
  27940. (function (BABYLON) {
  27941. var Sprite = (function () {
  27942. function Sprite(name, manager) {
  27943. this.name = name;
  27944. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27945. this.width = 1.0;
  27946. this.height = 1.0;
  27947. this.angle = 0;
  27948. this.cellIndex = 0;
  27949. this.invertU = 0;
  27950. this.invertV = 0;
  27951. this.animations = new Array();
  27952. this.isPickable = false;
  27953. this._animationStarted = false;
  27954. this._loopAnimation = false;
  27955. this._fromIndex = 0;
  27956. this._toIndex = 0;
  27957. this._delay = 0;
  27958. this._direction = 1;
  27959. this._frameCount = 0;
  27960. this._time = 0;
  27961. this._manager = manager;
  27962. this._manager.sprites.push(this);
  27963. this.position = BABYLON.Vector3.Zero();
  27964. }
  27965. Object.defineProperty(Sprite.prototype, "size", {
  27966. get: function () {
  27967. return this.width;
  27968. },
  27969. set: function (value) {
  27970. this.width = value;
  27971. this.height = value;
  27972. },
  27973. enumerable: true,
  27974. configurable: true
  27975. });
  27976. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  27977. this._fromIndex = from;
  27978. this._toIndex = to;
  27979. this._loopAnimation = loop;
  27980. this._delay = delay;
  27981. this._animationStarted = true;
  27982. this._direction = from < to ? 1 : -1;
  27983. this.cellIndex = from;
  27984. this._time = 0;
  27985. this._onAnimationEnd = onAnimationEnd;
  27986. };
  27987. Sprite.prototype.stopAnimation = function () {
  27988. this._animationStarted = false;
  27989. };
  27990. Sprite.prototype._animate = function (deltaTime) {
  27991. if (!this._animationStarted)
  27992. return;
  27993. this._time += deltaTime;
  27994. if (this._time > this._delay) {
  27995. this._time = this._time % this._delay;
  27996. this.cellIndex += this._direction;
  27997. if (this.cellIndex === this._toIndex) {
  27998. if (this._loopAnimation) {
  27999. this.cellIndex = this._fromIndex;
  28000. }
  28001. else {
  28002. this._animationStarted = false;
  28003. if (this._onAnimationEnd) {
  28004. this._onAnimationEnd();
  28005. }
  28006. if (this.disposeWhenFinishedAnimating) {
  28007. this.dispose();
  28008. }
  28009. }
  28010. }
  28011. }
  28012. };
  28013. Sprite.prototype.dispose = function () {
  28014. for (var i = 0; i < this._manager.sprites.length; i++) {
  28015. if (this._manager.sprites[i] == this) {
  28016. this._manager.sprites.splice(i, 1);
  28017. }
  28018. }
  28019. };
  28020. return Sprite;
  28021. }());
  28022. BABYLON.Sprite = Sprite;
  28023. })(BABYLON || (BABYLON = {}));
  28024. //# sourceMappingURL=../Sprites/babylon.sprite.js.map
  28025. var BABYLON;
  28026. (function (BABYLON) {
  28027. var Layer = (function () {
  28028. function Layer(name, imgUrl, scene, isBackground, color) {
  28029. this.name = name;
  28030. this.scale = new BABYLON.Vector2(1, 1);
  28031. this.offset = new BABYLON.Vector2(0, 0);
  28032. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  28033. this._vertexBuffers = {};
  28034. // Events
  28035. /**
  28036. * An event triggered when the layer is disposed.
  28037. * @type {BABYLON.Observable}
  28038. */
  28039. this.onDisposeObservable = new BABYLON.Observable();
  28040. /**
  28041. * An event triggered before rendering the scene
  28042. * @type {BABYLON.Observable}
  28043. */
  28044. this.onBeforeRenderObservable = new BABYLON.Observable();
  28045. /**
  28046. * An event triggered after rendering the scene
  28047. * @type {BABYLON.Observable}
  28048. */
  28049. this.onAfterRenderObservable = new BABYLON.Observable();
  28050. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  28051. this.isBackground = isBackground === undefined ? true : isBackground;
  28052. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  28053. this._scene = scene;
  28054. this._scene.layers.push(this);
  28055. var engine = scene.getEngine();
  28056. // VBO
  28057. var vertices = [];
  28058. vertices.push(1, 1);
  28059. vertices.push(-1, 1);
  28060. vertices.push(-1, -1);
  28061. vertices.push(1, -1);
  28062. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28063. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  28064. // Indices
  28065. var indices = [];
  28066. indices.push(0);
  28067. indices.push(1);
  28068. indices.push(2);
  28069. indices.push(0);
  28070. indices.push(2);
  28071. indices.push(3);
  28072. this._indexBuffer = engine.createIndexBuffer(indices);
  28073. // Effects
  28074. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  28075. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  28076. }
  28077. Object.defineProperty(Layer.prototype, "onDispose", {
  28078. set: function (callback) {
  28079. if (this._onDisposeObserver) {
  28080. this.onDisposeObservable.remove(this._onDisposeObserver);
  28081. }
  28082. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28083. },
  28084. enumerable: true,
  28085. configurable: true
  28086. });
  28087. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  28088. set: function (callback) {
  28089. if (this._onBeforeRenderObserver) {
  28090. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  28091. }
  28092. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  28093. },
  28094. enumerable: true,
  28095. configurable: true
  28096. });
  28097. Object.defineProperty(Layer.prototype, "onAfterRender", {
  28098. set: function (callback) {
  28099. if (this._onAfterRenderObserver) {
  28100. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  28101. }
  28102. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  28103. },
  28104. enumerable: true,
  28105. configurable: true
  28106. });
  28107. Layer.prototype.render = function () {
  28108. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  28109. // Check
  28110. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  28111. return;
  28112. var engine = this._scene.getEngine();
  28113. this.onBeforeRenderObservable.notifyObservers(this);
  28114. // Render
  28115. engine.enableEffect(currentEffect);
  28116. engine.setState(false);
  28117. // Texture
  28118. currentEffect.setTexture("textureSampler", this.texture);
  28119. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  28120. // Color
  28121. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  28122. // Scale / offset
  28123. currentEffect.setVector2("offset", this.offset);
  28124. currentEffect.setVector2("scale", this.scale);
  28125. // VBOs
  28126. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  28127. // Draw order
  28128. if (!this.alphaTest) {
  28129. engine.setAlphaMode(this.alphaBlendingMode);
  28130. engine.draw(true, 0, 6);
  28131. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28132. }
  28133. else {
  28134. engine.draw(true, 0, 6);
  28135. }
  28136. this.onAfterRenderObservable.notifyObservers(this);
  28137. };
  28138. Layer.prototype.dispose = function () {
  28139. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28140. if (vertexBuffer) {
  28141. vertexBuffer.dispose();
  28142. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28143. }
  28144. if (this._indexBuffer) {
  28145. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28146. this._indexBuffer = null;
  28147. }
  28148. if (this.texture) {
  28149. this.texture.dispose();
  28150. this.texture = null;
  28151. }
  28152. // Remove from scene
  28153. var index = this._scene.layers.indexOf(this);
  28154. this._scene.layers.splice(index, 1);
  28155. // Callback
  28156. this.onDisposeObservable.notifyObservers(this);
  28157. this.onDisposeObservable.clear();
  28158. this.onAfterRenderObservable.clear();
  28159. this.onBeforeRenderObservable.clear();
  28160. };
  28161. return Layer;
  28162. }());
  28163. BABYLON.Layer = Layer;
  28164. })(BABYLON || (BABYLON = {}));
  28165. //# sourceMappingURL=../Layer/babylon.layer.js.map
  28166. var BABYLON;
  28167. (function (BABYLON) {
  28168. var Particle = (function () {
  28169. function Particle() {
  28170. this.position = BABYLON.Vector3.Zero();
  28171. this.direction = BABYLON.Vector3.Zero();
  28172. this.color = new BABYLON.Color4(0, 0, 0, 0);
  28173. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  28174. this.lifeTime = 1.0;
  28175. this.age = 0;
  28176. this.size = 0;
  28177. this.angle = 0;
  28178. this.angularSpeed = 0;
  28179. }
  28180. Particle.prototype.copyTo = function (other) {
  28181. other.position.copyFrom(this.position);
  28182. other.direction.copyFrom(this.direction);
  28183. other.color.copyFrom(this.color);
  28184. other.colorStep.copyFrom(this.colorStep);
  28185. other.lifeTime = this.lifeTime;
  28186. other.age = this.age;
  28187. other.size = this.size;
  28188. other.angle = this.angle;
  28189. other.angularSpeed = this.angularSpeed;
  28190. };
  28191. return Particle;
  28192. }());
  28193. BABYLON.Particle = Particle;
  28194. })(BABYLON || (BABYLON = {}));
  28195. //# sourceMappingURL=../Particles/babylon.particle.js.map
  28196. var BABYLON;
  28197. (function (BABYLON) {
  28198. var randomNumber = function (min, max) {
  28199. if (min === max) {
  28200. return (min);
  28201. }
  28202. var random = Math.random();
  28203. return ((random * (max - min)) + min);
  28204. };
  28205. var ParticleSystem = (function () {
  28206. function ParticleSystem(name, capacity, scene, customEffect) {
  28207. var _this = this;
  28208. this.name = name;
  28209. // Members
  28210. this.animations = [];
  28211. this.renderingGroupId = 0;
  28212. this.emitter = null;
  28213. this.emitRate = 10;
  28214. this.manualEmitCount = -1;
  28215. this.updateSpeed = 0.01;
  28216. this.targetStopDuration = 0;
  28217. this.disposeOnStop = false;
  28218. this.minEmitPower = 1;
  28219. this.maxEmitPower = 1;
  28220. this.minLifeTime = 1;
  28221. this.maxLifeTime = 1;
  28222. this.minSize = 1;
  28223. this.maxSize = 1;
  28224. this.minAngularSpeed = 0;
  28225. this.maxAngularSpeed = 0;
  28226. this.layerMask = 0x0FFFFFFF;
  28227. /**
  28228. * An event triggered when the system is disposed.
  28229. * @type {BABYLON.Observable}
  28230. */
  28231. this.onDisposeObservable = new BABYLON.Observable();
  28232. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  28233. this.forceDepthWrite = false;
  28234. this.gravity = BABYLON.Vector3.Zero();
  28235. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  28236. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  28237. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  28238. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  28239. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28240. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28241. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  28242. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28243. this.particles = new Array();
  28244. this._stockParticles = new Array();
  28245. this._newPartsExcess = 0;
  28246. this._vertexBuffers = {};
  28247. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  28248. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  28249. this._scaledDirection = BABYLON.Vector3.Zero();
  28250. this._scaledGravity = BABYLON.Vector3.Zero();
  28251. this._currentRenderId = -1;
  28252. this._started = false;
  28253. this._stopped = false;
  28254. this._actualFrame = 0;
  28255. this.id = name;
  28256. this._capacity = capacity;
  28257. this._scene = scene;
  28258. this._customEffect = customEffect;
  28259. scene.particleSystems.push(this);
  28260. var indices = [];
  28261. var index = 0;
  28262. for (var count = 0; count < capacity; count++) {
  28263. indices.push(index);
  28264. indices.push(index + 1);
  28265. indices.push(index + 2);
  28266. indices.push(index);
  28267. indices.push(index + 2);
  28268. indices.push(index + 3);
  28269. index += 4;
  28270. }
  28271. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28272. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  28273. this._vertexData = new Float32Array(capacity * 11 * 4);
  28274. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  28275. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  28276. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  28277. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  28278. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28279. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28280. this._vertexBuffers["options"] = options;
  28281. // Default behaviors
  28282. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  28283. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  28284. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  28285. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  28286. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  28287. };
  28288. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  28289. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  28290. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  28291. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  28292. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  28293. };
  28294. this.updateFunction = function (particles) {
  28295. for (var index = 0; index < particles.length; index++) {
  28296. var particle = particles[index];
  28297. particle.age += _this._scaledUpdateSpeed;
  28298. if (particle.age >= particle.lifeTime) {
  28299. _this.recycleParticle(particle);
  28300. index--;
  28301. continue;
  28302. }
  28303. else {
  28304. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  28305. particle.color.addInPlace(_this._scaledColorStep);
  28306. if (particle.color.a < 0)
  28307. particle.color.a = 0;
  28308. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  28309. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  28310. particle.position.addInPlace(_this._scaledDirection);
  28311. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  28312. particle.direction.addInPlace(_this._scaledGravity);
  28313. }
  28314. }
  28315. };
  28316. }
  28317. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  28318. set: function (callback) {
  28319. if (this._onDisposeObserver) {
  28320. this.onDisposeObservable.remove(this._onDisposeObserver);
  28321. }
  28322. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28323. },
  28324. enumerable: true,
  28325. configurable: true
  28326. });
  28327. ParticleSystem.prototype.recycleParticle = function (particle) {
  28328. var lastParticle = this.particles.pop();
  28329. if (lastParticle !== particle) {
  28330. lastParticle.copyTo(particle);
  28331. this._stockParticles.push(lastParticle);
  28332. }
  28333. };
  28334. ParticleSystem.prototype.getCapacity = function () {
  28335. return this._capacity;
  28336. };
  28337. ParticleSystem.prototype.isAlive = function () {
  28338. return this._alive;
  28339. };
  28340. ParticleSystem.prototype.isStarted = function () {
  28341. return this._started;
  28342. };
  28343. ParticleSystem.prototype.start = function () {
  28344. this._started = true;
  28345. this._stopped = false;
  28346. this._actualFrame = 0;
  28347. };
  28348. ParticleSystem.prototype.stop = function () {
  28349. this._stopped = true;
  28350. };
  28351. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  28352. var offset = index * 11;
  28353. this._vertexData[offset] = particle.position.x;
  28354. this._vertexData[offset + 1] = particle.position.y;
  28355. this._vertexData[offset + 2] = particle.position.z;
  28356. this._vertexData[offset + 3] = particle.color.r;
  28357. this._vertexData[offset + 4] = particle.color.g;
  28358. this._vertexData[offset + 5] = particle.color.b;
  28359. this._vertexData[offset + 6] = particle.color.a;
  28360. this._vertexData[offset + 7] = particle.angle;
  28361. this._vertexData[offset + 8] = particle.size;
  28362. this._vertexData[offset + 9] = offsetX;
  28363. this._vertexData[offset + 10] = offsetY;
  28364. };
  28365. ParticleSystem.prototype._update = function (newParticles) {
  28366. // Update current
  28367. this._alive = this.particles.length > 0;
  28368. this.updateFunction(this.particles);
  28369. // Add new ones
  28370. var worldMatrix;
  28371. if (this.emitter.position) {
  28372. worldMatrix = this.emitter.getWorldMatrix();
  28373. }
  28374. else {
  28375. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  28376. }
  28377. var particle;
  28378. for (var index = 0; index < newParticles; index++) {
  28379. if (this.particles.length === this._capacity) {
  28380. break;
  28381. }
  28382. if (this._stockParticles.length !== 0) {
  28383. particle = this._stockParticles.pop();
  28384. particle.age = 0;
  28385. }
  28386. else {
  28387. particle = new BABYLON.Particle();
  28388. }
  28389. this.particles.push(particle);
  28390. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  28391. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  28392. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  28393. particle.size = randomNumber(this.minSize, this.maxSize);
  28394. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  28395. this.startPositionFunction(worldMatrix, particle.position, particle);
  28396. var step = randomNumber(0, 1.0);
  28397. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  28398. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  28399. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  28400. }
  28401. };
  28402. ParticleSystem.prototype._getEffect = function () {
  28403. if (this._customEffect) {
  28404. return this._customEffect;
  28405. }
  28406. ;
  28407. var defines = [];
  28408. if (this._scene.clipPlane) {
  28409. defines.push("#define CLIPPLANE");
  28410. }
  28411. // Effect
  28412. var join = defines.join("\n");
  28413. if (this._cachedDefines !== join) {
  28414. this._cachedDefines = join;
  28415. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  28416. }
  28417. return this._effect;
  28418. };
  28419. ParticleSystem.prototype.animate = function () {
  28420. if (!this._started)
  28421. return;
  28422. var effect = this._getEffect();
  28423. // Check
  28424. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  28425. return;
  28426. if (this._currentRenderId === this._scene.getRenderId()) {
  28427. return;
  28428. }
  28429. this._currentRenderId = this._scene.getRenderId();
  28430. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  28431. // determine the number of particles we need to create
  28432. var newParticles;
  28433. if (this.manualEmitCount > -1) {
  28434. newParticles = this.manualEmitCount;
  28435. this._newPartsExcess = 0;
  28436. this.manualEmitCount = 0;
  28437. }
  28438. else {
  28439. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  28440. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  28441. }
  28442. if (this._newPartsExcess > 1.0) {
  28443. newParticles += this._newPartsExcess >> 0;
  28444. this._newPartsExcess -= this._newPartsExcess >> 0;
  28445. }
  28446. this._alive = false;
  28447. if (!this._stopped) {
  28448. this._actualFrame += this._scaledUpdateSpeed;
  28449. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  28450. this.stop();
  28451. }
  28452. else {
  28453. newParticles = 0;
  28454. }
  28455. this._update(newParticles);
  28456. // Stopped?
  28457. if (this._stopped) {
  28458. if (!this._alive) {
  28459. this._started = false;
  28460. if (this.disposeOnStop) {
  28461. this._scene._toBeDisposed.push(this);
  28462. }
  28463. }
  28464. }
  28465. // Update VBO
  28466. var offset = 0;
  28467. for (var index = 0; index < this.particles.length; index++) {
  28468. var particle = this.particles[index];
  28469. this._appendParticleVertex(offset++, particle, 0, 0);
  28470. this._appendParticleVertex(offset++, particle, 1, 0);
  28471. this._appendParticleVertex(offset++, particle, 1, 1);
  28472. this._appendParticleVertex(offset++, particle, 0, 1);
  28473. }
  28474. this._vertexBuffer.update(this._vertexData);
  28475. };
  28476. ParticleSystem.prototype.render = function () {
  28477. var effect = this._getEffect();
  28478. // Check
  28479. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  28480. return 0;
  28481. var engine = this._scene.getEngine();
  28482. // Render
  28483. engine.enableEffect(effect);
  28484. engine.setState(false);
  28485. var viewMatrix = this._scene.getViewMatrix();
  28486. effect.setTexture("diffuseSampler", this.particleTexture);
  28487. effect.setMatrix("view", viewMatrix);
  28488. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28489. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  28490. if (this._scene.clipPlane) {
  28491. var clipPlane = this._scene.clipPlane;
  28492. var invView = viewMatrix.clone();
  28493. invView.invert();
  28494. effect.setMatrix("invView", invView);
  28495. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  28496. }
  28497. // VBOs
  28498. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28499. // Draw order
  28500. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  28501. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  28502. }
  28503. else {
  28504. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28505. }
  28506. if (this.forceDepthWrite) {
  28507. engine.setDepthWrite(true);
  28508. }
  28509. engine.draw(true, 0, this.particles.length * 6);
  28510. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28511. return this.particles.length;
  28512. };
  28513. ParticleSystem.prototype.dispose = function () {
  28514. if (this._vertexBuffer) {
  28515. this._vertexBuffer.dispose();
  28516. this._vertexBuffer = null;
  28517. }
  28518. if (this._indexBuffer) {
  28519. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28520. this._indexBuffer = null;
  28521. }
  28522. if (this.particleTexture) {
  28523. this.particleTexture.dispose();
  28524. this.particleTexture = null;
  28525. }
  28526. // Remove from scene
  28527. var index = this._scene.particleSystems.indexOf(this);
  28528. this._scene.particleSystems.splice(index, 1);
  28529. // Callback
  28530. this.onDisposeObservable.notifyObservers(this);
  28531. this.onDisposeObservable.clear();
  28532. };
  28533. // Clone
  28534. ParticleSystem.prototype.clone = function (name, newEmitter) {
  28535. var result = new ParticleSystem(name, this._capacity, this._scene);
  28536. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  28537. if (newEmitter === undefined) {
  28538. newEmitter = this.emitter;
  28539. }
  28540. result.emitter = newEmitter;
  28541. if (this.particleTexture) {
  28542. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  28543. }
  28544. result.start();
  28545. return result;
  28546. };
  28547. ParticleSystem.prototype.serialize = function () {
  28548. var serializationObject = {};
  28549. serializationObject.name = this.name;
  28550. serializationObject.id = this.id;
  28551. // Emitter
  28552. if (this.emitter.position) {
  28553. serializationObject.emitterId = this.emitter.id;
  28554. }
  28555. else {
  28556. serializationObject.emitter = this.emitter.asArray();
  28557. }
  28558. serializationObject.capacity = this.getCapacity();
  28559. if (this.particleTexture) {
  28560. serializationObject.textureName = this.particleTexture.name;
  28561. }
  28562. // Animations
  28563. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28564. // Particle system
  28565. serializationObject.minAngularSpeed = this.minAngularSpeed;
  28566. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  28567. serializationObject.minSize = this.minSize;
  28568. serializationObject.maxSize = this.maxSize;
  28569. serializationObject.minEmitPower = this.minEmitPower;
  28570. serializationObject.maxEmitPower = this.maxEmitPower;
  28571. serializationObject.minLifeTime = this.minLifeTime;
  28572. serializationObject.maxLifeTime = this.maxLifeTime;
  28573. serializationObject.emitRate = this.emitRate;
  28574. serializationObject.minEmitBox = this.minEmitBox.asArray();
  28575. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  28576. serializationObject.gravity = this.gravity.asArray();
  28577. serializationObject.direction1 = this.direction1.asArray();
  28578. serializationObject.direction2 = this.direction2.asArray();
  28579. serializationObject.color1 = this.color1.asArray();
  28580. serializationObject.color2 = this.color2.asArray();
  28581. serializationObject.colorDead = this.colorDead.asArray();
  28582. serializationObject.updateSpeed = this.updateSpeed;
  28583. serializationObject.targetStopDuration = this.targetStopDuration;
  28584. serializationObject.textureMask = this.textureMask.asArray();
  28585. serializationObject.blendMode = this.blendMode;
  28586. return serializationObject;
  28587. };
  28588. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  28589. var name = parsedParticleSystem.name;
  28590. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  28591. if (parsedParticleSystem.id) {
  28592. particleSystem.id = parsedParticleSystem.id;
  28593. }
  28594. // Texture
  28595. if (parsedParticleSystem.textureName) {
  28596. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  28597. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  28598. }
  28599. // Emitter
  28600. if (parsedParticleSystem.emitterId) {
  28601. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  28602. }
  28603. else {
  28604. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  28605. }
  28606. // Animations
  28607. if (parsedParticleSystem.animations) {
  28608. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  28609. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  28610. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28611. }
  28612. }
  28613. if (parsedParticleSystem.autoAnimate) {
  28614. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  28615. }
  28616. // Particle system
  28617. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  28618. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  28619. particleSystem.minSize = parsedParticleSystem.minSize;
  28620. particleSystem.maxSize = parsedParticleSystem.maxSize;
  28621. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  28622. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  28623. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  28624. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  28625. particleSystem.emitRate = parsedParticleSystem.emitRate;
  28626. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  28627. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  28628. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  28629. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  28630. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  28631. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  28632. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  28633. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  28634. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  28635. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  28636. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  28637. particleSystem.blendMode = parsedParticleSystem.blendMode;
  28638. if (!parsedParticleSystem.preventAutoStart) {
  28639. particleSystem.start();
  28640. }
  28641. return particleSystem;
  28642. };
  28643. // Statics
  28644. ParticleSystem.BLENDMODE_ONEONE = 0;
  28645. ParticleSystem.BLENDMODE_STANDARD = 1;
  28646. return ParticleSystem;
  28647. }());
  28648. BABYLON.ParticleSystem = ParticleSystem;
  28649. })(BABYLON || (BABYLON = {}));
  28650. //# sourceMappingURL=../Particles/babylon.particleSystem.js.map
  28651. var BABYLON;
  28652. (function (BABYLON) {
  28653. var AnimationRange = (function () {
  28654. function AnimationRange(name, from, to) {
  28655. this.name = name;
  28656. this.from = from;
  28657. this.to = to;
  28658. }
  28659. AnimationRange.prototype.clone = function () {
  28660. return new AnimationRange(this.name, this.from, this.to);
  28661. };
  28662. return AnimationRange;
  28663. }());
  28664. BABYLON.AnimationRange = AnimationRange;
  28665. /**
  28666. * Composed of a frame, and an action function
  28667. */
  28668. var AnimationEvent = (function () {
  28669. function AnimationEvent(frame, action, onlyOnce) {
  28670. this.frame = frame;
  28671. this.action = action;
  28672. this.onlyOnce = onlyOnce;
  28673. this.isDone = false;
  28674. }
  28675. return AnimationEvent;
  28676. }());
  28677. BABYLON.AnimationEvent = AnimationEvent;
  28678. var PathCursor = (function () {
  28679. function PathCursor(path) {
  28680. this.path = path;
  28681. this._onchange = new Array();
  28682. this.value = 0;
  28683. this.animations = new Array();
  28684. }
  28685. PathCursor.prototype.getPoint = function () {
  28686. var point = this.path.getPointAtLengthPosition(this.value);
  28687. return new BABYLON.Vector3(point.x, 0, point.y);
  28688. };
  28689. PathCursor.prototype.moveAhead = function (step) {
  28690. if (step === void 0) { step = 0.002; }
  28691. this.move(step);
  28692. return this;
  28693. };
  28694. PathCursor.prototype.moveBack = function (step) {
  28695. if (step === void 0) { step = 0.002; }
  28696. this.move(-step);
  28697. return this;
  28698. };
  28699. PathCursor.prototype.move = function (step) {
  28700. if (Math.abs(step) > 1) {
  28701. throw "step size should be less than 1.";
  28702. }
  28703. this.value += step;
  28704. this.ensureLimits();
  28705. this.raiseOnChange();
  28706. return this;
  28707. };
  28708. PathCursor.prototype.ensureLimits = function () {
  28709. while (this.value > 1) {
  28710. this.value -= 1;
  28711. }
  28712. while (this.value < 0) {
  28713. this.value += 1;
  28714. }
  28715. return this;
  28716. };
  28717. // used by animation engine
  28718. PathCursor.prototype.markAsDirty = function (propertyName) {
  28719. this.ensureLimits();
  28720. this.raiseOnChange();
  28721. return this;
  28722. };
  28723. PathCursor.prototype.raiseOnChange = function () {
  28724. var _this = this;
  28725. this._onchange.forEach(function (f) { return f(_this); });
  28726. return this;
  28727. };
  28728. PathCursor.prototype.onchange = function (f) {
  28729. this._onchange.push(f);
  28730. return this;
  28731. };
  28732. return PathCursor;
  28733. }());
  28734. BABYLON.PathCursor = PathCursor;
  28735. var Animation = (function () {
  28736. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  28737. this.name = name;
  28738. this.targetProperty = targetProperty;
  28739. this.framePerSecond = framePerSecond;
  28740. this.dataType = dataType;
  28741. this.loopMode = loopMode;
  28742. this.enableBlending = enableBlending;
  28743. this._offsetsCache = {};
  28744. this._highLimitsCache = {};
  28745. this._stopped = false;
  28746. this._blendingFactor = 0;
  28747. // The set of event that will be linked to this animation
  28748. this._events = new Array();
  28749. this.allowMatricesInterpolation = false;
  28750. this.blendingSpeed = 0.01;
  28751. this._ranges = {};
  28752. this.targetPropertyPath = targetProperty.split(".");
  28753. this.dataType = dataType;
  28754. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  28755. }
  28756. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  28757. var dataType = undefined;
  28758. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  28759. dataType = Animation.ANIMATIONTYPE_FLOAT;
  28760. }
  28761. else if (from instanceof BABYLON.Quaternion) {
  28762. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  28763. }
  28764. else if (from instanceof BABYLON.Vector3) {
  28765. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  28766. }
  28767. else if (from instanceof BABYLON.Vector2) {
  28768. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  28769. }
  28770. else if (from instanceof BABYLON.Color3) {
  28771. dataType = Animation.ANIMATIONTYPE_COLOR3;
  28772. }
  28773. else if (from instanceof BABYLON.Size) {
  28774. dataType = Animation.ANIMATIONTYPE_SIZE;
  28775. }
  28776. if (dataType == undefined) {
  28777. return null;
  28778. }
  28779. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  28780. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  28781. animation.setKeys(keys);
  28782. if (easingFunction !== undefined) {
  28783. animation.setEasingFunction(easingFunction);
  28784. }
  28785. return animation;
  28786. };
  28787. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28788. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28789. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28790. };
  28791. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28792. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28793. node.animations.push(animation);
  28794. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28795. };
  28796. // Methods
  28797. /**
  28798. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28799. */
  28800. Animation.prototype.toString = function (fullDetails) {
  28801. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  28802. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  28803. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  28804. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28805. if (fullDetails) {
  28806. ret += ", Ranges: {";
  28807. var first = true;
  28808. for (var name in this._ranges) {
  28809. if (first) {
  28810. ret += ", ";
  28811. first = false;
  28812. }
  28813. ret += name;
  28814. }
  28815. ret += "}";
  28816. }
  28817. return ret;
  28818. };
  28819. /**
  28820. * Add an event to this animation.
  28821. */
  28822. Animation.prototype.addEvent = function (event) {
  28823. this._events.push(event);
  28824. };
  28825. /**
  28826. * Remove all events found at the given frame
  28827. * @param frame
  28828. */
  28829. Animation.prototype.removeEvents = function (frame) {
  28830. for (var index = 0; index < this._events.length; index++) {
  28831. if (this._events[index].frame === frame) {
  28832. this._events.splice(index, 1);
  28833. index--;
  28834. }
  28835. }
  28836. };
  28837. Animation.prototype.createRange = function (name, from, to) {
  28838. // check name not already in use; could happen for bones after serialized
  28839. if (!this._ranges[name]) {
  28840. this._ranges[name] = new AnimationRange(name, from, to);
  28841. }
  28842. };
  28843. Animation.prototype.deleteRange = function (name, deleteFrames) {
  28844. if (deleteFrames === void 0) { deleteFrames = true; }
  28845. if (this._ranges[name]) {
  28846. if (deleteFrames) {
  28847. var from = this._ranges[name].from;
  28848. var to = this._ranges[name].to;
  28849. // this loop MUST go high to low for multiple splices to work
  28850. for (var key = this._keys.length - 1; key >= 0; key--) {
  28851. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  28852. this._keys.splice(key, 1);
  28853. }
  28854. }
  28855. }
  28856. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28857. }
  28858. };
  28859. Animation.prototype.getRange = function (name) {
  28860. return this._ranges[name];
  28861. };
  28862. Animation.prototype.reset = function () {
  28863. this._offsetsCache = {};
  28864. this._highLimitsCache = {};
  28865. this.currentFrame = 0;
  28866. this._blendingFactor = 0;
  28867. this._originalBlendValue = null;
  28868. };
  28869. Animation.prototype.isStopped = function () {
  28870. return this._stopped;
  28871. };
  28872. Animation.prototype.getKeys = function () {
  28873. return this._keys;
  28874. };
  28875. Animation.prototype.getHighestFrame = function () {
  28876. var ret = 0;
  28877. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  28878. if (ret < this._keys[key].frame) {
  28879. ret = this._keys[key].frame;
  28880. }
  28881. }
  28882. return ret;
  28883. };
  28884. Animation.prototype.getEasingFunction = function () {
  28885. return this._easingFunction;
  28886. };
  28887. Animation.prototype.setEasingFunction = function (easingFunction) {
  28888. this._easingFunction = easingFunction;
  28889. };
  28890. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  28891. return startValue + (endValue - startValue) * gradient;
  28892. };
  28893. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  28894. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  28895. };
  28896. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  28897. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  28898. };
  28899. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  28900. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  28901. };
  28902. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  28903. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  28904. };
  28905. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  28906. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  28907. };
  28908. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  28909. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  28910. };
  28911. Animation.prototype.clone = function () {
  28912. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  28913. if (this._keys) {
  28914. clone.setKeys(this._keys);
  28915. }
  28916. if (this._ranges) {
  28917. clone._ranges = {};
  28918. for (var name in this._ranges) {
  28919. clone._ranges[name] = this._ranges[name].clone();
  28920. }
  28921. }
  28922. return clone;
  28923. };
  28924. Animation.prototype.setKeys = function (values) {
  28925. this._keys = values.slice(0);
  28926. this._offsetsCache = {};
  28927. this._highLimitsCache = {};
  28928. };
  28929. Animation.prototype._getKeyValue = function (value) {
  28930. if (typeof value === "function") {
  28931. return value();
  28932. }
  28933. return value;
  28934. };
  28935. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  28936. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  28937. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  28938. }
  28939. this.currentFrame = currentFrame;
  28940. // Try to get a hash to find the right key
  28941. 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));
  28942. if (this._keys[startKey].frame >= currentFrame) {
  28943. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  28944. startKey--;
  28945. }
  28946. }
  28947. for (var key = startKey; key < this._keys.length; key++) {
  28948. if (this._keys[key + 1].frame >= currentFrame) {
  28949. var startValue = this._getKeyValue(this._keys[key].value);
  28950. var endValue = this._getKeyValue(this._keys[key + 1].value);
  28951. // gradient : percent of currentFrame between the frame inf and the frame sup
  28952. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  28953. // check for easingFunction and correction of gradient
  28954. if (this._easingFunction != null) {
  28955. gradient = this._easingFunction.ease(gradient);
  28956. }
  28957. switch (this.dataType) {
  28958. // Float
  28959. case Animation.ANIMATIONTYPE_FLOAT:
  28960. switch (loopMode) {
  28961. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28962. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28963. return this.floatInterpolateFunction(startValue, endValue, gradient);
  28964. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28965. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  28966. }
  28967. break;
  28968. // Quaternion
  28969. case Animation.ANIMATIONTYPE_QUATERNION:
  28970. var quaternion = null;
  28971. switch (loopMode) {
  28972. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28973. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28974. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  28975. break;
  28976. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28977. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28978. break;
  28979. }
  28980. return quaternion;
  28981. // Vector3
  28982. case Animation.ANIMATIONTYPE_VECTOR3:
  28983. switch (loopMode) {
  28984. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28985. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28986. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  28987. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28988. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28989. }
  28990. // Vector2
  28991. case Animation.ANIMATIONTYPE_VECTOR2:
  28992. switch (loopMode) {
  28993. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28994. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28995. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  28996. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28997. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28998. }
  28999. // Size
  29000. case Animation.ANIMATIONTYPE_SIZE:
  29001. switch (loopMode) {
  29002. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29003. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29004. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  29005. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29006. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29007. }
  29008. // Color3
  29009. case Animation.ANIMATIONTYPE_COLOR3:
  29010. switch (loopMode) {
  29011. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29012. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29013. return this.color3InterpolateFunction(startValue, endValue, gradient);
  29014. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29015. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29016. }
  29017. // Matrix
  29018. case Animation.ANIMATIONTYPE_MATRIX:
  29019. switch (loopMode) {
  29020. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29021. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29022. if (this.allowMatricesInterpolation) {
  29023. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  29024. }
  29025. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29026. return startValue;
  29027. }
  29028. default:
  29029. break;
  29030. }
  29031. break;
  29032. }
  29033. }
  29034. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  29035. };
  29036. Animation.prototype.setValue = function (currentValue, blend) {
  29037. if (blend === void 0) { blend = false; }
  29038. // Set value
  29039. var path;
  29040. var destination;
  29041. if (this.targetPropertyPath.length > 1) {
  29042. var property = this._target[this.targetPropertyPath[0]];
  29043. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  29044. property = property[this.targetPropertyPath[index]];
  29045. }
  29046. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  29047. destination = property;
  29048. }
  29049. else {
  29050. path = this.targetPropertyPath[0];
  29051. destination = this._target;
  29052. }
  29053. // Blending
  29054. if (this.enableBlending && this._blendingFactor <= 1.0) {
  29055. if (!this._originalBlendValue) {
  29056. if (destination[path].clone) {
  29057. this._originalBlendValue = destination[path].clone();
  29058. }
  29059. else {
  29060. this._originalBlendValue = destination[path];
  29061. }
  29062. }
  29063. if (this._originalBlendValue.prototype) {
  29064. if (this._originalBlendValue.prototype.Lerp) {
  29065. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  29066. }
  29067. else {
  29068. destination[path] = currentValue;
  29069. }
  29070. }
  29071. else if (this._originalBlendValue.m) {
  29072. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  29073. }
  29074. else {
  29075. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  29076. }
  29077. this._blendingFactor += this.blendingSpeed;
  29078. }
  29079. else {
  29080. destination[path] = currentValue;
  29081. }
  29082. if (this._target.markAsDirty) {
  29083. this._target.markAsDirty(this.targetProperty);
  29084. }
  29085. };
  29086. Animation.prototype.goToFrame = function (frame) {
  29087. if (frame < this._keys[0].frame) {
  29088. frame = this._keys[0].frame;
  29089. }
  29090. else if (frame > this._keys[this._keys.length - 1].frame) {
  29091. frame = this._keys[this._keys.length - 1].frame;
  29092. }
  29093. var currentValue = this._interpolate(frame, 0, this.loopMode);
  29094. this.setValue(currentValue);
  29095. };
  29096. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  29097. if (blend === void 0) { blend = false; }
  29098. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  29099. this._stopped = true;
  29100. return false;
  29101. }
  29102. var returnValue = true;
  29103. // Adding a start key at frame 0 if missing
  29104. if (this._keys[0].frame !== 0) {
  29105. var newKey = { frame: 0, value: this._keys[0].value };
  29106. this._keys.splice(0, 0, newKey);
  29107. }
  29108. // Check limits
  29109. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  29110. from = this._keys[0].frame;
  29111. }
  29112. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  29113. to = this._keys[this._keys.length - 1].frame;
  29114. }
  29115. //to and from cannot be the same key
  29116. if (from === to) {
  29117. from++;
  29118. }
  29119. // Compute ratio
  29120. var range = to - from;
  29121. var offsetValue;
  29122. // ratio represents the frame delta between from and to
  29123. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  29124. var highLimitValue = 0;
  29125. if (ratio > range && !loop) {
  29126. returnValue = false;
  29127. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  29128. }
  29129. else {
  29130. // Get max value if required
  29131. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  29132. var keyOffset = to.toString() + from.toString();
  29133. if (!this._offsetsCache[keyOffset]) {
  29134. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29135. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29136. switch (this.dataType) {
  29137. // Float
  29138. case Animation.ANIMATIONTYPE_FLOAT:
  29139. this._offsetsCache[keyOffset] = toValue - fromValue;
  29140. break;
  29141. // Quaternion
  29142. case Animation.ANIMATIONTYPE_QUATERNION:
  29143. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29144. break;
  29145. // Vector3
  29146. case Animation.ANIMATIONTYPE_VECTOR3:
  29147. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29148. // Vector2
  29149. case Animation.ANIMATIONTYPE_VECTOR2:
  29150. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29151. // Size
  29152. case Animation.ANIMATIONTYPE_SIZE:
  29153. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29154. // Color3
  29155. case Animation.ANIMATIONTYPE_COLOR3:
  29156. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29157. default:
  29158. break;
  29159. }
  29160. this._highLimitsCache[keyOffset] = toValue;
  29161. }
  29162. highLimitValue = this._highLimitsCache[keyOffset];
  29163. offsetValue = this._offsetsCache[keyOffset];
  29164. }
  29165. }
  29166. if (offsetValue === undefined) {
  29167. switch (this.dataType) {
  29168. // Float
  29169. case Animation.ANIMATIONTYPE_FLOAT:
  29170. offsetValue = 0;
  29171. break;
  29172. // Quaternion
  29173. case Animation.ANIMATIONTYPE_QUATERNION:
  29174. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  29175. break;
  29176. // Vector3
  29177. case Animation.ANIMATIONTYPE_VECTOR3:
  29178. offsetValue = BABYLON.Vector3.Zero();
  29179. break;
  29180. // Vector2
  29181. case Animation.ANIMATIONTYPE_VECTOR2:
  29182. offsetValue = BABYLON.Vector2.Zero();
  29183. break;
  29184. // Size
  29185. case Animation.ANIMATIONTYPE_SIZE:
  29186. offsetValue = BABYLON.Size.Zero();
  29187. break;
  29188. // Color3
  29189. case Animation.ANIMATIONTYPE_COLOR3:
  29190. offsetValue = BABYLON.Color3.Black();
  29191. }
  29192. }
  29193. // Compute value
  29194. var repeatCount = (ratio / range) >> 0;
  29195. var currentFrame = returnValue ? from + ratio % range : to;
  29196. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  29197. // Set value
  29198. this.setValue(currentValue);
  29199. // Check events
  29200. for (var index = 0; index < this._events.length; index++) {
  29201. if (currentFrame >= this._events[index].frame) {
  29202. var event = this._events[index];
  29203. if (!event.isDone) {
  29204. // If event should be done only once, remove it.
  29205. if (event.onlyOnce) {
  29206. this._events.splice(index, 1);
  29207. index--;
  29208. }
  29209. event.isDone = true;
  29210. event.action();
  29211. } // Don't do anything if the event has already be done.
  29212. }
  29213. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  29214. // reset event, the animation is looping
  29215. this._events[index].isDone = false;
  29216. }
  29217. }
  29218. if (!returnValue) {
  29219. this._stopped = true;
  29220. }
  29221. return returnValue;
  29222. };
  29223. Animation.prototype.serialize = function () {
  29224. var serializationObject = {};
  29225. serializationObject.name = this.name;
  29226. serializationObject.property = this.targetProperty;
  29227. serializationObject.framePerSecond = this.framePerSecond;
  29228. serializationObject.dataType = this.dataType;
  29229. serializationObject.loopBehavior = this.loopMode;
  29230. var dataType = this.dataType;
  29231. serializationObject.keys = [];
  29232. var keys = this.getKeys();
  29233. for (var index = 0; index < keys.length; index++) {
  29234. var animationKey = keys[index];
  29235. var key = {};
  29236. key.frame = animationKey.frame;
  29237. switch (dataType) {
  29238. case Animation.ANIMATIONTYPE_FLOAT:
  29239. key.values = [animationKey.value];
  29240. break;
  29241. case Animation.ANIMATIONTYPE_QUATERNION:
  29242. case Animation.ANIMATIONTYPE_MATRIX:
  29243. case Animation.ANIMATIONTYPE_VECTOR3:
  29244. case Animation.ANIMATIONTYPE_COLOR3:
  29245. key.values = animationKey.value.asArray();
  29246. break;
  29247. }
  29248. serializationObject.keys.push(key);
  29249. }
  29250. serializationObject.ranges = [];
  29251. for (var name in this._ranges) {
  29252. var range = {};
  29253. range.name = name;
  29254. range.from = this._ranges[name].from;
  29255. range.to = this._ranges[name].to;
  29256. serializationObject.ranges.push(range);
  29257. }
  29258. return serializationObject;
  29259. };
  29260. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  29261. get: function () {
  29262. return Animation._ANIMATIONTYPE_FLOAT;
  29263. },
  29264. enumerable: true,
  29265. configurable: true
  29266. });
  29267. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  29268. get: function () {
  29269. return Animation._ANIMATIONTYPE_VECTOR3;
  29270. },
  29271. enumerable: true,
  29272. configurable: true
  29273. });
  29274. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  29275. get: function () {
  29276. return Animation._ANIMATIONTYPE_VECTOR2;
  29277. },
  29278. enumerable: true,
  29279. configurable: true
  29280. });
  29281. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  29282. get: function () {
  29283. return Animation._ANIMATIONTYPE_SIZE;
  29284. },
  29285. enumerable: true,
  29286. configurable: true
  29287. });
  29288. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  29289. get: function () {
  29290. return Animation._ANIMATIONTYPE_QUATERNION;
  29291. },
  29292. enumerable: true,
  29293. configurable: true
  29294. });
  29295. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  29296. get: function () {
  29297. return Animation._ANIMATIONTYPE_MATRIX;
  29298. },
  29299. enumerable: true,
  29300. configurable: true
  29301. });
  29302. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  29303. get: function () {
  29304. return Animation._ANIMATIONTYPE_COLOR3;
  29305. },
  29306. enumerable: true,
  29307. configurable: true
  29308. });
  29309. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  29310. get: function () {
  29311. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  29312. },
  29313. enumerable: true,
  29314. configurable: true
  29315. });
  29316. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  29317. get: function () {
  29318. return Animation._ANIMATIONLOOPMODE_CYCLE;
  29319. },
  29320. enumerable: true,
  29321. configurable: true
  29322. });
  29323. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  29324. get: function () {
  29325. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  29326. },
  29327. enumerable: true,
  29328. configurable: true
  29329. });
  29330. Animation.Parse = function (parsedAnimation) {
  29331. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  29332. var dataType = parsedAnimation.dataType;
  29333. var keys = [];
  29334. var data;
  29335. var index;
  29336. for (index = 0; index < parsedAnimation.keys.length; index++) {
  29337. var key = parsedAnimation.keys[index];
  29338. switch (dataType) {
  29339. case Animation.ANIMATIONTYPE_FLOAT:
  29340. data = key.values[0];
  29341. break;
  29342. case Animation.ANIMATIONTYPE_QUATERNION:
  29343. data = BABYLON.Quaternion.FromArray(key.values);
  29344. break;
  29345. case Animation.ANIMATIONTYPE_MATRIX:
  29346. data = BABYLON.Matrix.FromArray(key.values);
  29347. break;
  29348. case Animation.ANIMATIONTYPE_COLOR3:
  29349. data = BABYLON.Color3.FromArray(key.values);
  29350. break;
  29351. case Animation.ANIMATIONTYPE_VECTOR3:
  29352. default:
  29353. data = BABYLON.Vector3.FromArray(key.values);
  29354. break;
  29355. }
  29356. keys.push({
  29357. frame: key.frame,
  29358. value: data
  29359. });
  29360. }
  29361. animation.setKeys(keys);
  29362. if (parsedAnimation.ranges) {
  29363. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  29364. data = parsedAnimation.ranges[index];
  29365. animation.createRange(data.name, data.from, data.to);
  29366. }
  29367. }
  29368. return animation;
  29369. };
  29370. Animation.AppendSerializedAnimations = function (source, destination) {
  29371. if (source.animations) {
  29372. destination.animations = [];
  29373. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29374. var animation = source.animations[animationIndex];
  29375. destination.animations.push(animation.serialize());
  29376. }
  29377. }
  29378. };
  29379. // Statics
  29380. Animation._ANIMATIONTYPE_FLOAT = 0;
  29381. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  29382. Animation._ANIMATIONTYPE_QUATERNION = 2;
  29383. Animation._ANIMATIONTYPE_MATRIX = 3;
  29384. Animation._ANIMATIONTYPE_COLOR3 = 4;
  29385. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  29386. Animation._ANIMATIONTYPE_SIZE = 6;
  29387. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  29388. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  29389. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  29390. return Animation;
  29391. }());
  29392. BABYLON.Animation = Animation;
  29393. })(BABYLON || (BABYLON = {}));
  29394. //# sourceMappingURL=../Animations/babylon.animation.js.map
  29395. var BABYLON;
  29396. (function (BABYLON) {
  29397. var Animatable = (function () {
  29398. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  29399. if (fromFrame === void 0) { fromFrame = 0; }
  29400. if (toFrame === void 0) { toFrame = 100; }
  29401. if (loopAnimation === void 0) { loopAnimation = false; }
  29402. if (speedRatio === void 0) { speedRatio = 1.0; }
  29403. this.target = target;
  29404. this.fromFrame = fromFrame;
  29405. this.toFrame = toFrame;
  29406. this.loopAnimation = loopAnimation;
  29407. this.speedRatio = speedRatio;
  29408. this.onAnimationEnd = onAnimationEnd;
  29409. this._animations = new Array();
  29410. this._paused = false;
  29411. this.animationStarted = false;
  29412. if (animations) {
  29413. this.appendAnimations(target, animations);
  29414. }
  29415. this._scene = scene;
  29416. scene._activeAnimatables.push(this);
  29417. }
  29418. // Methods
  29419. Animatable.prototype.getAnimations = function () {
  29420. return this._animations;
  29421. };
  29422. Animatable.prototype.appendAnimations = function (target, animations) {
  29423. for (var index = 0; index < animations.length; index++) {
  29424. var animation = animations[index];
  29425. animation._target = target;
  29426. this._animations.push(animation);
  29427. }
  29428. };
  29429. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  29430. var animations = this._animations;
  29431. for (var index = 0; index < animations.length; index++) {
  29432. if (animations[index].targetProperty === property) {
  29433. return animations[index];
  29434. }
  29435. }
  29436. return null;
  29437. };
  29438. Animatable.prototype.reset = function () {
  29439. var animations = this._animations;
  29440. for (var index = 0; index < animations.length; index++) {
  29441. animations[index].reset();
  29442. }
  29443. this._localDelayOffset = null;
  29444. this._pausedDelay = null;
  29445. };
  29446. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29447. var animations = this._animations;
  29448. for (var index = 0; index < animations.length; index++) {
  29449. animations[index].enableBlending = true;
  29450. animations[index].blendingSpeed = blendingSpeed;
  29451. }
  29452. };
  29453. Animatable.prototype.disableBlending = function () {
  29454. var animations = this._animations;
  29455. for (var index = 0; index < animations.length; index++) {
  29456. animations[index].enableBlending = false;
  29457. }
  29458. };
  29459. Animatable.prototype.goToFrame = function (frame) {
  29460. var animations = this._animations;
  29461. if (animations[0]) {
  29462. var fps = animations[0].framePerSecond;
  29463. var currentFrame = animations[0].currentFrame;
  29464. var adjustTime = frame - currentFrame;
  29465. var delay = adjustTime * 1000 / fps;
  29466. this._localDelayOffset -= delay;
  29467. }
  29468. for (var index = 0; index < animations.length; index++) {
  29469. animations[index].goToFrame(frame);
  29470. }
  29471. };
  29472. Animatable.prototype.pause = function () {
  29473. if (this._paused) {
  29474. return;
  29475. }
  29476. this._paused = true;
  29477. };
  29478. Animatable.prototype.restart = function () {
  29479. this._paused = false;
  29480. };
  29481. Animatable.prototype.stop = function (animationName) {
  29482. var index = this._scene._activeAnimatables.indexOf(this);
  29483. if (index > -1) {
  29484. var animations = this._animations;
  29485. var numberOfAnimationsStopped = 0;
  29486. for (var index = animations.length - 1; index >= 0; index--) {
  29487. if (typeof animationName === "string" && animations[index].name != animationName) {
  29488. continue;
  29489. }
  29490. animations[index].reset();
  29491. animations.splice(index, 1);
  29492. numberOfAnimationsStopped++;
  29493. }
  29494. if (animations.length == numberOfAnimationsStopped) {
  29495. this._scene._activeAnimatables.splice(index, 1);
  29496. if (this.onAnimationEnd) {
  29497. this.onAnimationEnd();
  29498. }
  29499. }
  29500. }
  29501. };
  29502. Animatable.prototype._animate = function (delay) {
  29503. if (this._paused) {
  29504. this.animationStarted = false;
  29505. if (!this._pausedDelay) {
  29506. this._pausedDelay = delay;
  29507. }
  29508. return true;
  29509. }
  29510. if (!this._localDelayOffset) {
  29511. this._localDelayOffset = delay;
  29512. }
  29513. else if (this._pausedDelay) {
  29514. this._localDelayOffset += delay - this._pausedDelay;
  29515. this._pausedDelay = null;
  29516. }
  29517. // Animating
  29518. var running = false;
  29519. var animations = this._animations;
  29520. var index;
  29521. for (index = 0; index < animations.length; index++) {
  29522. var animation = animations[index];
  29523. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  29524. running = running || isRunning;
  29525. }
  29526. this.animationStarted = running;
  29527. if (!running) {
  29528. // Remove from active animatables
  29529. index = this._scene._activeAnimatables.indexOf(this);
  29530. this._scene._activeAnimatables.splice(index, 1);
  29531. }
  29532. if (!running && this.onAnimationEnd) {
  29533. this.onAnimationEnd();
  29534. this.onAnimationEnd = null;
  29535. }
  29536. return running;
  29537. };
  29538. return Animatable;
  29539. }());
  29540. BABYLON.Animatable = Animatable;
  29541. })(BABYLON || (BABYLON = {}));
  29542. //# sourceMappingURL=../Animations/babylon.animatable.js.map
  29543. var BABYLON;
  29544. (function (BABYLON) {
  29545. var EasingFunction = (function () {
  29546. function EasingFunction() {
  29547. // Properties
  29548. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  29549. }
  29550. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  29551. get: function () {
  29552. return EasingFunction._EASINGMODE_EASEIN;
  29553. },
  29554. enumerable: true,
  29555. configurable: true
  29556. });
  29557. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  29558. get: function () {
  29559. return EasingFunction._EASINGMODE_EASEOUT;
  29560. },
  29561. enumerable: true,
  29562. configurable: true
  29563. });
  29564. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  29565. get: function () {
  29566. return EasingFunction._EASINGMODE_EASEINOUT;
  29567. },
  29568. enumerable: true,
  29569. configurable: true
  29570. });
  29571. EasingFunction.prototype.setEasingMode = function (easingMode) {
  29572. var n = Math.min(Math.max(easingMode, 0), 2);
  29573. this._easingMode = n;
  29574. };
  29575. EasingFunction.prototype.getEasingMode = function () {
  29576. return this._easingMode;
  29577. };
  29578. EasingFunction.prototype.easeInCore = function (gradient) {
  29579. throw new Error('You must implement this method');
  29580. };
  29581. EasingFunction.prototype.ease = function (gradient) {
  29582. switch (this._easingMode) {
  29583. case EasingFunction.EASINGMODE_EASEIN:
  29584. return this.easeInCore(gradient);
  29585. case EasingFunction.EASINGMODE_EASEOUT:
  29586. return (1 - this.easeInCore(1 - gradient));
  29587. }
  29588. if (gradient >= 0.5) {
  29589. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29590. }
  29591. return (this.easeInCore(gradient * 2) * 0.5);
  29592. };
  29593. //Statics
  29594. EasingFunction._EASINGMODE_EASEIN = 0;
  29595. EasingFunction._EASINGMODE_EASEOUT = 1;
  29596. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29597. return EasingFunction;
  29598. }());
  29599. BABYLON.EasingFunction = EasingFunction;
  29600. var CircleEase = (function (_super) {
  29601. __extends(CircleEase, _super);
  29602. function CircleEase() {
  29603. _super.apply(this, arguments);
  29604. }
  29605. CircleEase.prototype.easeInCore = function (gradient) {
  29606. gradient = Math.max(0, Math.min(1, gradient));
  29607. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29608. };
  29609. return CircleEase;
  29610. }(EasingFunction));
  29611. BABYLON.CircleEase = CircleEase;
  29612. var BackEase = (function (_super) {
  29613. __extends(BackEase, _super);
  29614. function BackEase(amplitude) {
  29615. if (amplitude === void 0) { amplitude = 1; }
  29616. _super.call(this);
  29617. this.amplitude = amplitude;
  29618. }
  29619. BackEase.prototype.easeInCore = function (gradient) {
  29620. var num = Math.max(0, this.amplitude);
  29621. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29622. };
  29623. return BackEase;
  29624. }(EasingFunction));
  29625. BABYLON.BackEase = BackEase;
  29626. var BounceEase = (function (_super) {
  29627. __extends(BounceEase, _super);
  29628. function BounceEase(bounces, bounciness) {
  29629. if (bounces === void 0) { bounces = 3; }
  29630. if (bounciness === void 0) { bounciness = 2; }
  29631. _super.call(this);
  29632. this.bounces = bounces;
  29633. this.bounciness = bounciness;
  29634. }
  29635. BounceEase.prototype.easeInCore = function (gradient) {
  29636. var y = Math.max(0.0, this.bounces);
  29637. var bounciness = this.bounciness;
  29638. if (bounciness <= 1.0) {
  29639. bounciness = 1.001;
  29640. }
  29641. var num9 = Math.pow(bounciness, y);
  29642. var num5 = 1.0 - bounciness;
  29643. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  29644. var num15 = gradient * num4;
  29645. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  29646. var num3 = Math.floor(num65);
  29647. var num13 = num3 + 1.0;
  29648. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  29649. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  29650. var num7 = (num8 + num12) * 0.5;
  29651. var num6 = gradient - num7;
  29652. var num2 = num7 - num8;
  29653. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  29654. };
  29655. return BounceEase;
  29656. }(EasingFunction));
  29657. BABYLON.BounceEase = BounceEase;
  29658. var CubicEase = (function (_super) {
  29659. __extends(CubicEase, _super);
  29660. function CubicEase() {
  29661. _super.apply(this, arguments);
  29662. }
  29663. CubicEase.prototype.easeInCore = function (gradient) {
  29664. return (gradient * gradient * gradient);
  29665. };
  29666. return CubicEase;
  29667. }(EasingFunction));
  29668. BABYLON.CubicEase = CubicEase;
  29669. var ElasticEase = (function (_super) {
  29670. __extends(ElasticEase, _super);
  29671. function ElasticEase(oscillations, springiness) {
  29672. if (oscillations === void 0) { oscillations = 3; }
  29673. if (springiness === void 0) { springiness = 3; }
  29674. _super.call(this);
  29675. this.oscillations = oscillations;
  29676. this.springiness = springiness;
  29677. }
  29678. ElasticEase.prototype.easeInCore = function (gradient) {
  29679. var num2;
  29680. var num3 = Math.max(0.0, this.oscillations);
  29681. var num = Math.max(0.0, this.springiness);
  29682. if (num == 0) {
  29683. num2 = gradient;
  29684. }
  29685. else {
  29686. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  29687. }
  29688. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  29689. };
  29690. return ElasticEase;
  29691. }(EasingFunction));
  29692. BABYLON.ElasticEase = ElasticEase;
  29693. var ExponentialEase = (function (_super) {
  29694. __extends(ExponentialEase, _super);
  29695. function ExponentialEase(exponent) {
  29696. if (exponent === void 0) { exponent = 2; }
  29697. _super.call(this);
  29698. this.exponent = exponent;
  29699. }
  29700. ExponentialEase.prototype.easeInCore = function (gradient) {
  29701. if (this.exponent <= 0) {
  29702. return gradient;
  29703. }
  29704. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  29705. };
  29706. return ExponentialEase;
  29707. }(EasingFunction));
  29708. BABYLON.ExponentialEase = ExponentialEase;
  29709. var PowerEase = (function (_super) {
  29710. __extends(PowerEase, _super);
  29711. function PowerEase(power) {
  29712. if (power === void 0) { power = 2; }
  29713. _super.call(this);
  29714. this.power = power;
  29715. }
  29716. PowerEase.prototype.easeInCore = function (gradient) {
  29717. var y = Math.max(0.0, this.power);
  29718. return Math.pow(gradient, y);
  29719. };
  29720. return PowerEase;
  29721. }(EasingFunction));
  29722. BABYLON.PowerEase = PowerEase;
  29723. var QuadraticEase = (function (_super) {
  29724. __extends(QuadraticEase, _super);
  29725. function QuadraticEase() {
  29726. _super.apply(this, arguments);
  29727. }
  29728. QuadraticEase.prototype.easeInCore = function (gradient) {
  29729. return (gradient * gradient);
  29730. };
  29731. return QuadraticEase;
  29732. }(EasingFunction));
  29733. BABYLON.QuadraticEase = QuadraticEase;
  29734. var QuarticEase = (function (_super) {
  29735. __extends(QuarticEase, _super);
  29736. function QuarticEase() {
  29737. _super.apply(this, arguments);
  29738. }
  29739. QuarticEase.prototype.easeInCore = function (gradient) {
  29740. return (gradient * gradient * gradient * gradient);
  29741. };
  29742. return QuarticEase;
  29743. }(EasingFunction));
  29744. BABYLON.QuarticEase = QuarticEase;
  29745. var QuinticEase = (function (_super) {
  29746. __extends(QuinticEase, _super);
  29747. function QuinticEase() {
  29748. _super.apply(this, arguments);
  29749. }
  29750. QuinticEase.prototype.easeInCore = function (gradient) {
  29751. return (gradient * gradient * gradient * gradient * gradient);
  29752. };
  29753. return QuinticEase;
  29754. }(EasingFunction));
  29755. BABYLON.QuinticEase = QuinticEase;
  29756. var SineEase = (function (_super) {
  29757. __extends(SineEase, _super);
  29758. function SineEase() {
  29759. _super.apply(this, arguments);
  29760. }
  29761. SineEase.prototype.easeInCore = function (gradient) {
  29762. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  29763. };
  29764. return SineEase;
  29765. }(EasingFunction));
  29766. BABYLON.SineEase = SineEase;
  29767. var BezierCurveEase = (function (_super) {
  29768. __extends(BezierCurveEase, _super);
  29769. function BezierCurveEase(x1, y1, x2, y2) {
  29770. if (x1 === void 0) { x1 = 0; }
  29771. if (y1 === void 0) { y1 = 0; }
  29772. if (x2 === void 0) { x2 = 1; }
  29773. if (y2 === void 0) { y2 = 1; }
  29774. _super.call(this);
  29775. this.x1 = x1;
  29776. this.y1 = y1;
  29777. this.x2 = x2;
  29778. this.y2 = y2;
  29779. }
  29780. BezierCurveEase.prototype.easeInCore = function (gradient) {
  29781. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  29782. };
  29783. return BezierCurveEase;
  29784. }(EasingFunction));
  29785. BABYLON.BezierCurveEase = BezierCurveEase;
  29786. })(BABYLON || (BABYLON = {}));
  29787. //# sourceMappingURL=../Animations/babylon.easing.js.map
  29788. var BABYLON;
  29789. (function (BABYLON) {
  29790. var Bone = (function (_super) {
  29791. __extends(Bone, _super);
  29792. function Bone(name, skeleton, parentBone, matrix, restPose) {
  29793. _super.call(this, name, skeleton.getScene());
  29794. this.name = name;
  29795. this.children = new Array();
  29796. this.animations = new Array();
  29797. this._worldTransform = new BABYLON.Matrix();
  29798. this._absoluteTransform = new BABYLON.Matrix();
  29799. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  29800. this._scaleMatrix = BABYLON.Matrix.Identity();
  29801. this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  29802. this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  29803. this._scalingDeterminant = 1;
  29804. this._syncScaleVector = function () {
  29805. var lm = this.getLocalMatrix();
  29806. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  29807. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  29808. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  29809. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  29810. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  29811. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  29812. this._scaleVector.x = xs * Math.sqrt(xsq);
  29813. this._scaleVector.y = ys * Math.sqrt(ysq);
  29814. this._scaleVector.z = zs * Math.sqrt(zsq);
  29815. if (this._parent) {
  29816. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  29817. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  29818. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  29819. }
  29820. 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);
  29821. };
  29822. this._skeleton = skeleton;
  29823. this._matrix = matrix;
  29824. this._baseMatrix = matrix;
  29825. this._restPose = restPose ? restPose : matrix.clone();
  29826. skeleton.bones.push(this);
  29827. if (parentBone) {
  29828. this._parent = parentBone;
  29829. parentBone.children.push(this);
  29830. }
  29831. else {
  29832. this._parent = null;
  29833. }
  29834. this._updateDifferenceMatrix();
  29835. if (this.getAbsoluteTransform().determinant() < 0) {
  29836. this._scalingDeterminant *= -1;
  29837. }
  29838. }
  29839. // Members
  29840. Bone.prototype.getParent = function () {
  29841. return this._parent;
  29842. };
  29843. Bone.prototype.getLocalMatrix = function () {
  29844. return this._matrix;
  29845. };
  29846. Bone.prototype.getBaseMatrix = function () {
  29847. return this._baseMatrix;
  29848. };
  29849. Bone.prototype.getRestPose = function () {
  29850. return this._restPose;
  29851. };
  29852. Bone.prototype.returnToRest = function () {
  29853. this.updateMatrix(this._restPose.clone());
  29854. };
  29855. Bone.prototype.getWorldMatrix = function () {
  29856. return this._worldTransform;
  29857. };
  29858. Bone.prototype.getInvertedAbsoluteTransform = function () {
  29859. return this._invertedAbsoluteTransform;
  29860. };
  29861. Bone.prototype.getAbsoluteTransform = function () {
  29862. return this._absoluteTransform;
  29863. };
  29864. // Methods
  29865. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  29866. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  29867. this._baseMatrix = matrix.clone();
  29868. this._matrix = matrix.clone();
  29869. this._skeleton._markAsDirty();
  29870. if (updateDifferenceMatrix) {
  29871. this._updateDifferenceMatrix();
  29872. }
  29873. };
  29874. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  29875. if (!rootMatrix) {
  29876. rootMatrix = this._baseMatrix;
  29877. }
  29878. if (this._parent) {
  29879. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  29880. }
  29881. else {
  29882. this._absoluteTransform.copyFrom(rootMatrix);
  29883. }
  29884. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  29885. for (var index = 0; index < this.children.length; index++) {
  29886. this.children[index]._updateDifferenceMatrix();
  29887. }
  29888. };
  29889. Bone.prototype.markAsDirty = function () {
  29890. this._currentRenderId++;
  29891. this._skeleton._markAsDirty();
  29892. };
  29893. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  29894. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  29895. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  29896. // all animation may be coming from a library skeleton, so may need to create animation
  29897. if (this.animations.length === 0) {
  29898. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  29899. this.animations[0].setKeys([]);
  29900. }
  29901. // get animation info / verify there is such a range from the source bone
  29902. var sourceRange = source.animations[0].getRange(rangeName);
  29903. if (!sourceRange) {
  29904. return false;
  29905. }
  29906. var from = sourceRange.from;
  29907. var to = sourceRange.to;
  29908. var sourceKeys = source.animations[0].getKeys();
  29909. // rescaling prep
  29910. var sourceBoneLength = source.length;
  29911. var sourceParent = source.getParent();
  29912. var parent = this.getParent();
  29913. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  29914. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  29915. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  29916. var destKeys = this.animations[0].getKeys();
  29917. // loop vars declaration
  29918. var orig;
  29919. var origTranslation;
  29920. var mat;
  29921. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  29922. orig = sourceKeys[key];
  29923. if (orig.frame >= from && orig.frame <= to) {
  29924. if (rescaleAsRequired) {
  29925. mat = orig.value.clone();
  29926. // scale based on parent ratio, when bone has parent
  29927. if (parentScalingReqd) {
  29928. origTranslation = mat.getTranslation();
  29929. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  29930. }
  29931. else if (dimensionsScalingReqd) {
  29932. origTranslation = mat.getTranslation();
  29933. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  29934. }
  29935. else {
  29936. mat = orig.value;
  29937. }
  29938. }
  29939. else {
  29940. mat = orig.value;
  29941. }
  29942. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  29943. }
  29944. }
  29945. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  29946. return true;
  29947. };
  29948. Bone.prototype.translate = function (vec, space, mesh) {
  29949. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29950. var lm = this.getLocalMatrix();
  29951. if (space == BABYLON.Space.LOCAL) {
  29952. lm.m[12] += vec.x;
  29953. lm.m[13] += vec.y;
  29954. lm.m[14] += vec.z;
  29955. }
  29956. else {
  29957. this._skeleton.computeAbsoluteTransforms();
  29958. var tmat = BABYLON.Tmp.Matrix[0];
  29959. var tvec = BABYLON.Tmp.Vector3[0];
  29960. if (mesh) {
  29961. tmat.copyFrom(this._parent.getAbsoluteTransform());
  29962. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  29963. }
  29964. else {
  29965. tmat.copyFrom(this._parent.getAbsoluteTransform());
  29966. }
  29967. tmat.m[12] = 0;
  29968. tmat.m[13] = 0;
  29969. tmat.m[14] = 0;
  29970. tmat.invert();
  29971. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  29972. lm.m[12] += tvec.x;
  29973. lm.m[13] += tvec.y;
  29974. lm.m[14] += tvec.z;
  29975. }
  29976. this.markAsDirty();
  29977. };
  29978. Bone.prototype.setPosition = function (position, space, mesh) {
  29979. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29980. var lm = this.getLocalMatrix();
  29981. if (space == BABYLON.Space.LOCAL) {
  29982. lm.m[12] = position.x;
  29983. lm.m[13] = position.y;
  29984. lm.m[14] = position.z;
  29985. }
  29986. else {
  29987. this._skeleton.computeAbsoluteTransforms();
  29988. var tmat = BABYLON.Tmp.Matrix[0];
  29989. var vec = BABYLON.Tmp.Vector3[0];
  29990. if (mesh) {
  29991. tmat.copyFrom(this._parent.getAbsoluteTransform());
  29992. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  29993. }
  29994. else {
  29995. tmat.copyFrom(this._parent.getAbsoluteTransform());
  29996. }
  29997. tmat.invert();
  29998. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  29999. lm.m[12] = vec.x;
  30000. lm.m[13] = vec.y;
  30001. lm.m[14] = vec.z;
  30002. }
  30003. this.markAsDirty();
  30004. };
  30005. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  30006. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  30007. };
  30008. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  30009. if (scaleChildren === void 0) { scaleChildren = false; }
  30010. if (this.animations[0] && !this.animations[0].isStopped()) {
  30011. if (!scaleChildren) {
  30012. this._negateScaleChildren.x = 1 / x;
  30013. this._negateScaleChildren.y = 1 / y;
  30014. this._negateScaleChildren.z = 1 / z;
  30015. }
  30016. this._syncScaleVector();
  30017. }
  30018. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  30019. };
  30020. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  30021. if (scaleChildren === void 0) { scaleChildren = false; }
  30022. var locMat = this.getLocalMatrix();
  30023. var origLocMat = BABYLON.Tmp.Matrix[0];
  30024. origLocMat.copyFrom(locMat);
  30025. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  30026. origLocMatInv.copyFrom(origLocMat);
  30027. origLocMatInv.invert();
  30028. var scaleMat = BABYLON.Tmp.Matrix[2];
  30029. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  30030. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  30031. this._scaleVector.x *= x;
  30032. this._scaleVector.y *= y;
  30033. this._scaleVector.z *= z;
  30034. locMat.multiplyToRef(origLocMatInv, locMat);
  30035. locMat.multiplyToRef(scaleMat, locMat);
  30036. locMat.multiplyToRef(origLocMat, locMat);
  30037. var parent = this.getParent();
  30038. if (parent) {
  30039. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  30040. }
  30041. else {
  30042. this.getAbsoluteTransform().copyFrom(locMat);
  30043. }
  30044. var len = this.children.length;
  30045. scaleMat.invert();
  30046. for (var i = 0; i < len; i++) {
  30047. var child = this.children[i];
  30048. var cm = child.getLocalMatrix();
  30049. cm.multiplyToRef(scaleMat, cm);
  30050. var lm = child.getLocalMatrix();
  30051. lm.m[12] *= x;
  30052. lm.m[13] *= y;
  30053. lm.m[14] *= z;
  30054. }
  30055. this.computeAbsoluteTransforms();
  30056. if (scaleChildren) {
  30057. for (var i = 0; i < len; i++) {
  30058. this.children[i].scale(x, y, z, scaleChildren);
  30059. }
  30060. }
  30061. this.markAsDirty();
  30062. };
  30063. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  30064. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30065. var rotMat = BABYLON.Tmp.Matrix[0];
  30066. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  30067. var rotMatInv = BABYLON.Tmp.Matrix[1];
  30068. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30069. rotMatInv.multiplyToRef(rotMat, rotMat);
  30070. this._rotateWithMatrix(rotMat, space, mesh);
  30071. };
  30072. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  30073. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30074. var rmat = BABYLON.Tmp.Matrix[0];
  30075. rmat.m[12] = 0;
  30076. rmat.m[13] = 0;
  30077. rmat.m[14] = 0;
  30078. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  30079. this._rotateWithMatrix(rmat, space, mesh);
  30080. };
  30081. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  30082. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30083. var rotMat = BABYLON.Tmp.Matrix[0];
  30084. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  30085. var rotMatInv = BABYLON.Tmp.Matrix[1];
  30086. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30087. rotMatInv.multiplyToRef(rotMat, rotMat);
  30088. this._rotateWithMatrix(rotMat, space, mesh);
  30089. };
  30090. Bone.prototype.setRotation = function (rotation, space, mesh) {
  30091. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30092. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  30093. };
  30094. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  30095. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30096. var rotMatInv = BABYLON.Tmp.Matrix[0];
  30097. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30098. var rotMat = BABYLON.Tmp.Matrix[1];
  30099. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  30100. rotMatInv.multiplyToRef(rotMat, rotMat);
  30101. this._rotateWithMatrix(rotMat, space, mesh);
  30102. };
  30103. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  30104. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30105. var rotMatInv = BABYLON.Tmp.Matrix[0];
  30106. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30107. var rotMat2 = BABYLON.Tmp.Matrix[1];
  30108. rotMat2.copyFrom(rotMat);
  30109. rotMatInv.multiplyToRef(rotMat, rotMat2);
  30110. this._rotateWithMatrix(rotMat2, space, mesh);
  30111. };
  30112. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  30113. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30114. var lmat = this.getLocalMatrix();
  30115. var lx = lmat.m[12];
  30116. var ly = lmat.m[13];
  30117. var lz = lmat.m[14];
  30118. var parent = this.getParent();
  30119. var parentScale = BABYLON.Tmp.Matrix[3];
  30120. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  30121. if (parent) {
  30122. if (space == BABYLON.Space.WORLD) {
  30123. if (mesh) {
  30124. parentScale.copyFrom(mesh.getWorldMatrix());
  30125. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  30126. }
  30127. else {
  30128. parentScale.copyFrom(parent.getAbsoluteTransform());
  30129. }
  30130. }
  30131. else {
  30132. parentScale = parent._scaleMatrix;
  30133. }
  30134. parentScaleInv.copyFrom(parentScale);
  30135. parentScaleInv.invert();
  30136. lmat.multiplyToRef(parentScale, lmat);
  30137. lmat.multiplyToRef(rmat, lmat);
  30138. lmat.multiplyToRef(parentScaleInv, lmat);
  30139. }
  30140. else {
  30141. if (space == BABYLON.Space.WORLD && mesh) {
  30142. parentScale.copyFrom(mesh.getWorldMatrix());
  30143. parentScaleInv.copyFrom(parentScale);
  30144. parentScaleInv.invert();
  30145. lmat.multiplyToRef(parentScale, lmat);
  30146. lmat.multiplyToRef(rmat, lmat);
  30147. lmat.multiplyToRef(parentScaleInv, lmat);
  30148. }
  30149. else {
  30150. lmat.multiplyToRef(rmat, lmat);
  30151. }
  30152. }
  30153. lmat.m[12] = lx;
  30154. lmat.m[13] = ly;
  30155. lmat.m[14] = lz;
  30156. this.computeAbsoluteTransforms();
  30157. this.markAsDirty();
  30158. };
  30159. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  30160. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30161. if (space == BABYLON.Space.WORLD) {
  30162. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  30163. scaleMatrix.copyFrom(this._scaleMatrix);
  30164. rotMatInv.copyFrom(this.getAbsoluteTransform());
  30165. if (mesh) {
  30166. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  30167. var meshScale = BABYLON.Tmp.Matrix[3];
  30168. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  30169. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  30170. }
  30171. rotMatInv.invert();
  30172. scaleMatrix.m[0] *= this._scalingDeterminant;
  30173. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  30174. }
  30175. else {
  30176. rotMatInv.copyFrom(this.getLocalMatrix());
  30177. rotMatInv.invert();
  30178. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  30179. scaleMatrix.copyFrom(this._scaleMatrix);
  30180. if (this._parent) {
  30181. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  30182. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  30183. pscaleMatrix.invert();
  30184. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  30185. }
  30186. else {
  30187. scaleMatrix.m[0] *= this._scalingDeterminant;
  30188. }
  30189. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  30190. }
  30191. };
  30192. Bone.prototype.getScale = function () {
  30193. return this._scaleVector.clone();
  30194. };
  30195. Bone.prototype.getScaleToRef = function (result) {
  30196. result.copyFrom(this._scaleVector);
  30197. };
  30198. Bone.prototype.getPosition = function (space, mesh) {
  30199. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30200. var pos = BABYLON.Vector3.Zero();
  30201. this.getPositionToRef(space, mesh, pos);
  30202. return pos;
  30203. };
  30204. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  30205. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30206. if (space == BABYLON.Space.LOCAL) {
  30207. var lm = this.getLocalMatrix();
  30208. result.x = lm.m[12];
  30209. result.y = lm.m[13];
  30210. result.z = lm.m[14];
  30211. }
  30212. else {
  30213. this._skeleton.computeAbsoluteTransforms();
  30214. var tmat = BABYLON.Tmp.Matrix[0];
  30215. if (mesh) {
  30216. tmat.copyFrom(this.getAbsoluteTransform());
  30217. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30218. }
  30219. else {
  30220. tmat = this.getAbsoluteTransform();
  30221. }
  30222. result.x = tmat.m[12];
  30223. result.y = tmat.m[13];
  30224. result.z = tmat.m[14];
  30225. }
  30226. };
  30227. Bone.prototype.getAbsolutePosition = function (mesh) {
  30228. var pos = BABYLON.Vector3.Zero();
  30229. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  30230. return pos;
  30231. };
  30232. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  30233. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  30234. };
  30235. Bone.prototype.computeAbsoluteTransforms = function () {
  30236. if (this._parent) {
  30237. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  30238. }
  30239. else {
  30240. this._absoluteTransform.copyFrom(this._matrix);
  30241. var poseMatrix = this._skeleton.getPoseMatrix();
  30242. if (poseMatrix) {
  30243. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  30244. }
  30245. }
  30246. var children = this.children;
  30247. var len = children.length;
  30248. for (var i = 0; i < len; i++) {
  30249. children[i].computeAbsoluteTransforms();
  30250. }
  30251. };
  30252. Bone.prototype.getDirection = function (localAxis, mesh) {
  30253. var result = BABYLON.Vector3.Zero();
  30254. this.getDirectionToRef(localAxis, mesh, result);
  30255. return result;
  30256. };
  30257. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  30258. this._skeleton.computeAbsoluteTransforms();
  30259. var mat = BABYLON.Tmp.Matrix[0];
  30260. mat.copyFrom(this.getAbsoluteTransform());
  30261. if (mesh) {
  30262. mat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30263. }
  30264. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  30265. result.normalize();
  30266. };
  30267. Bone.prototype.getRotation = function (space, mesh) {
  30268. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30269. var result = BABYLON.Vector3.Zero();
  30270. this.getRotationToRef(space, mesh, result);
  30271. return result;
  30272. };
  30273. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  30274. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30275. var quat = BABYLON.Tmp.Quaternion[0];
  30276. this.getRotationQuaternionToRef(space, mesh, quat);
  30277. quat.toEulerAnglesToRef(result);
  30278. };
  30279. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  30280. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30281. var result = BABYLON.Quaternion.Identity();
  30282. this.getRotationQuaternionToRef(space, mesh, result);
  30283. return result;
  30284. };
  30285. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  30286. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30287. if (space == BABYLON.Space.LOCAL) {
  30288. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  30289. }
  30290. else {
  30291. var mat = BABYLON.Tmp.Matrix[0];
  30292. var amat = this.getAbsoluteTransform();
  30293. if (mesh) {
  30294. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30295. }
  30296. else {
  30297. mat.copyFrom(amat);
  30298. }
  30299. mat.m[0] *= this._scalingDeterminant;
  30300. mat.m[1] *= this._scalingDeterminant;
  30301. mat.m[2] *= this._scalingDeterminant;
  30302. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  30303. }
  30304. };
  30305. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  30306. var result = BABYLON.Vector3.Zero();
  30307. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  30308. return result;
  30309. };
  30310. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  30311. this._skeleton.computeAbsoluteTransforms();
  30312. var tmat = BABYLON.Tmp.Matrix[0];
  30313. if (mesh) {
  30314. tmat.copyFrom(this.getAbsoluteTransform());
  30315. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30316. }
  30317. else {
  30318. tmat = this.getAbsoluteTransform();
  30319. }
  30320. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  30321. };
  30322. return Bone;
  30323. }(BABYLON.Node));
  30324. BABYLON.Bone = Bone;
  30325. })(BABYLON || (BABYLON = {}));
  30326. //# sourceMappingURL=../Bones/babylon.bone.js.map
  30327. var BABYLON;
  30328. (function (BABYLON) {
  30329. var BoneIKController = (function () {
  30330. function BoneIKController(mesh, bone, options) {
  30331. this.targetPosition = BABYLON.Vector3.Zero();
  30332. this.poleTargetPosition = BABYLON.Vector3.Zero();
  30333. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  30334. this.poleAngle = 0;
  30335. this._maxAngle = Math.PI;
  30336. this._tmpVec1 = BABYLON.Vector3.Zero();
  30337. this._tmpVec2 = BABYLON.Vector3.Zero();
  30338. this._tmpVec3 = BABYLON.Vector3.Zero();
  30339. this._tmpVec4 = BABYLON.Vector3.Zero();
  30340. this._tmpVec5 = BABYLON.Vector3.Zero();
  30341. this._tmpMat1 = BABYLON.Matrix.Identity();
  30342. this._tmpMat2 = BABYLON.Matrix.Identity();
  30343. this._rightHandedSystem = false;
  30344. this._bendAxis = BABYLON.Vector3.Right();
  30345. this._bone2 = bone;
  30346. this._bone1 = bone.getParent();
  30347. this.mesh = mesh;
  30348. if (bone.getAbsoluteTransform().determinant() > 0) {
  30349. this._rightHandedSystem = true;
  30350. this._bendAxis.x = 0;
  30351. this._bendAxis.y = 0;
  30352. this._bendAxis.z = 1;
  30353. }
  30354. if (this._bone1.length) {
  30355. var boneScale1 = this._bone1.getScale();
  30356. var boneScale2 = this._bone2.getScale();
  30357. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  30358. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  30359. }
  30360. else if (this._bone1.children[0]) {
  30361. mesh.computeWorldMatrix(true);
  30362. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  30363. var pos2 = this._bone2.getAbsolutePosition(mesh);
  30364. var pos3 = this._bone1.getAbsolutePosition(mesh);
  30365. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  30366. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  30367. }
  30368. this.maxAngle = Math.PI;
  30369. if (options) {
  30370. if (options.targetMesh) {
  30371. this.targetMesh = options.targetMesh;
  30372. this.targetMesh.computeWorldMatrix(true);
  30373. }
  30374. if (options.poleTargetMesh) {
  30375. this.poleTargetMesh = options.poleTargetMesh;
  30376. this.poleTargetMesh.computeWorldMatrix(true);
  30377. }
  30378. else if (options.poleTargetBone) {
  30379. this.poleTargetBone = options.poleTargetBone;
  30380. }
  30381. else if (this._bone1.getParent()) {
  30382. this.poleTargetBone = this._bone1.getParent();
  30383. }
  30384. if (options.poleTargetLocalOffset) {
  30385. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  30386. }
  30387. if (options.poleAngle) {
  30388. this.poleAngle = options.poleAngle;
  30389. }
  30390. if (options.bendAxis) {
  30391. this._bendAxis.copyFrom(options.bendAxis);
  30392. }
  30393. if (options.maxAngle) {
  30394. this.maxAngle = options.maxAngle;
  30395. }
  30396. }
  30397. }
  30398. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  30399. get: function () {
  30400. return this._maxAngle;
  30401. },
  30402. set: function (value) {
  30403. this._setMaxAngle(value);
  30404. },
  30405. enumerable: true,
  30406. configurable: true
  30407. });
  30408. BoneIKController.prototype._setMaxAngle = function (ang) {
  30409. if (ang < 0) {
  30410. ang = 0;
  30411. }
  30412. if (ang > Math.PI || ang == undefined) {
  30413. ang = Math.PI;
  30414. }
  30415. this._maxAngle = ang;
  30416. var a = this._bone1Length;
  30417. var b = this._bone2Length;
  30418. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  30419. };
  30420. BoneIKController.prototype.update = function () {
  30421. var bone1 = this._bone1;
  30422. var target = this.targetPosition;
  30423. var poleTarget = this.poleTargetPosition;
  30424. var mat1 = this._tmpMat1;
  30425. var mat2 = this._tmpMat2;
  30426. if (this.targetMesh) {
  30427. target.copyFrom(this.targetMesh.getAbsolutePosition());
  30428. }
  30429. if (this.poleTargetBone) {
  30430. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  30431. }
  30432. else if (this.poleTargetMesh) {
  30433. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  30434. }
  30435. var bonePos = this._tmpVec1;
  30436. var zaxis = this._tmpVec2;
  30437. var xaxis = this._tmpVec3;
  30438. var yaxis = this._tmpVec4;
  30439. var upAxis = this._tmpVec5;
  30440. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  30441. poleTarget.subtractToRef(bonePos, upAxis);
  30442. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  30443. upAxis.y = 1;
  30444. }
  30445. else {
  30446. upAxis.normalize();
  30447. }
  30448. target.subtractToRef(bonePos, yaxis);
  30449. yaxis.normalize();
  30450. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  30451. zaxis.normalize();
  30452. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  30453. xaxis.normalize();
  30454. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  30455. var a = this._bone1Length;
  30456. var b = this._bone2Length;
  30457. var c = BABYLON.Vector3.Distance(bonePos, target);
  30458. if (this._maxReach > 0) {
  30459. c = Math.min(this._maxReach, c);
  30460. }
  30461. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  30462. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  30463. if (acosa > 1) {
  30464. acosa = 1;
  30465. }
  30466. if (acosb > 1) {
  30467. acosb = 1;
  30468. }
  30469. if (acosa < -1) {
  30470. acosa = -1;
  30471. }
  30472. if (acosb < -1) {
  30473. acosb = -1;
  30474. }
  30475. var angA = Math.acos(acosa);
  30476. var angB = Math.acos(acosb);
  30477. var angC = -angA - angB;
  30478. if (this._rightHandedSystem) {
  30479. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, Math.PI * .5, mat2);
  30480. mat2.multiplyToRef(mat1, mat1);
  30481. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  30482. mat2.multiplyToRef(mat1, mat1);
  30483. }
  30484. else {
  30485. this._tmpVec1.copyFrom(this._bendAxis);
  30486. this._tmpVec1.x *= -1;
  30487. BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
  30488. mat2.multiplyToRef(mat1, mat1);
  30489. }
  30490. if (this.poleAngle) {
  30491. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  30492. mat1.multiplyToRef(mat2, mat1);
  30493. }
  30494. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  30495. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  30496. };
  30497. return BoneIKController;
  30498. }());
  30499. BABYLON.BoneIKController = BoneIKController;
  30500. })(BABYLON || (BABYLON = {}));
  30501. //# sourceMappingURL=../Bones/babylon.boneIKController.js.map
  30502. var BABYLON;
  30503. (function (BABYLON) {
  30504. var BoneLookController = (function () {
  30505. function BoneLookController(mesh, bone, target, options) {
  30506. this.upAxis = BABYLON.Vector3.Up();
  30507. this.adjustYaw = 0;
  30508. this.adjustPitch = 0;
  30509. this.adjustRoll = 0;
  30510. this._tmpVec1 = BABYLON.Vector3.Zero();
  30511. this._tmpVec2 = BABYLON.Vector3.Zero();
  30512. this._tmpVec3 = BABYLON.Vector3.Zero();
  30513. this._tmpVec4 = BABYLON.Vector3.Zero();
  30514. this._tmpMat1 = BABYLON.Matrix.Identity();
  30515. this._tmpMat2 = BABYLON.Matrix.Identity();
  30516. this.mesh = mesh;
  30517. this.bone = bone;
  30518. this.target = target;
  30519. if (options) {
  30520. if (options.adjustYaw) {
  30521. this.adjustYaw = options.adjustYaw;
  30522. }
  30523. if (options.adjustPitch) {
  30524. this.adjustPitch = options.adjustPitch;
  30525. }
  30526. if (options.adjustRoll) {
  30527. this.adjustRoll = options.adjustRoll;
  30528. }
  30529. }
  30530. }
  30531. BoneLookController.prototype.update = function () {
  30532. var bone = this.bone;
  30533. var target = this.target;
  30534. var bonePos = this._tmpVec1;
  30535. var zaxis = this._tmpVec2;
  30536. var xaxis = this._tmpVec3;
  30537. var yaxis = this._tmpVec4;
  30538. var mat1 = this._tmpMat1;
  30539. var mat2 = this._tmpMat2;
  30540. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  30541. target.subtractToRef(bonePos, zaxis);
  30542. zaxis.normalize();
  30543. BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
  30544. xaxis.normalize();
  30545. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  30546. yaxis.normalize();
  30547. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  30548. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  30549. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
  30550. mat2.multiplyToRef(mat1, mat1);
  30551. }
  30552. this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  30553. };
  30554. return BoneLookController;
  30555. }());
  30556. BABYLON.BoneLookController = BoneLookController;
  30557. })(BABYLON || (BABYLON = {}));
  30558. //# sourceMappingURL=../Bones/babylon.boneLookController.js.map
  30559. var BABYLON;
  30560. (function (BABYLON) {
  30561. var Skeleton = (function () {
  30562. function Skeleton(name, id, scene) {
  30563. this.name = name;
  30564. this.id = id;
  30565. this.bones = new Array();
  30566. this.needInitialSkinMatrix = false;
  30567. this._isDirty = true;
  30568. this._meshesWithPoseMatrix = new Array();
  30569. this._identity = BABYLON.Matrix.Identity();
  30570. this._ranges = {};
  30571. this._lastAbsoluteTransformsUpdateId = -1;
  30572. this.bones = [];
  30573. this._scene = scene;
  30574. scene.skeletons.push(this);
  30575. //make sure it will recalculate the matrix next time prepare is called.
  30576. this._isDirty = true;
  30577. }
  30578. // Members
  30579. Skeleton.prototype.getTransformMatrices = function (mesh) {
  30580. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  30581. return mesh._bonesTransformMatrices;
  30582. }
  30583. return this._transformMatrices;
  30584. };
  30585. Skeleton.prototype.getScene = function () {
  30586. return this._scene;
  30587. };
  30588. // Methods
  30589. /**
  30590. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30591. */
  30592. Skeleton.prototype.toString = function (fullDetails) {
  30593. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  30594. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  30595. if (fullDetails) {
  30596. ret += ", Ranges: {";
  30597. var first = true;
  30598. for (var name_1 in this._ranges) {
  30599. if (first) {
  30600. ret += ", ";
  30601. first = false;
  30602. }
  30603. ret += name_1;
  30604. }
  30605. ret += "}";
  30606. }
  30607. return ret;
  30608. };
  30609. /**
  30610. * Get bone's index searching by name
  30611. * @param {string} name is bone's name to search for
  30612. * @return {number} Indice of the bone. Returns -1 if not found
  30613. */
  30614. Skeleton.prototype.getBoneIndexByName = function (name) {
  30615. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  30616. if (this.bones[boneIndex].name === name) {
  30617. return boneIndex;
  30618. }
  30619. }
  30620. return -1;
  30621. };
  30622. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  30623. // check name not already in use
  30624. if (!this._ranges[name]) {
  30625. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  30626. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  30627. if (this.bones[i].animations[0]) {
  30628. this.bones[i].animations[0].createRange(name, from, to);
  30629. }
  30630. }
  30631. }
  30632. };
  30633. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  30634. if (deleteFrames === void 0) { deleteFrames = true; }
  30635. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  30636. if (this.bones[i].animations[0]) {
  30637. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  30638. }
  30639. }
  30640. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  30641. };
  30642. Skeleton.prototype.getAnimationRange = function (name) {
  30643. return this._ranges[name];
  30644. };
  30645. /**
  30646. * Returns as an Array, all AnimationRanges defined on this skeleton
  30647. */
  30648. Skeleton.prototype.getAnimationRanges = function () {
  30649. var animationRanges = [];
  30650. var name;
  30651. var i = 0;
  30652. for (name in this._ranges) {
  30653. animationRanges[i] = this._ranges[name];
  30654. i++;
  30655. }
  30656. return animationRanges;
  30657. };
  30658. /**
  30659. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  30660. */
  30661. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  30662. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  30663. if (this._ranges[name] || !source.getAnimationRange(name)) {
  30664. return false;
  30665. }
  30666. var ret = true;
  30667. var frameOffset = this._getHighestAnimationFrame() + 1;
  30668. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  30669. var boneDict = {};
  30670. var sourceBones = source.bones;
  30671. var nBones;
  30672. var i;
  30673. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  30674. boneDict[sourceBones[i].name] = sourceBones[i];
  30675. }
  30676. if (this.bones.length !== sourceBones.length) {
  30677. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  30678. ret = false;
  30679. }
  30680. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  30681. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  30682. var boneName = this.bones[i].name;
  30683. var sourceBone = boneDict[boneName];
  30684. if (sourceBone) {
  30685. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  30686. }
  30687. else {
  30688. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  30689. ret = false;
  30690. }
  30691. }
  30692. // do not call createAnimationRange(), since it also is done to bones, which was already done
  30693. var range = source.getAnimationRange(name);
  30694. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  30695. return ret;
  30696. };
  30697. Skeleton.prototype.returnToRest = function () {
  30698. for (var index = 0; index < this.bones.length; index++) {
  30699. this.bones[index].returnToRest();
  30700. }
  30701. };
  30702. Skeleton.prototype._getHighestAnimationFrame = function () {
  30703. var ret = 0;
  30704. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  30705. if (this.bones[i].animations[0]) {
  30706. var highest = this.bones[i].animations[0].getHighestFrame();
  30707. if (ret < highest) {
  30708. ret = highest;
  30709. }
  30710. }
  30711. }
  30712. return ret;
  30713. };
  30714. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  30715. var range = this.getAnimationRange(name);
  30716. if (!range) {
  30717. return null;
  30718. }
  30719. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  30720. };
  30721. Skeleton.prototype._markAsDirty = function () {
  30722. this._isDirty = true;
  30723. };
  30724. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  30725. this._meshesWithPoseMatrix.push(mesh);
  30726. };
  30727. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  30728. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  30729. if (index > -1) {
  30730. this._meshesWithPoseMatrix.splice(index, 1);
  30731. }
  30732. };
  30733. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  30734. for (var index = 0; index < this.bones.length; index++) {
  30735. var bone = this.bones[index];
  30736. var parentBone = bone.getParent();
  30737. if (parentBone) {
  30738. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  30739. }
  30740. else {
  30741. if (initialSkinMatrix) {
  30742. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  30743. }
  30744. else {
  30745. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  30746. }
  30747. }
  30748. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  30749. }
  30750. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  30751. };
  30752. Skeleton.prototype.prepare = function () {
  30753. if (!this._isDirty) {
  30754. return;
  30755. }
  30756. if (this.needInitialSkinMatrix) {
  30757. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  30758. var mesh = this._meshesWithPoseMatrix[index];
  30759. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  30760. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  30761. }
  30762. var poseMatrix = mesh.getPoseMatrix();
  30763. // Prepare bones
  30764. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  30765. var bone = this.bones[boneIndex];
  30766. if (!bone.getParent()) {
  30767. var matrix = bone.getBaseMatrix();
  30768. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  30769. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  30770. }
  30771. }
  30772. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  30773. }
  30774. }
  30775. else {
  30776. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  30777. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  30778. }
  30779. this._computeTransformMatrices(this._transformMatrices, null);
  30780. }
  30781. this._isDirty = false;
  30782. this._scene._activeBones.addCount(this.bones.length, false);
  30783. };
  30784. Skeleton.prototype.getAnimatables = function () {
  30785. if (!this._animatables || this._animatables.length !== this.bones.length) {
  30786. this._animatables = [];
  30787. for (var index = 0; index < this.bones.length; index++) {
  30788. this._animatables.push(this.bones[index]);
  30789. }
  30790. }
  30791. return this._animatables;
  30792. };
  30793. Skeleton.prototype.clone = function (name, id) {
  30794. var result = new Skeleton(name, id || name, this._scene);
  30795. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  30796. for (var index = 0; index < this.bones.length; index++) {
  30797. var source = this.bones[index];
  30798. var parentBone = null;
  30799. if (source.getParent()) {
  30800. var parentIndex = this.bones.indexOf(source.getParent());
  30801. parentBone = result.bones[parentIndex];
  30802. }
  30803. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  30804. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  30805. }
  30806. if (this._ranges) {
  30807. result._ranges = {};
  30808. for (var rangeName in this._ranges) {
  30809. result._ranges[rangeName] = this._ranges[rangeName].clone();
  30810. }
  30811. }
  30812. this._isDirty = true;
  30813. return result;
  30814. };
  30815. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  30816. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  30817. this.bones.forEach(function (bone) {
  30818. bone.animations.forEach(function (animation) {
  30819. animation.enableBlending = true;
  30820. animation.blendingSpeed = blendingSpeed;
  30821. });
  30822. });
  30823. };
  30824. Skeleton.prototype.dispose = function () {
  30825. this._meshesWithPoseMatrix = [];
  30826. // Animations
  30827. this.getScene().stopAnimation(this);
  30828. // Remove from scene
  30829. this.getScene().removeSkeleton(this);
  30830. };
  30831. Skeleton.prototype.serialize = function () {
  30832. var serializationObject = {};
  30833. serializationObject.name = this.name;
  30834. serializationObject.id = this.id;
  30835. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  30836. serializationObject.bones = [];
  30837. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  30838. for (var index = 0; index < this.bones.length; index++) {
  30839. var bone = this.bones[index];
  30840. var serializedBone = {
  30841. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  30842. name: bone.name,
  30843. matrix: bone.getLocalMatrix().toArray(),
  30844. rest: bone.getRestPose().toArray()
  30845. };
  30846. serializationObject.bones.push(serializedBone);
  30847. if (bone.length) {
  30848. serializedBone.length = bone.length;
  30849. }
  30850. if (bone.animations && bone.animations.length > 0) {
  30851. serializedBone.animation = bone.animations[0].serialize();
  30852. }
  30853. serializationObject.ranges = [];
  30854. for (var name in this._ranges) {
  30855. var range = {};
  30856. range.name = name;
  30857. range.from = this._ranges[name].from;
  30858. range.to = this._ranges[name].to;
  30859. serializationObject.ranges.push(range);
  30860. }
  30861. }
  30862. return serializationObject;
  30863. };
  30864. Skeleton.Parse = function (parsedSkeleton, scene) {
  30865. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  30866. if (parsedSkeleton.dimensionsAtRest) {
  30867. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  30868. }
  30869. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  30870. var index;
  30871. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  30872. var parsedBone = parsedSkeleton.bones[index];
  30873. var parentBone = null;
  30874. if (parsedBone.parentBoneIndex > -1) {
  30875. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  30876. }
  30877. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  30878. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  30879. if (parsedBone.length) {
  30880. bone.length = parsedBone.length;
  30881. }
  30882. if (parsedBone.animation) {
  30883. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  30884. }
  30885. }
  30886. // placed after bones, so createAnimationRange can cascade down
  30887. if (parsedSkeleton.ranges) {
  30888. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  30889. var data = parsedSkeleton.ranges[index];
  30890. skeleton.createAnimationRange(data.name, data.from, data.to);
  30891. }
  30892. }
  30893. return skeleton;
  30894. };
  30895. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  30896. if (forceUpdate === void 0) { forceUpdate = false; }
  30897. var renderId = this._scene.getRenderId();
  30898. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  30899. this.bones[0].computeAbsoluteTransforms();
  30900. this._lastAbsoluteTransformsUpdateId = renderId;
  30901. }
  30902. };
  30903. Skeleton.prototype.getPoseMatrix = function () {
  30904. var poseMatrix;
  30905. if (this._meshesWithPoseMatrix.length > 0) {
  30906. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  30907. }
  30908. return poseMatrix;
  30909. };
  30910. return Skeleton;
  30911. }());
  30912. BABYLON.Skeleton = Skeleton;
  30913. })(BABYLON || (BABYLON = {}));
  30914. //# sourceMappingURL=../Bones/babylon.skeleton.js.map
  30915. var BABYLON;
  30916. (function (BABYLON) {
  30917. var PostProcess = (function () {
  30918. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  30919. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  30920. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  30921. this.name = name;
  30922. this.width = -1;
  30923. this.height = -1;
  30924. /*
  30925. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  30926. Can only be used on a single postprocess or on the last one of a chain.
  30927. */
  30928. this.enablePixelPerfectMode = false;
  30929. this._reusable = false;
  30930. this._textures = new BABYLON.SmartArray(2);
  30931. this._currentRenderTextureInd = 0;
  30932. this._scaleRatio = new BABYLON.Vector2(1, 1);
  30933. // Events
  30934. /**
  30935. * An event triggered when the postprocess is activated.
  30936. * @type {BABYLON.Observable}
  30937. */
  30938. this.onActivateObservable = new BABYLON.Observable();
  30939. /**
  30940. * An event triggered when the postprocess changes its size.
  30941. * @type {BABYLON.Observable}
  30942. */
  30943. this.onSizeChangedObservable = new BABYLON.Observable();
  30944. /**
  30945. * An event triggered when the postprocess applies its effect.
  30946. * @type {BABYLON.Observable}
  30947. */
  30948. this.onApplyObservable = new BABYLON.Observable();
  30949. /**
  30950. * An event triggered before rendering the postprocess
  30951. * @type {BABYLON.Observable}
  30952. */
  30953. this.onBeforeRenderObservable = new BABYLON.Observable();
  30954. /**
  30955. * An event triggered after rendering the postprocess
  30956. * @type {BABYLON.Observable}
  30957. */
  30958. this.onAfterRenderObservable = new BABYLON.Observable();
  30959. if (camera != null) {
  30960. this._camera = camera;
  30961. this._scene = camera.getScene();
  30962. camera.attachPostProcess(this);
  30963. this._engine = this._scene.getEngine();
  30964. }
  30965. else {
  30966. this._engine = engine;
  30967. }
  30968. this._options = options;
  30969. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  30970. this._reusable = reusable || false;
  30971. this._textureType = textureType;
  30972. this._samplers = samplers || [];
  30973. this._samplers.push("textureSampler");
  30974. this._fragmentUrl = fragmentUrl;
  30975. this._parameters = parameters || [];
  30976. this._parameters.push("scale");
  30977. this.updateEffect(defines);
  30978. }
  30979. Object.defineProperty(PostProcess.prototype, "onActivate", {
  30980. set: function (callback) {
  30981. if (this._onActivateObserver) {
  30982. this.onActivateObservable.remove(this._onActivateObserver);
  30983. }
  30984. this._onActivateObserver = this.onActivateObservable.add(callback);
  30985. },
  30986. enumerable: true,
  30987. configurable: true
  30988. });
  30989. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  30990. set: function (callback) {
  30991. if (this._onSizeChangedObserver) {
  30992. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  30993. }
  30994. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  30995. },
  30996. enumerable: true,
  30997. configurable: true
  30998. });
  30999. Object.defineProperty(PostProcess.prototype, "onApply", {
  31000. set: function (callback) {
  31001. if (this._onApplyObserver) {
  31002. this.onApplyObservable.remove(this._onApplyObserver);
  31003. }
  31004. this._onApplyObserver = this.onApplyObservable.add(callback);
  31005. },
  31006. enumerable: true,
  31007. configurable: true
  31008. });
  31009. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  31010. set: function (callback) {
  31011. if (this._onBeforeRenderObserver) {
  31012. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  31013. }
  31014. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  31015. },
  31016. enumerable: true,
  31017. configurable: true
  31018. });
  31019. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  31020. set: function (callback) {
  31021. if (this._onAfterRenderObserver) {
  31022. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  31023. }
  31024. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31025. },
  31026. enumerable: true,
  31027. configurable: true
  31028. });
  31029. PostProcess.prototype.updateEffect = function (defines) {
  31030. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  31031. };
  31032. PostProcess.prototype.isReusable = function () {
  31033. return this._reusable;
  31034. };
  31035. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  31036. PostProcess.prototype.markTextureDirty = function () {
  31037. this.width = -1;
  31038. };
  31039. PostProcess.prototype.activate = function (camera, sourceTexture) {
  31040. camera = camera || this._camera;
  31041. var scene = camera.getScene();
  31042. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  31043. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  31044. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  31045. var desiredWidth = this._options.width || requiredWidth;
  31046. var desiredHeight = this._options.height || requiredHeight;
  31047. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  31048. if (!this._options.width) {
  31049. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  31050. }
  31051. if (!this._options.height) {
  31052. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  31053. }
  31054. }
  31055. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  31056. if (this._textures.length > 0) {
  31057. for (var i = 0; i < this._textures.length; i++) {
  31058. this._engine._releaseTexture(this._textures.data[i]);
  31059. }
  31060. this._textures.reset();
  31061. }
  31062. this.width = desiredWidth;
  31063. this.height = desiredHeight;
  31064. var textureSize = { width: this.width, height: this.height };
  31065. var textureOptions = {
  31066. generateMipMaps: false,
  31067. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  31068. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  31069. samplingMode: this.renderTargetSamplingMode,
  31070. type: this._textureType
  31071. };
  31072. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  31073. if (this._reusable) {
  31074. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  31075. }
  31076. this.onSizeChangedObservable.notifyObservers(this);
  31077. }
  31078. if (this.enablePixelPerfectMode) {
  31079. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  31080. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  31081. }
  31082. else {
  31083. this._scaleRatio.copyFromFloats(1, 1);
  31084. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  31085. }
  31086. this.onActivateObservable.notifyObservers(camera);
  31087. // Clear
  31088. if (this.clearColor) {
  31089. this._engine.clear(this.clearColor, true, true, true);
  31090. }
  31091. else {
  31092. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  31093. }
  31094. if (this._reusable) {
  31095. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  31096. }
  31097. };
  31098. Object.defineProperty(PostProcess.prototype, "isSupported", {
  31099. get: function () {
  31100. return this._effect.isSupported;
  31101. },
  31102. enumerable: true,
  31103. configurable: true
  31104. });
  31105. PostProcess.prototype.apply = function () {
  31106. // Check
  31107. if (!this._effect.isReady())
  31108. return null;
  31109. // States
  31110. this._engine.enableEffect(this._effect);
  31111. this._engine.setState(false);
  31112. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31113. this._engine.setDepthBuffer(false);
  31114. this._engine.setDepthWrite(false);
  31115. // Texture
  31116. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  31117. // Parameters
  31118. this._effect.setVector2("scale", this._scaleRatio);
  31119. this.onApplyObservable.notifyObservers(this._effect);
  31120. return this._effect;
  31121. };
  31122. PostProcess.prototype.dispose = function (camera) {
  31123. camera = camera || this._camera;
  31124. if (this._textures.length > 0) {
  31125. for (var i = 0; i < this._textures.length; i++) {
  31126. this._engine._releaseTexture(this._textures.data[i]);
  31127. }
  31128. this._textures.reset();
  31129. }
  31130. if (!camera) {
  31131. return;
  31132. }
  31133. camera.detachPostProcess(this);
  31134. var index = camera._postProcesses.indexOf(this);
  31135. if (index === 0 && camera._postProcesses.length > 0) {
  31136. this._camera._postProcesses[0].markTextureDirty();
  31137. }
  31138. this.onActivateObservable.clear();
  31139. this.onAfterRenderObservable.clear();
  31140. this.onApplyObservable.clear();
  31141. this.onBeforeRenderObservable.clear();
  31142. this.onSizeChangedObservable.clear();
  31143. };
  31144. return PostProcess;
  31145. }());
  31146. BABYLON.PostProcess = PostProcess;
  31147. })(BABYLON || (BABYLON = {}));
  31148. //# sourceMappingURL=../PostProcess/babylon.postProcess.js.map
  31149. var BABYLON;
  31150. (function (BABYLON) {
  31151. var PostProcessManager = (function () {
  31152. function PostProcessManager(scene) {
  31153. this._vertexBuffers = {};
  31154. this._scene = scene;
  31155. }
  31156. PostProcessManager.prototype._prepareBuffers = function () {
  31157. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31158. return;
  31159. }
  31160. // VBO
  31161. var vertices = [];
  31162. vertices.push(1, 1);
  31163. vertices.push(-1, 1);
  31164. vertices.push(-1, -1);
  31165. vertices.push(1, -1);
  31166. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31167. // Indices
  31168. var indices = [];
  31169. indices.push(0);
  31170. indices.push(1);
  31171. indices.push(2);
  31172. indices.push(0);
  31173. indices.push(2);
  31174. indices.push(3);
  31175. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31176. };
  31177. // Methods
  31178. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  31179. var postProcesses = this._scene.activeCamera._postProcesses;
  31180. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31181. return false;
  31182. }
  31183. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  31184. return true;
  31185. };
  31186. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  31187. var engine = this._scene.getEngine();
  31188. for (var index = 0; index < postProcesses.length; index++) {
  31189. if (index < postProcesses.length - 1) {
  31190. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31191. }
  31192. else {
  31193. if (targetTexture) {
  31194. engine.bindFramebuffer(targetTexture);
  31195. }
  31196. else {
  31197. engine.restoreDefaultFramebuffer();
  31198. }
  31199. }
  31200. var pp = postProcesses[index];
  31201. var effect = pp.apply();
  31202. if (effect) {
  31203. pp.onBeforeRenderObservable.notifyObservers(effect);
  31204. // VBOs
  31205. this._prepareBuffers();
  31206. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31207. // Draw order
  31208. engine.draw(true, 0, 6);
  31209. pp.onAfterRenderObservable.notifyObservers(effect);
  31210. }
  31211. }
  31212. // Restore depth buffer
  31213. engine.setDepthBuffer(true);
  31214. engine.setDepthWrite(true);
  31215. };
  31216. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  31217. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  31218. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31219. return;
  31220. }
  31221. var engine = this._scene.getEngine();
  31222. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31223. if (index < len - 1) {
  31224. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31225. }
  31226. else {
  31227. if (targetTexture) {
  31228. engine.bindFramebuffer(targetTexture, faceIndex);
  31229. }
  31230. else {
  31231. engine.restoreDefaultFramebuffer();
  31232. }
  31233. }
  31234. if (doNotPresent) {
  31235. break;
  31236. }
  31237. var pp = postProcesses[index];
  31238. var effect = pp.apply();
  31239. if (effect) {
  31240. pp.onBeforeRenderObservable.notifyObservers(effect);
  31241. // VBOs
  31242. this._prepareBuffers();
  31243. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31244. // Draw order
  31245. engine.draw(true, 0, 6);
  31246. pp.onAfterRenderObservable.notifyObservers(effect);
  31247. }
  31248. }
  31249. // Restore depth buffer
  31250. engine.setDepthBuffer(true);
  31251. engine.setDepthWrite(true);
  31252. };
  31253. PostProcessManager.prototype.dispose = function () {
  31254. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31255. if (buffer) {
  31256. buffer.dispose();
  31257. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31258. }
  31259. if (this._indexBuffer) {
  31260. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31261. this._indexBuffer = null;
  31262. }
  31263. };
  31264. return PostProcessManager;
  31265. }());
  31266. BABYLON.PostProcessManager = PostProcessManager;
  31267. })(BABYLON || (BABYLON = {}));
  31268. //# sourceMappingURL=../PostProcess/babylon.postProcessManager.js.map
  31269. var BABYLON;
  31270. (function (BABYLON) {
  31271. var PassPostProcess = (function (_super) {
  31272. __extends(PassPostProcess, _super);
  31273. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  31274. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  31275. }
  31276. return PassPostProcess;
  31277. }(BABYLON.PostProcess));
  31278. BABYLON.PassPostProcess = PassPostProcess;
  31279. })(BABYLON || (BABYLON = {}));
  31280. //# sourceMappingURL=../PostProcess/babylon.passPostProcess.js.map
  31281. var BABYLON;
  31282. (function (BABYLON) {
  31283. /**
  31284. * This is a holder class for the physics joint created by the physics plugin.
  31285. * It holds a set of functions to control the underlying joint.
  31286. */
  31287. var PhysicsJoint = (function () {
  31288. function PhysicsJoint(type, jointData) {
  31289. this.type = type;
  31290. this.jointData = jointData;
  31291. jointData.nativeParams = jointData.nativeParams || {};
  31292. }
  31293. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  31294. get: function () {
  31295. return this._physicsJoint;
  31296. },
  31297. set: function (newJoint) {
  31298. if (this._physicsJoint) {
  31299. }
  31300. this._physicsJoint = newJoint;
  31301. },
  31302. enumerable: true,
  31303. configurable: true
  31304. });
  31305. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  31306. set: function (physicsPlugin) {
  31307. this._physicsPlugin = physicsPlugin;
  31308. },
  31309. enumerable: true,
  31310. configurable: true
  31311. });
  31312. /**
  31313. * Execute a function that is physics-plugin specific.
  31314. * @param {Function} func the function that will be executed.
  31315. * It accepts two parameters: the physics world and the physics joint.
  31316. */
  31317. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  31318. func(this._physicsPlugin.world, this._physicsJoint);
  31319. };
  31320. //TODO check if the native joints are the same
  31321. //Joint Types
  31322. PhysicsJoint.DistanceJoint = 0;
  31323. PhysicsJoint.HingeJoint = 1;
  31324. PhysicsJoint.BallAndSocketJoint = 2;
  31325. PhysicsJoint.WheelJoint = 3;
  31326. PhysicsJoint.SliderJoint = 4;
  31327. //OIMO
  31328. PhysicsJoint.PrismaticJoint = 5;
  31329. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  31330. PhysicsJoint.UniversalJoint = 6;
  31331. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  31332. //Cannon
  31333. //Similar to a Ball-Joint. Different in params
  31334. PhysicsJoint.PointToPointJoint = 8;
  31335. //Cannon only at the moment
  31336. PhysicsJoint.SpringJoint = 9;
  31337. PhysicsJoint.LockJoint = 10;
  31338. return PhysicsJoint;
  31339. }());
  31340. BABYLON.PhysicsJoint = PhysicsJoint;
  31341. /**
  31342. * A class representing a physics distance joint.
  31343. */
  31344. var DistanceJoint = (function (_super) {
  31345. __extends(DistanceJoint, _super);
  31346. function DistanceJoint(jointData) {
  31347. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  31348. }
  31349. /**
  31350. * Update the predefined distance.
  31351. */
  31352. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  31353. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  31354. };
  31355. return DistanceJoint;
  31356. }(PhysicsJoint));
  31357. BABYLON.DistanceJoint = DistanceJoint;
  31358. var MotorEnabledJoint = (function (_super) {
  31359. __extends(MotorEnabledJoint, _super);
  31360. function MotorEnabledJoint(type, jointData) {
  31361. _super.call(this, type, jointData);
  31362. }
  31363. /**
  31364. * Set the motor values.
  31365. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31366. * @param {number} force the force to apply
  31367. * @param {number} maxForce max force for this motor.
  31368. */
  31369. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  31370. this._physicsPlugin.setMotor(this, force, maxForce);
  31371. };
  31372. /**
  31373. * Set the motor's limits.
  31374. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31375. */
  31376. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  31377. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  31378. };
  31379. return MotorEnabledJoint;
  31380. }(PhysicsJoint));
  31381. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  31382. /**
  31383. * This class represents a single hinge physics joint
  31384. */
  31385. var HingeJoint = (function (_super) {
  31386. __extends(HingeJoint, _super);
  31387. function HingeJoint(jointData) {
  31388. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  31389. }
  31390. /**
  31391. * Set the motor values.
  31392. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31393. * @param {number} force the force to apply
  31394. * @param {number} maxForce max force for this motor.
  31395. */
  31396. HingeJoint.prototype.setMotor = function (force, maxForce) {
  31397. this._physicsPlugin.setMotor(this, force, maxForce);
  31398. };
  31399. /**
  31400. * Set the motor's limits.
  31401. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31402. */
  31403. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  31404. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  31405. };
  31406. return HingeJoint;
  31407. }(MotorEnabledJoint));
  31408. BABYLON.HingeJoint = HingeJoint;
  31409. /**
  31410. * This class represents a dual hinge physics joint (same as wheel joint)
  31411. */
  31412. var Hinge2Joint = (function (_super) {
  31413. __extends(Hinge2Joint, _super);
  31414. function Hinge2Joint(jointData) {
  31415. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  31416. }
  31417. /**
  31418. * Set the motor values.
  31419. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31420. * @param {number} force the force to apply
  31421. * @param {number} maxForce max force for this motor.
  31422. * @param {motorIndex} the motor's index, 0 or 1.
  31423. */
  31424. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  31425. if (motorIndex === void 0) { motorIndex = 0; }
  31426. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  31427. };
  31428. /**
  31429. * Set the motor limits.
  31430. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31431. * @param {number} upperLimit the upper limit
  31432. * @param {number} lowerLimit lower limit
  31433. * @param {motorIndex} the motor's index, 0 or 1.
  31434. */
  31435. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  31436. if (motorIndex === void 0) { motorIndex = 0; }
  31437. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  31438. };
  31439. return Hinge2Joint;
  31440. }(MotorEnabledJoint));
  31441. BABYLON.Hinge2Joint = Hinge2Joint;
  31442. })(BABYLON || (BABYLON = {}));
  31443. //# sourceMappingURL=../Physics/babylon.physicsJoint.js.map
  31444. var BABYLON;
  31445. (function (BABYLON) {
  31446. var PhysicsImpostor = (function () {
  31447. function PhysicsImpostor(object, type, _options, _scene) {
  31448. var _this = this;
  31449. if (_options === void 0) { _options = { mass: 0 }; }
  31450. this.object = object;
  31451. this.type = type;
  31452. this._options = _options;
  31453. this._scene = _scene;
  31454. this._bodyUpdateRequired = false;
  31455. this._onBeforePhysicsStepCallbacks = new Array();
  31456. this._onAfterPhysicsStepCallbacks = new Array();
  31457. this._onPhysicsCollideCallbacks = [];
  31458. this._deltaPosition = BABYLON.Vector3.Zero();
  31459. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  31460. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  31461. /**
  31462. * this function is executed by the physics engine.
  31463. */
  31464. this.beforeStep = function () {
  31465. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  31466. //conjugate deltaRotation
  31467. if (_this._deltaRotationConjugated) {
  31468. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  31469. }
  31470. else {
  31471. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  31472. }
  31473. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  31474. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  31475. func(_this);
  31476. });
  31477. };
  31478. /**
  31479. * this function is executed by the physics engine.
  31480. */
  31481. this.afterStep = function () {
  31482. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  31483. func(_this);
  31484. });
  31485. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  31486. _this.object.position.addInPlace(_this._deltaPosition);
  31487. if (_this._deltaRotation) {
  31488. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  31489. }
  31490. };
  31491. //event and body object due to cannon's event-based architecture.
  31492. this.onCollide = function (e) {
  31493. if (!_this._onPhysicsCollideCallbacks.length)
  31494. return;
  31495. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  31496. if (otherImpostor) {
  31497. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  31498. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  31499. }).forEach(function (obj) {
  31500. obj.callback(_this, otherImpostor);
  31501. });
  31502. }
  31503. };
  31504. //sanity check!
  31505. if (!this.object) {
  31506. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  31507. return;
  31508. }
  31509. //legacy support for old syntax.
  31510. if (!this._scene && object.getScene) {
  31511. this._scene = object.getScene();
  31512. }
  31513. this._physicsEngine = this._scene.getPhysicsEngine();
  31514. if (!this._physicsEngine) {
  31515. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  31516. }
  31517. else {
  31518. //set the object's quaternion, if not set
  31519. if (!this.object.rotationQuaternion) {
  31520. if (this.object.rotation) {
  31521. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  31522. }
  31523. else {
  31524. this.object.rotationQuaternion = new BABYLON.Quaternion();
  31525. }
  31526. }
  31527. //default options params
  31528. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  31529. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  31530. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  31531. this._joints = [];
  31532. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  31533. if (!this.object.parent) {
  31534. this._init();
  31535. }
  31536. }
  31537. }
  31538. /**
  31539. * This function will completly initialize this impostor.
  31540. * It will create a new body - but only if this mesh has no parent.
  31541. * If it has, this impostor will not be used other than to define the impostor
  31542. * of the child mesh.
  31543. */
  31544. PhysicsImpostor.prototype._init = function () {
  31545. this._physicsEngine.removeImpostor(this);
  31546. this.physicsBody = null;
  31547. this._parent = this._parent || this._getPhysicsParent();
  31548. if (!this.parent) {
  31549. this._physicsEngine.addImpostor(this);
  31550. }
  31551. };
  31552. PhysicsImpostor.prototype._getPhysicsParent = function () {
  31553. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  31554. var parentMesh = this.object.parent;
  31555. return parentMesh.physicsImpostor;
  31556. }
  31557. return;
  31558. };
  31559. /**
  31560. * Should a new body be generated.
  31561. */
  31562. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  31563. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  31564. };
  31565. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  31566. this.forceUpdate();
  31567. };
  31568. /**
  31569. * Force a regeneration of this or the parent's impostor's body.
  31570. * Use under cautious - This will remove all joints already implemented.
  31571. */
  31572. PhysicsImpostor.prototype.forceUpdate = function () {
  31573. this._init();
  31574. if (this.parent) {
  31575. this.parent.forceUpdate();
  31576. }
  31577. };
  31578. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  31579. /*public get mesh(): AbstractMesh {
  31580. return this._mesh;
  31581. }*/
  31582. /**
  31583. * Gets the body that holds this impostor. Either its own, or its parent.
  31584. */
  31585. get: function () {
  31586. return this._parent ? this._parent.physicsBody : this._physicsBody;
  31587. },
  31588. /**
  31589. * Set the physics body. Used mainly by the physics engine/plugin
  31590. */
  31591. set: function (physicsBody) {
  31592. if (this._physicsBody) {
  31593. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  31594. }
  31595. this._physicsBody = physicsBody;
  31596. this.resetUpdateFlags();
  31597. },
  31598. enumerable: true,
  31599. configurable: true
  31600. });
  31601. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  31602. get: function () {
  31603. return this._parent;
  31604. },
  31605. set: function (value) {
  31606. this._parent = value;
  31607. },
  31608. enumerable: true,
  31609. configurable: true
  31610. });
  31611. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  31612. this._bodyUpdateRequired = false;
  31613. };
  31614. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  31615. if (this.object.getBoundingInfo) {
  31616. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  31617. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  31618. }
  31619. else {
  31620. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  31621. }
  31622. };
  31623. PhysicsImpostor.prototype.getObjectCenter = function () {
  31624. if (this.object.getBoundingInfo) {
  31625. return this.object.getBoundingInfo().boundingBox.center;
  31626. }
  31627. else {
  31628. return this.object.position;
  31629. }
  31630. };
  31631. /**
  31632. * Get a specific parametes from the options parameter.
  31633. */
  31634. PhysicsImpostor.prototype.getParam = function (paramName) {
  31635. return this._options[paramName];
  31636. };
  31637. /**
  31638. * Sets a specific parameter in the options given to the physics plugin
  31639. */
  31640. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  31641. this._options[paramName] = value;
  31642. this._bodyUpdateRequired = true;
  31643. };
  31644. /**
  31645. * Specifically change the body's mass option. Won't recreate the physics body object
  31646. */
  31647. PhysicsImpostor.prototype.setMass = function (mass) {
  31648. if (this.getParam("mass") !== mass) {
  31649. this.setParam("mass", mass);
  31650. }
  31651. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  31652. };
  31653. PhysicsImpostor.prototype.getLinearVelocity = function () {
  31654. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  31655. };
  31656. /**
  31657. * Set the body's linear velocity.
  31658. */
  31659. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  31660. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  31661. };
  31662. PhysicsImpostor.prototype.getAngularVelocity = function () {
  31663. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  31664. };
  31665. /**
  31666. * Set the body's linear velocity.
  31667. */
  31668. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  31669. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  31670. };
  31671. /**
  31672. * Execute a function with the physics plugin native code.
  31673. * Provide a function the will have two variables - the world object and the physics body object.
  31674. */
  31675. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  31676. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  31677. };
  31678. /**
  31679. * Register a function that will be executed before the physics world is stepping forward.
  31680. */
  31681. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  31682. this._onBeforePhysicsStepCallbacks.push(func);
  31683. };
  31684. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  31685. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  31686. if (index > -1) {
  31687. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  31688. }
  31689. else {
  31690. BABYLON.Tools.Warn("Function to remove was not found");
  31691. }
  31692. };
  31693. /**
  31694. * Register a function that will be executed after the physics step
  31695. */
  31696. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  31697. this._onAfterPhysicsStepCallbacks.push(func);
  31698. };
  31699. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  31700. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  31701. if (index > -1) {
  31702. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  31703. }
  31704. else {
  31705. BABYLON.Tools.Warn("Function to remove was not found");
  31706. }
  31707. };
  31708. /**
  31709. * register a function that will be executed when this impostor collides against a different body.
  31710. */
  31711. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  31712. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  31713. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  31714. };
  31715. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  31716. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  31717. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  31718. if (index > -1) {
  31719. this._onPhysicsCollideCallbacks.splice(index, 1);
  31720. }
  31721. else {
  31722. BABYLON.Tools.Warn("Function to remove was not found");
  31723. }
  31724. };
  31725. /**
  31726. * Apply a force
  31727. */
  31728. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  31729. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  31730. };
  31731. /**
  31732. * Apply an impulse
  31733. */
  31734. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  31735. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  31736. };
  31737. /**
  31738. * A help function to create a joint.
  31739. */
  31740. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  31741. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  31742. this.addJoint(otherImpostor, joint);
  31743. };
  31744. /**
  31745. * Add a joint to this impostor with a different impostor.
  31746. */
  31747. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  31748. this._joints.push({
  31749. otherImpostor: otherImpostor,
  31750. joint: joint
  31751. });
  31752. this._physicsEngine.addJoint(this, otherImpostor, joint);
  31753. };
  31754. /**
  31755. * Will keep this body still, in a sleep mode.
  31756. */
  31757. PhysicsImpostor.prototype.sleep = function () {
  31758. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  31759. };
  31760. /**
  31761. * Wake the body up.
  31762. */
  31763. PhysicsImpostor.prototype.wakeUp = function () {
  31764. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  31765. };
  31766. PhysicsImpostor.prototype.clone = function (newObject) {
  31767. if (!newObject)
  31768. return null;
  31769. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  31770. };
  31771. PhysicsImpostor.prototype.dispose = function () {
  31772. var _this = this;
  31773. //no dispose if no physics engine is available.
  31774. if (!this._physicsEngine) {
  31775. return;
  31776. }
  31777. this._joints.forEach(function (j) {
  31778. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  31779. });
  31780. //dispose the physics body
  31781. this._physicsEngine.removeImpostor(this);
  31782. if (this.parent) {
  31783. this.parent.forceUpdate();
  31784. }
  31785. else {
  31786. }
  31787. };
  31788. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  31789. this._deltaPosition.copyFrom(position);
  31790. };
  31791. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  31792. if (!this._deltaRotation) {
  31793. this._deltaRotation = new BABYLON.Quaternion();
  31794. }
  31795. this._deltaRotation.copyFrom(rotation);
  31796. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  31797. };
  31798. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  31799. //Impostor types
  31800. PhysicsImpostor.NoImpostor = 0;
  31801. PhysicsImpostor.SphereImpostor = 1;
  31802. PhysicsImpostor.BoxImpostor = 2;
  31803. PhysicsImpostor.PlaneImpostor = 3;
  31804. PhysicsImpostor.MeshImpostor = 4;
  31805. PhysicsImpostor.CylinderImpostor = 7;
  31806. PhysicsImpostor.ParticleImpostor = 8;
  31807. PhysicsImpostor.HeightmapImpostor = 9;
  31808. return PhysicsImpostor;
  31809. }());
  31810. BABYLON.PhysicsImpostor = PhysicsImpostor;
  31811. })(BABYLON || (BABYLON = {}));
  31812. //# sourceMappingURL=../Physics/babylon.physicsImpostor.js.map
  31813. var BABYLON;
  31814. (function (BABYLON) {
  31815. var PhysicsEngine = (function () {
  31816. function PhysicsEngine(gravity, _physicsPlugin) {
  31817. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  31818. this._physicsPlugin = _physicsPlugin;
  31819. //new methods and parameters
  31820. this._impostors = [];
  31821. this._joints = [];
  31822. if (!this._physicsPlugin.isSupported()) {
  31823. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  31824. + "Please make sure it is included.");
  31825. }
  31826. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  31827. this.setGravity(gravity);
  31828. this.setTimeStep();
  31829. }
  31830. PhysicsEngine.prototype.setGravity = function (gravity) {
  31831. this.gravity = gravity;
  31832. this._physicsPlugin.setGravity(this.gravity);
  31833. };
  31834. /**
  31835. * Set the time step of the physics engine.
  31836. * default is 1/60.
  31837. * To slow it down, enter 1/600 for example.
  31838. * To speed it up, 1/30
  31839. * @param {number} newTimeStep the new timestep to apply to this world.
  31840. */
  31841. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  31842. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  31843. this._physicsPlugin.setTimeStep(newTimeStep);
  31844. };
  31845. PhysicsEngine.prototype.dispose = function () {
  31846. this._impostors.forEach(function (impostor) {
  31847. impostor.dispose();
  31848. });
  31849. this._physicsPlugin.dispose();
  31850. };
  31851. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  31852. return this._physicsPlugin.name;
  31853. };
  31854. /**
  31855. * Adding a new impostor for the impostor tracking.
  31856. * This will be done by the impostor itself.
  31857. * @param {PhysicsImpostor} impostor the impostor to add
  31858. */
  31859. PhysicsEngine.prototype.addImpostor = function (impostor) {
  31860. impostor.uniqueId = this._impostors.push(impostor);
  31861. //if no parent, generate the body
  31862. if (!impostor.parent) {
  31863. this._physicsPlugin.generatePhysicsBody(impostor);
  31864. }
  31865. };
  31866. /**
  31867. * Remove an impostor from the engine.
  31868. * This impostor and its mesh will not longer be updated by the physics engine.
  31869. * @param {PhysicsImpostor} impostor the impostor to remove
  31870. */
  31871. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  31872. var index = this._impostors.indexOf(impostor);
  31873. if (index > -1) {
  31874. var removed = this._impostors.splice(index, 1);
  31875. //Is it needed?
  31876. if (removed.length) {
  31877. //this will also remove it from the world.
  31878. removed[0].physicsBody = null;
  31879. }
  31880. }
  31881. };
  31882. /**
  31883. * Add a joint to the physics engine
  31884. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  31885. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  31886. * @param {PhysicsJoint} the joint that will connect both impostors.
  31887. */
  31888. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  31889. var impostorJoint = {
  31890. mainImpostor: mainImpostor,
  31891. connectedImpostor: connectedImpostor,
  31892. joint: joint
  31893. };
  31894. joint.physicsPlugin = this._physicsPlugin;
  31895. this._joints.push(impostorJoint);
  31896. this._physicsPlugin.generateJoint(impostorJoint);
  31897. };
  31898. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  31899. var matchingJoints = this._joints.filter(function (impostorJoint) {
  31900. return (impostorJoint.connectedImpostor === connectedImpostor
  31901. && impostorJoint.joint === joint
  31902. && impostorJoint.mainImpostor === mainImpostor);
  31903. });
  31904. if (matchingJoints.length) {
  31905. this._physicsPlugin.removeJoint(matchingJoints[0]);
  31906. }
  31907. };
  31908. /**
  31909. * Called by the scene. no need to call it.
  31910. */
  31911. PhysicsEngine.prototype._step = function (delta) {
  31912. var _this = this;
  31913. //check if any mesh has no body / requires an update
  31914. this._impostors.forEach(function (impostor) {
  31915. if (impostor.isBodyInitRequired()) {
  31916. _this._physicsPlugin.generatePhysicsBody(impostor);
  31917. }
  31918. });
  31919. if (delta > 0.1) {
  31920. delta = 0.1;
  31921. }
  31922. else if (delta <= 0) {
  31923. delta = 1.0 / 60.0;
  31924. }
  31925. this._physicsPlugin.executeStep(delta, this._impostors);
  31926. };
  31927. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  31928. return this._physicsPlugin;
  31929. };
  31930. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  31931. for (var i = 0; i < this._impostors.length; ++i) {
  31932. if (this._impostors[i].object === object) {
  31933. return this._impostors[i];
  31934. }
  31935. }
  31936. };
  31937. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  31938. for (var i = 0; i < this._impostors.length; ++i) {
  31939. if (this._impostors[i].physicsBody === body) {
  31940. return this._impostors[i];
  31941. }
  31942. }
  31943. };
  31944. // Statics, Legacy support.
  31945. /**
  31946. * @Deprecated
  31947. *
  31948. */
  31949. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  31950. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  31951. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  31952. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  31953. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  31954. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  31955. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  31956. PhysicsEngine.CapsuleImpostor = -1;
  31957. PhysicsEngine.ConeImpostor = -1;
  31958. PhysicsEngine.ConvexHullImpostor = -1;
  31959. PhysicsEngine.Epsilon = 0.001;
  31960. return PhysicsEngine;
  31961. }());
  31962. BABYLON.PhysicsEngine = PhysicsEngine;
  31963. })(BABYLON || (BABYLON = {}));
  31964. //# sourceMappingURL=../Physics/babylon.physicsEngine.js.map
  31965. var BABYLON;
  31966. (function (BABYLON) {
  31967. var VertexData = (function () {
  31968. function VertexData() {
  31969. }
  31970. VertexData.prototype.set = function (data, kind) {
  31971. switch (kind) {
  31972. case BABYLON.VertexBuffer.PositionKind:
  31973. this.positions = data;
  31974. break;
  31975. case BABYLON.VertexBuffer.NormalKind:
  31976. this.normals = data;
  31977. break;
  31978. case BABYLON.VertexBuffer.UVKind:
  31979. this.uvs = data;
  31980. break;
  31981. case BABYLON.VertexBuffer.UV2Kind:
  31982. this.uvs2 = data;
  31983. break;
  31984. case BABYLON.VertexBuffer.UV3Kind:
  31985. this.uvs3 = data;
  31986. break;
  31987. case BABYLON.VertexBuffer.UV4Kind:
  31988. this.uvs4 = data;
  31989. break;
  31990. case BABYLON.VertexBuffer.UV5Kind:
  31991. this.uvs5 = data;
  31992. break;
  31993. case BABYLON.VertexBuffer.UV6Kind:
  31994. this.uvs6 = data;
  31995. break;
  31996. case BABYLON.VertexBuffer.ColorKind:
  31997. this.colors = data;
  31998. break;
  31999. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32000. this.matricesIndices = data;
  32001. break;
  32002. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32003. this.matricesWeights = data;
  32004. break;
  32005. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32006. this.matricesIndicesExtra = data;
  32007. break;
  32008. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32009. this.matricesWeightsExtra = data;
  32010. break;
  32011. }
  32012. };
  32013. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32014. this._applyTo(mesh, updatable);
  32015. };
  32016. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32017. this._applyTo(geometry, updatable);
  32018. };
  32019. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32020. this._update(mesh);
  32021. };
  32022. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32023. this._update(geometry);
  32024. };
  32025. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32026. if (this.positions) {
  32027. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32028. }
  32029. if (this.normals) {
  32030. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32031. }
  32032. if (this.uvs) {
  32033. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32034. }
  32035. if (this.uvs2) {
  32036. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32037. }
  32038. if (this.uvs3) {
  32039. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32040. }
  32041. if (this.uvs4) {
  32042. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32043. }
  32044. if (this.uvs5) {
  32045. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32046. }
  32047. if (this.uvs6) {
  32048. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32049. }
  32050. if (this.colors) {
  32051. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32052. }
  32053. if (this.matricesIndices) {
  32054. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32055. }
  32056. if (this.matricesWeights) {
  32057. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32058. }
  32059. if (this.matricesIndicesExtra) {
  32060. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32061. }
  32062. if (this.matricesWeightsExtra) {
  32063. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32064. }
  32065. if (this.indices) {
  32066. meshOrGeometry.setIndices(this.indices);
  32067. }
  32068. };
  32069. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32070. if (this.positions) {
  32071. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32072. }
  32073. if (this.normals) {
  32074. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32075. }
  32076. if (this.uvs) {
  32077. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32078. }
  32079. if (this.uvs2) {
  32080. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32081. }
  32082. if (this.uvs3) {
  32083. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32084. }
  32085. if (this.uvs4) {
  32086. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32087. }
  32088. if (this.uvs5) {
  32089. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32090. }
  32091. if (this.uvs6) {
  32092. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32093. }
  32094. if (this.colors) {
  32095. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32096. }
  32097. if (this.matricesIndices) {
  32098. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32099. }
  32100. if (this.matricesWeights) {
  32101. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32102. }
  32103. if (this.matricesIndicesExtra) {
  32104. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32105. }
  32106. if (this.matricesWeightsExtra) {
  32107. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32108. }
  32109. if (this.indices) {
  32110. meshOrGeometry.setIndices(this.indices);
  32111. }
  32112. };
  32113. VertexData.prototype.transform = function (matrix) {
  32114. var transformed = BABYLON.Vector3.Zero();
  32115. var index;
  32116. if (this.positions) {
  32117. var position = BABYLON.Vector3.Zero();
  32118. for (index = 0; index < this.positions.length; index += 3) {
  32119. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32120. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32121. this.positions[index] = transformed.x;
  32122. this.positions[index + 1] = transformed.y;
  32123. this.positions[index + 2] = transformed.z;
  32124. }
  32125. }
  32126. if (this.normals) {
  32127. var normal = BABYLON.Vector3.Zero();
  32128. for (index = 0; index < this.normals.length; index += 3) {
  32129. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32130. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32131. this.normals[index] = transformed.x;
  32132. this.normals[index + 1] = transformed.y;
  32133. this.normals[index + 2] = transformed.z;
  32134. }
  32135. }
  32136. };
  32137. VertexData.prototype.merge = function (other) {
  32138. if (other.indices) {
  32139. if (!this.indices) {
  32140. this.indices = [];
  32141. }
  32142. var offset = this.positions ? this.positions.length / 3 : 0;
  32143. for (var index = 0; index < other.indices.length; index++) {
  32144. //TODO check type - if Int32Array!
  32145. this.indices.push(other.indices[index] + offset);
  32146. }
  32147. }
  32148. this.positions = this._mergeElement(this.positions, other.positions);
  32149. this.normals = this._mergeElement(this.normals, other.normals);
  32150. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32151. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32152. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32153. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32154. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32155. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32156. this.colors = this._mergeElement(this.colors, other.colors);
  32157. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32158. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32159. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32160. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32161. };
  32162. VertexData.prototype._mergeElement = function (source, other) {
  32163. if (!other)
  32164. return source;
  32165. if (!source)
  32166. return other;
  32167. var len = other.length + source.length;
  32168. var isSrcTypedArray = source instanceof Float32Array;
  32169. var isOthTypedArray = other instanceof Float32Array;
  32170. // use non-loop method when the source is Float32Array
  32171. if (isSrcTypedArray) {
  32172. var ret32 = new Float32Array(len);
  32173. ret32.set(source);
  32174. ret32.set(other, source.length);
  32175. return ret32;
  32176. }
  32177. else if (!isOthTypedArray) {
  32178. return source.concat(other);
  32179. }
  32180. else {
  32181. var ret = source.slice(0); // copy source to a separate array
  32182. for (var i = 0, len = other.length; i < len; i++) {
  32183. ret.push(other[i]);
  32184. }
  32185. return ret;
  32186. }
  32187. };
  32188. VertexData.prototype.serialize = function () {
  32189. var serializationObject = this.serialize();
  32190. if (this.positions) {
  32191. serializationObject.positions = this.positions;
  32192. }
  32193. if (this.normals) {
  32194. serializationObject.normals = this.normals;
  32195. }
  32196. if (this.uvs) {
  32197. serializationObject.uvs = this.uvs;
  32198. }
  32199. if (this.uvs2) {
  32200. serializationObject.uvs2 = this.uvs2;
  32201. }
  32202. if (this.uvs3) {
  32203. serializationObject.uvs3 = this.uvs3;
  32204. }
  32205. if (this.uvs4) {
  32206. serializationObject.uvs4 = this.uvs4;
  32207. }
  32208. if (this.uvs5) {
  32209. serializationObject.uvs5 = this.uvs5;
  32210. }
  32211. if (this.uvs6) {
  32212. serializationObject.uvs6 = this.uvs6;
  32213. }
  32214. if (this.colors) {
  32215. serializationObject.colors = this.colors;
  32216. }
  32217. if (this.matricesIndices) {
  32218. serializationObject.matricesIndices = this.matricesIndices;
  32219. serializationObject.matricesIndices._isExpanded = true;
  32220. }
  32221. if (this.matricesWeights) {
  32222. serializationObject.matricesWeights = this.matricesWeights;
  32223. }
  32224. if (this.matricesIndicesExtra) {
  32225. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32226. serializationObject.matricesIndicesExtra._isExpanded = true;
  32227. }
  32228. if (this.matricesWeightsExtra) {
  32229. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32230. }
  32231. serializationObject.indices = this.indices;
  32232. return serializationObject;
  32233. };
  32234. // Statics
  32235. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  32236. return VertexData._ExtractFrom(mesh, copyWhenShared);
  32237. };
  32238. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  32239. return VertexData._ExtractFrom(geometry, copyWhenShared);
  32240. };
  32241. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  32242. var result = new VertexData();
  32243. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32244. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  32245. }
  32246. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32247. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  32248. }
  32249. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32250. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  32251. }
  32252. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32253. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  32254. }
  32255. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32256. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  32257. }
  32258. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32259. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  32260. }
  32261. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32262. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  32263. }
  32264. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32265. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  32266. }
  32267. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32268. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  32269. }
  32270. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32271. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  32272. }
  32273. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32274. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  32275. }
  32276. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32277. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  32278. }
  32279. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32280. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  32281. }
  32282. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32283. return result;
  32284. };
  32285. VertexData.CreateRibbon = function (options) {
  32286. var pathArray = options.pathArray;
  32287. var closeArray = options.closeArray || false;
  32288. var closePath = options.closePath || false;
  32289. var invertUV = options.invertUV || false;
  32290. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32291. var offset = options.offset || defaultOffset;
  32292. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32293. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32294. var positions = [];
  32295. var indices = [];
  32296. var normals = [];
  32297. var uvs = [];
  32298. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32299. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32300. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32301. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32302. var minlg; // minimal length among all paths from pathArray
  32303. var lg = []; // array of path lengths : nb of vertex per path
  32304. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32305. var p; // path iterator
  32306. var i; // point iterator
  32307. var j; // point iterator
  32308. // if single path in pathArray
  32309. if (pathArray.length < 2) {
  32310. var ar1 = [];
  32311. var ar2 = [];
  32312. for (i = 0; i < pathArray[0].length - offset; i++) {
  32313. ar1.push(pathArray[0][i]);
  32314. ar2.push(pathArray[0][i + offset]);
  32315. }
  32316. pathArray = [ar1, ar2];
  32317. }
  32318. // positions and horizontal distances (u)
  32319. var idc = 0;
  32320. var closePathCorr = (closePath) ? 1 : 0;
  32321. var path;
  32322. var l;
  32323. minlg = pathArray[0].length;
  32324. var vectlg;
  32325. var dist;
  32326. for (p = 0; p < pathArray.length; p++) {
  32327. uTotalDistance[p] = 0;
  32328. us[p] = [0];
  32329. path = pathArray[p];
  32330. l = path.length;
  32331. minlg = (minlg < l) ? minlg : l;
  32332. j = 0;
  32333. while (j < l) {
  32334. positions.push(path[j].x, path[j].y, path[j].z);
  32335. if (j > 0) {
  32336. vectlg = path[j].subtract(path[j - 1]).length();
  32337. dist = vectlg + uTotalDistance[p];
  32338. us[p].push(dist);
  32339. uTotalDistance[p] = dist;
  32340. }
  32341. j++;
  32342. }
  32343. if (closePath) {
  32344. j--;
  32345. positions.push(path[0].x, path[0].y, path[0].z);
  32346. vectlg = path[j].subtract(path[0]).length();
  32347. dist = vectlg + uTotalDistance[p];
  32348. us[p].push(dist);
  32349. uTotalDistance[p] = dist;
  32350. }
  32351. lg[p] = l + closePathCorr;
  32352. idx[p] = idc;
  32353. idc += (l + closePathCorr);
  32354. }
  32355. // vertical distances (v)
  32356. var path1;
  32357. var path2;
  32358. var vertex1;
  32359. var vertex2;
  32360. for (i = 0; i < minlg + closePathCorr; i++) {
  32361. vTotalDistance[i] = 0;
  32362. vs[i] = [0];
  32363. for (p = 0; p < pathArray.length - 1; p++) {
  32364. path1 = pathArray[p];
  32365. path2 = pathArray[p + 1];
  32366. if (i === minlg) {
  32367. vertex1 = path1[0];
  32368. vertex2 = path2[0];
  32369. }
  32370. else {
  32371. vertex1 = path1[i];
  32372. vertex2 = path2[i];
  32373. }
  32374. vectlg = vertex2.subtract(vertex1).length();
  32375. dist = vectlg + vTotalDistance[i];
  32376. vs[i].push(dist);
  32377. vTotalDistance[i] = dist;
  32378. }
  32379. if (closeArray) {
  32380. path1 = pathArray[p];
  32381. path2 = pathArray[0];
  32382. if (i === minlg) {
  32383. vertex2 = path2[0];
  32384. }
  32385. vectlg = vertex2.subtract(vertex1).length();
  32386. dist = vectlg + vTotalDistance[i];
  32387. vTotalDistance[i] = dist;
  32388. }
  32389. }
  32390. // uvs
  32391. var u;
  32392. var v;
  32393. for (p = 0; p < pathArray.length; p++) {
  32394. for (i = 0; i < minlg + closePathCorr; i++) {
  32395. u = us[p][i] / uTotalDistance[p];
  32396. v = vs[i][p] / vTotalDistance[i];
  32397. if (invertUV) {
  32398. uvs.push(v, u);
  32399. }
  32400. else {
  32401. uvs.push(u, v);
  32402. }
  32403. }
  32404. }
  32405. // indices
  32406. p = 0; // path index
  32407. var pi = 0; // positions array index
  32408. var l1 = lg[p] - 1; // path1 length
  32409. var l2 = lg[p + 1] - 1; // path2 length
  32410. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32411. var shft = idx[1] - idx[0]; // shift
  32412. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32413. while (pi <= min && p < path1nb) {
  32414. // 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
  32415. indices.push(pi, pi + shft, pi + 1);
  32416. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32417. pi += 1;
  32418. if (pi === min) {
  32419. p++;
  32420. if (p === lg.length - 1) {
  32421. shft = idx[0] - idx[p];
  32422. l1 = lg[p] - 1;
  32423. l2 = lg[0] - 1;
  32424. }
  32425. else {
  32426. shft = idx[p + 1] - idx[p];
  32427. l1 = lg[p] - 1;
  32428. l2 = lg[p + 1] - 1;
  32429. }
  32430. pi = idx[p];
  32431. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32432. }
  32433. }
  32434. // normals
  32435. VertexData.ComputeNormals(positions, indices, normals);
  32436. if (closePath) {
  32437. var indexFirst = 0;
  32438. var indexLast = 0;
  32439. for (p = 0; p < pathArray.length; p++) {
  32440. indexFirst = idx[p] * 3;
  32441. if (p + 1 < pathArray.length) {
  32442. indexLast = (idx[p + 1] - 1) * 3;
  32443. }
  32444. else {
  32445. indexLast = normals.length - 3;
  32446. }
  32447. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32448. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32449. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32450. normals[indexLast] = normals[indexFirst];
  32451. normals[indexLast + 1] = normals[indexFirst + 1];
  32452. normals[indexLast + 2] = normals[indexFirst + 2];
  32453. }
  32454. }
  32455. // sides
  32456. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32457. // Result
  32458. var vertexData = new VertexData();
  32459. vertexData.indices = indices;
  32460. vertexData.positions = positions;
  32461. vertexData.normals = normals;
  32462. vertexData.uvs = uvs;
  32463. if (closePath) {
  32464. vertexData._idx = idx;
  32465. }
  32466. return vertexData;
  32467. };
  32468. VertexData.CreateBox = function (options) {
  32469. var normalsSource = [
  32470. new BABYLON.Vector3(0, 0, 1),
  32471. new BABYLON.Vector3(0, 0, -1),
  32472. new BABYLON.Vector3(1, 0, 0),
  32473. new BABYLON.Vector3(-1, 0, 0),
  32474. new BABYLON.Vector3(0, 1, 0),
  32475. new BABYLON.Vector3(0, -1, 0)
  32476. ];
  32477. var indices = [];
  32478. var positions = [];
  32479. var normals = [];
  32480. var uvs = [];
  32481. var width = options.width || options.size || 1;
  32482. var height = options.height || options.size || 1;
  32483. var depth = options.depth || options.size || 1;
  32484. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32485. var faceUV = options.faceUV || new Array(6);
  32486. var faceColors = options.faceColors;
  32487. var colors = [];
  32488. // default face colors and UV if undefined
  32489. for (var f = 0; f < 6; f++) {
  32490. if (faceUV[f] === undefined) {
  32491. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32492. }
  32493. if (faceColors && faceColors[f] === undefined) {
  32494. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32495. }
  32496. }
  32497. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32498. // Create each face in turn.
  32499. for (var index = 0; index < normalsSource.length; index++) {
  32500. var normal = normalsSource[index];
  32501. // Get two vectors perpendicular to the face normal and to each other.
  32502. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32503. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32504. // Six indices (two triangles) per face.
  32505. var verticesLength = positions.length / 3;
  32506. indices.push(verticesLength);
  32507. indices.push(verticesLength + 1);
  32508. indices.push(verticesLength + 2);
  32509. indices.push(verticesLength);
  32510. indices.push(verticesLength + 2);
  32511. indices.push(verticesLength + 3);
  32512. // Four vertices per face.
  32513. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32514. positions.push(vertex.x, vertex.y, vertex.z);
  32515. normals.push(normal.x, normal.y, normal.z);
  32516. uvs.push(faceUV[index].z, faceUV[index].w);
  32517. if (faceColors) {
  32518. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32519. }
  32520. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32521. positions.push(vertex.x, vertex.y, vertex.z);
  32522. normals.push(normal.x, normal.y, normal.z);
  32523. uvs.push(faceUV[index].x, faceUV[index].w);
  32524. if (faceColors) {
  32525. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32526. }
  32527. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32528. positions.push(vertex.x, vertex.y, vertex.z);
  32529. normals.push(normal.x, normal.y, normal.z);
  32530. uvs.push(faceUV[index].x, faceUV[index].y);
  32531. if (faceColors) {
  32532. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32533. }
  32534. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32535. positions.push(vertex.x, vertex.y, vertex.z);
  32536. normals.push(normal.x, normal.y, normal.z);
  32537. uvs.push(faceUV[index].z, faceUV[index].y);
  32538. if (faceColors) {
  32539. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32540. }
  32541. }
  32542. // sides
  32543. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32544. // Result
  32545. var vertexData = new VertexData();
  32546. vertexData.indices = indices;
  32547. vertexData.positions = positions;
  32548. vertexData.normals = normals;
  32549. vertexData.uvs = uvs;
  32550. if (faceColors) {
  32551. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32552. vertexData.colors = totalColors;
  32553. }
  32554. return vertexData;
  32555. };
  32556. VertexData.CreateSphere = function (options) {
  32557. var segments = options.segments || 32;
  32558. var diameterX = options.diameterX || options.diameter || 1;
  32559. var diameterY = options.diameterY || options.diameter || 1;
  32560. var diameterZ = options.diameterZ || options.diameter || 1;
  32561. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32562. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32563. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32564. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32565. var totalZRotationSteps = 2 + segments;
  32566. var totalYRotationSteps = 2 * totalZRotationSteps;
  32567. var indices = [];
  32568. var positions = [];
  32569. var normals = [];
  32570. var uvs = [];
  32571. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32572. var normalizedZ = zRotationStep / totalZRotationSteps;
  32573. var angleZ = normalizedZ * Math.PI * slice;
  32574. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32575. var normalizedY = yRotationStep / totalYRotationSteps;
  32576. var angleY = normalizedY * Math.PI * 2 * arc;
  32577. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32578. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32579. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32580. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32581. var vertex = complete.multiply(radius);
  32582. var normal = complete.divide(radius).normalize();
  32583. positions.push(vertex.x, vertex.y, vertex.z);
  32584. normals.push(normal.x, normal.y, normal.z);
  32585. uvs.push(normalizedY, normalizedZ);
  32586. }
  32587. if (zRotationStep > 0) {
  32588. var verticesCount = positions.length / 3;
  32589. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32590. indices.push((firstIndex));
  32591. indices.push((firstIndex + 1));
  32592. indices.push(firstIndex + totalYRotationSteps + 1);
  32593. indices.push((firstIndex + totalYRotationSteps + 1));
  32594. indices.push((firstIndex + 1));
  32595. indices.push((firstIndex + totalYRotationSteps + 2));
  32596. }
  32597. }
  32598. }
  32599. // Sides
  32600. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32601. // Result
  32602. var vertexData = new VertexData();
  32603. vertexData.indices = indices;
  32604. vertexData.positions = positions;
  32605. vertexData.normals = normals;
  32606. vertexData.uvs = uvs;
  32607. return vertexData;
  32608. };
  32609. // Cylinder and cone
  32610. VertexData.CreateCylinder = function (options) {
  32611. var height = options.height || 2;
  32612. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32613. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32614. var tessellation = options.tessellation || 24;
  32615. var subdivisions = options.subdivisions || 1;
  32616. var hasRings = options.hasRings;
  32617. var enclose = options.enclose;
  32618. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32619. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32620. var faceUV = options.faceUV || new Array(3);
  32621. var faceColors = options.faceColors;
  32622. // default face colors and UV if undefined
  32623. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32624. var ringNb = (hasRings) ? subdivisions : 1;
  32625. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32626. var f;
  32627. for (f = 0; f < surfaceNb; f++) {
  32628. if (faceColors && faceColors[f] === undefined) {
  32629. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32630. }
  32631. }
  32632. for (f = 0; f < surfaceNb; f++) {
  32633. if (faceUV && faceUV[f] === undefined) {
  32634. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32635. }
  32636. }
  32637. var indices = [];
  32638. var positions = [];
  32639. var normals = [];
  32640. var uvs = [];
  32641. var colors = [];
  32642. var angle_step = Math.PI * 2 * arc / tessellation;
  32643. var angle;
  32644. var h;
  32645. var radius;
  32646. var tan = (diameterBottom - diameterTop) / 2 / height;
  32647. var ringVertex = BABYLON.Vector3.Zero();
  32648. var ringNormal = BABYLON.Vector3.Zero();
  32649. var ringFirstVertex = BABYLON.Vector3.Zero();
  32650. var ringFirstNormal = BABYLON.Vector3.Zero();
  32651. var quadNormal = BABYLON.Vector3.Zero();
  32652. var Y = BABYLON.Axis.Y;
  32653. // positions, normals, uvs
  32654. var i;
  32655. var j;
  32656. var r;
  32657. var ringIdx = 1;
  32658. var s = 1; // surface index
  32659. var cs = 0;
  32660. var v = 0;
  32661. for (i = 0; i <= subdivisions; i++) {
  32662. h = i / subdivisions;
  32663. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32664. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32665. for (r = 0; r < ringIdx; r++) {
  32666. if (hasRings) {
  32667. s += r;
  32668. }
  32669. if (enclose) {
  32670. s += 2 * r;
  32671. }
  32672. for (j = 0; j <= tessellation; j++) {
  32673. angle = j * angle_step;
  32674. // position
  32675. ringVertex.x = Math.cos(-angle) * radius;
  32676. ringVertex.y = -height / 2 + h * height;
  32677. ringVertex.z = Math.sin(-angle) * radius;
  32678. // normal
  32679. if (diameterTop === 0 && i === subdivisions) {
  32680. // if no top cap, reuse former normals
  32681. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32682. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32683. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32684. }
  32685. else {
  32686. ringNormal.x = ringVertex.x;
  32687. ringNormal.z = ringVertex.z;
  32688. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32689. ringNormal.normalize();
  32690. }
  32691. // keep first ring vertex values for enclose
  32692. if (j === 0) {
  32693. ringFirstVertex.copyFrom(ringVertex);
  32694. ringFirstNormal.copyFrom(ringNormal);
  32695. }
  32696. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32697. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32698. if (hasRings) {
  32699. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32700. }
  32701. else {
  32702. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32703. }
  32704. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32705. if (faceColors) {
  32706. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32707. }
  32708. }
  32709. // if enclose, add four vertices and their dedicated normals
  32710. if (arc !== 1 && enclose) {
  32711. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32712. positions.push(0, ringVertex.y, 0);
  32713. positions.push(0, ringVertex.y, 0);
  32714. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32715. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32716. quadNormal.normalize();
  32717. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32718. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32719. quadNormal.normalize();
  32720. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32721. if (hasRings) {
  32722. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32723. }
  32724. else {
  32725. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32726. }
  32727. uvs.push(faceUV[s + 1].x, v);
  32728. uvs.push(faceUV[s + 1].z, v);
  32729. if (hasRings) {
  32730. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32731. }
  32732. else {
  32733. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32734. }
  32735. uvs.push(faceUV[s + 2].x, v);
  32736. uvs.push(faceUV[s + 2].z, v);
  32737. if (faceColors) {
  32738. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32739. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32740. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32741. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32742. }
  32743. }
  32744. if (cs !== s) {
  32745. cs = s;
  32746. }
  32747. }
  32748. }
  32749. // indices
  32750. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32751. var s;
  32752. i = 0;
  32753. for (s = 0; s < subdivisions; s++) {
  32754. for (j = 0; j < tessellation; j++) {
  32755. var i0 = i * (e + 1) + j;
  32756. var i1 = (i + 1) * (e + 1) + j;
  32757. var i2 = i * (e + 1) + (j + 1);
  32758. var i3 = (i + 1) * (e + 1) + (j + 1);
  32759. indices.push(i0, i1, i2);
  32760. indices.push(i3, i2, i1);
  32761. }
  32762. if (arc !== 1 && enclose) {
  32763. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32764. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32765. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32766. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32767. }
  32768. i = (hasRings) ? (i + 2) : (i + 1);
  32769. }
  32770. // Caps
  32771. var createCylinderCap = function (isTop) {
  32772. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32773. if (radius === 0) {
  32774. return;
  32775. }
  32776. // Cap positions, normals & uvs
  32777. var angle;
  32778. var circleVector;
  32779. var i;
  32780. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32781. var c;
  32782. if (faceColors) {
  32783. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32784. }
  32785. // cap center
  32786. var vbase = positions.length / 3;
  32787. var offset = isTop ? height / 2 : -height / 2;
  32788. var center = new BABYLON.Vector3(0, offset, 0);
  32789. positions.push(center.x, center.y, center.z);
  32790. normals.push(0, isTop ? 1 : -1, 0);
  32791. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32792. if (faceColors) {
  32793. colors.push(c.r, c.g, c.b, c.a);
  32794. }
  32795. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32796. for (i = 0; i <= tessellation; i++) {
  32797. angle = Math.PI * 2 * i * arc / tessellation;
  32798. var cos = Math.cos(-angle);
  32799. var sin = Math.sin(-angle);
  32800. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32801. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32802. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32803. normals.push(0, isTop ? 1 : -1, 0);
  32804. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32805. if (faceColors) {
  32806. colors.push(c.r, c.g, c.b, c.a);
  32807. }
  32808. }
  32809. // Cap indices
  32810. for (i = 0; i < tessellation; i++) {
  32811. if (!isTop) {
  32812. indices.push(vbase);
  32813. indices.push(vbase + (i + 1));
  32814. indices.push(vbase + (i + 2));
  32815. }
  32816. else {
  32817. indices.push(vbase);
  32818. indices.push(vbase + (i + 2));
  32819. indices.push(vbase + (i + 1));
  32820. }
  32821. }
  32822. };
  32823. // add caps to geometry
  32824. createCylinderCap(false);
  32825. createCylinderCap(true);
  32826. // Sides
  32827. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32828. var vertexData = new VertexData();
  32829. vertexData.indices = indices;
  32830. vertexData.positions = positions;
  32831. vertexData.normals = normals;
  32832. vertexData.uvs = uvs;
  32833. if (faceColors) {
  32834. vertexData.colors = colors;
  32835. }
  32836. return vertexData;
  32837. };
  32838. VertexData.CreateTorus = function (options) {
  32839. var indices = [];
  32840. var positions = [];
  32841. var normals = [];
  32842. var uvs = [];
  32843. var diameter = options.diameter || 1;
  32844. var thickness = options.thickness || 0.5;
  32845. var tessellation = options.tessellation || 16;
  32846. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32847. var stride = tessellation + 1;
  32848. for (var i = 0; i <= tessellation; i++) {
  32849. var u = i / tessellation;
  32850. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32851. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32852. for (var j = 0; j <= tessellation; j++) {
  32853. var v = 1 - j / tessellation;
  32854. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32855. var dx = Math.cos(innerAngle);
  32856. var dy = Math.sin(innerAngle);
  32857. // Create a vertex.
  32858. var normal = new BABYLON.Vector3(dx, dy, 0);
  32859. var position = normal.scale(thickness / 2);
  32860. var textureCoordinate = new BABYLON.Vector2(u, v);
  32861. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32862. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32863. positions.push(position.x, position.y, position.z);
  32864. normals.push(normal.x, normal.y, normal.z);
  32865. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32866. // And create indices for two triangles.
  32867. var nextI = (i + 1) % stride;
  32868. var nextJ = (j + 1) % stride;
  32869. indices.push(i * stride + j);
  32870. indices.push(i * stride + nextJ);
  32871. indices.push(nextI * stride + j);
  32872. indices.push(i * stride + nextJ);
  32873. indices.push(nextI * stride + nextJ);
  32874. indices.push(nextI * stride + j);
  32875. }
  32876. }
  32877. // Sides
  32878. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32879. // Result
  32880. var vertexData = new VertexData();
  32881. vertexData.indices = indices;
  32882. vertexData.positions = positions;
  32883. vertexData.normals = normals;
  32884. vertexData.uvs = uvs;
  32885. return vertexData;
  32886. };
  32887. VertexData.CreateLineSystem = function (options) {
  32888. var indices = [];
  32889. var positions = [];
  32890. var lines = options.lines;
  32891. var idx = 0;
  32892. for (var l = 0; l < lines.length; l++) {
  32893. var points = lines[l];
  32894. for (var index = 0; index < points.length; index++) {
  32895. positions.push(points[index].x, points[index].y, points[index].z);
  32896. if (index > 0) {
  32897. indices.push(idx - 1);
  32898. indices.push(idx);
  32899. }
  32900. idx++;
  32901. }
  32902. }
  32903. var vertexData = new VertexData();
  32904. vertexData.indices = indices;
  32905. vertexData.positions = positions;
  32906. return vertexData;
  32907. };
  32908. VertexData.CreateDashedLines = function (options) {
  32909. var dashSize = options.dashSize || 3;
  32910. var gapSize = options.gapSize || 1;
  32911. var dashNb = options.dashNb || 200;
  32912. var points = options.points;
  32913. var positions = new Array();
  32914. var indices = new Array();
  32915. var curvect = BABYLON.Vector3.Zero();
  32916. var lg = 0;
  32917. var nb = 0;
  32918. var shft = 0;
  32919. var dashshft = 0;
  32920. var curshft = 0;
  32921. var idx = 0;
  32922. var i = 0;
  32923. for (i = 0; i < points.length - 1; i++) {
  32924. points[i + 1].subtractToRef(points[i], curvect);
  32925. lg += curvect.length();
  32926. }
  32927. shft = lg / dashNb;
  32928. dashshft = dashSize * shft / (dashSize + gapSize);
  32929. for (i = 0; i < points.length - 1; i++) {
  32930. points[i + 1].subtractToRef(points[i], curvect);
  32931. nb = Math.floor(curvect.length() / shft);
  32932. curvect.normalize();
  32933. for (var j = 0; j < nb; j++) {
  32934. curshft = shft * j;
  32935. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  32936. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  32937. indices.push(idx, idx + 1);
  32938. idx += 2;
  32939. }
  32940. }
  32941. // Result
  32942. var vertexData = new VertexData();
  32943. vertexData.positions = positions;
  32944. vertexData.indices = indices;
  32945. return vertexData;
  32946. };
  32947. VertexData.CreateGround = function (options) {
  32948. var indices = [];
  32949. var positions = [];
  32950. var normals = [];
  32951. var uvs = [];
  32952. var row, col;
  32953. var width = options.width || 1;
  32954. var height = options.height || 1;
  32955. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  32956. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  32957. for (row = 0; row <= subdivisionsY; row++) {
  32958. for (col = 0; col <= subdivisionsX; col++) {
  32959. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  32960. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32961. positions.push(position.x, position.y, position.z);
  32962. normals.push(normal.x, normal.y, normal.z);
  32963. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  32964. }
  32965. }
  32966. for (row = 0; row < subdivisionsY; row++) {
  32967. for (col = 0; col < subdivisionsX; col++) {
  32968. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32969. indices.push(col + 1 + row * (subdivisionsX + 1));
  32970. indices.push(col + row * (subdivisionsX + 1));
  32971. indices.push(col + (row + 1) * (subdivisionsX + 1));
  32972. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32973. indices.push(col + row * (subdivisionsX + 1));
  32974. }
  32975. }
  32976. // Result
  32977. var vertexData = new VertexData();
  32978. vertexData.indices = indices;
  32979. vertexData.positions = positions;
  32980. vertexData.normals = normals;
  32981. vertexData.uvs = uvs;
  32982. return vertexData;
  32983. };
  32984. VertexData.CreateTiledGround = function (options) {
  32985. var xmin = options.xmin || -1.0;
  32986. var zmin = options.zmin || -1.0;
  32987. var xmax = options.xmax || 1.0;
  32988. var zmax = options.zmax || 1.0;
  32989. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  32990. var precision = options.precision || { w: 1, h: 1 };
  32991. var indices = [];
  32992. var positions = [];
  32993. var normals = [];
  32994. var uvs = [];
  32995. var row, col, tileRow, tileCol;
  32996. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  32997. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  32998. precision.w = (precision.w < 1) ? 1 : precision.w;
  32999. precision.h = (precision.h < 1) ? 1 : precision.h;
  33000. var tileSize = {
  33001. 'w': (xmax - xmin) / subdivisions.w,
  33002. 'h': (zmax - zmin) / subdivisions.h
  33003. };
  33004. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33005. // Indices
  33006. var base = positions.length / 3;
  33007. var rowLength = precision.w + 1;
  33008. for (row = 0; row < precision.h; row++) {
  33009. for (col = 0; col < precision.w; col++) {
  33010. var square = [
  33011. base + col + row * rowLength,
  33012. base + (col + 1) + row * rowLength,
  33013. base + (col + 1) + (row + 1) * rowLength,
  33014. base + col + (row + 1) * rowLength
  33015. ];
  33016. indices.push(square[1]);
  33017. indices.push(square[2]);
  33018. indices.push(square[3]);
  33019. indices.push(square[0]);
  33020. indices.push(square[1]);
  33021. indices.push(square[3]);
  33022. }
  33023. }
  33024. // Position, normals and uvs
  33025. var position = BABYLON.Vector3.Zero();
  33026. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33027. for (row = 0; row <= precision.h; row++) {
  33028. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33029. for (col = 0; col <= precision.w; col++) {
  33030. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33031. position.y = 0;
  33032. positions.push(position.x, position.y, position.z);
  33033. normals.push(normal.x, normal.y, normal.z);
  33034. uvs.push(col / precision.w, row / precision.h);
  33035. }
  33036. }
  33037. }
  33038. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33039. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33040. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33041. }
  33042. }
  33043. // Result
  33044. var vertexData = new VertexData();
  33045. vertexData.indices = indices;
  33046. vertexData.positions = positions;
  33047. vertexData.normals = normals;
  33048. vertexData.uvs = uvs;
  33049. return vertexData;
  33050. };
  33051. VertexData.CreateGroundFromHeightMap = function (options) {
  33052. var indices = [];
  33053. var positions = [];
  33054. var normals = [];
  33055. var uvs = [];
  33056. var row, col;
  33057. // Vertices
  33058. for (row = 0; row <= options.subdivisions; row++) {
  33059. for (col = 0; col <= options.subdivisions; col++) {
  33060. 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));
  33061. // Compute height
  33062. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33063. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33064. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33065. var r = options.buffer[pos] / 255.0;
  33066. var g = options.buffer[pos + 1] / 255.0;
  33067. var b = options.buffer[pos + 2] / 255.0;
  33068. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33069. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33070. // Add vertex
  33071. positions.push(position.x, position.y, position.z);
  33072. normals.push(0, 0, 0);
  33073. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33074. }
  33075. }
  33076. // Indices
  33077. for (row = 0; row < options.subdivisions; row++) {
  33078. for (col = 0; col < options.subdivisions; col++) {
  33079. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33080. indices.push(col + 1 + row * (options.subdivisions + 1));
  33081. indices.push(col + row * (options.subdivisions + 1));
  33082. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33083. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33084. indices.push(col + row * (options.subdivisions + 1));
  33085. }
  33086. }
  33087. // Normals
  33088. VertexData.ComputeNormals(positions, indices, normals);
  33089. // Result
  33090. var vertexData = new VertexData();
  33091. vertexData.indices = indices;
  33092. vertexData.positions = positions;
  33093. vertexData.normals = normals;
  33094. vertexData.uvs = uvs;
  33095. return vertexData;
  33096. };
  33097. VertexData.CreatePlane = function (options) {
  33098. var indices = [];
  33099. var positions = [];
  33100. var normals = [];
  33101. var uvs = [];
  33102. var width = options.width || options.size || 1;
  33103. var height = options.height || options.size || 1;
  33104. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33105. // Vertices
  33106. var halfWidth = width / 2.0;
  33107. var halfHeight = height / 2.0;
  33108. positions.push(-halfWidth, -halfHeight, 0);
  33109. normals.push(0, 0, -1.0);
  33110. uvs.push(0.0, 0.0);
  33111. positions.push(halfWidth, -halfHeight, 0);
  33112. normals.push(0, 0, -1.0);
  33113. uvs.push(1.0, 0.0);
  33114. positions.push(halfWidth, halfHeight, 0);
  33115. normals.push(0, 0, -1.0);
  33116. uvs.push(1.0, 1.0);
  33117. positions.push(-halfWidth, halfHeight, 0);
  33118. normals.push(0, 0, -1.0);
  33119. uvs.push(0.0, 1.0);
  33120. // Indices
  33121. indices.push(0);
  33122. indices.push(1);
  33123. indices.push(2);
  33124. indices.push(0);
  33125. indices.push(2);
  33126. indices.push(3);
  33127. // Sides
  33128. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33129. // Result
  33130. var vertexData = new VertexData();
  33131. vertexData.indices = indices;
  33132. vertexData.positions = positions;
  33133. vertexData.normals = normals;
  33134. vertexData.uvs = uvs;
  33135. return vertexData;
  33136. };
  33137. VertexData.CreateDisc = function (options) {
  33138. var positions = [];
  33139. var indices = [];
  33140. var normals = [];
  33141. var uvs = [];
  33142. var radius = options.radius || 0.5;
  33143. var tessellation = options.tessellation || 64;
  33144. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33145. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33146. // positions and uvs
  33147. positions.push(0, 0, 0); // disc center first
  33148. uvs.push(0.5, 0.5);
  33149. var theta = Math.PI * 2 * arc;
  33150. var step = theta / tessellation;
  33151. for (var a = 0; a < theta; a += step) {
  33152. var x = Math.cos(a);
  33153. var y = Math.sin(a);
  33154. var u = (x + 1) / 2;
  33155. var v = (1 - y) / 2;
  33156. positions.push(radius * x, radius * y, 0);
  33157. uvs.push(u, v);
  33158. }
  33159. if (arc === 1) {
  33160. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33161. uvs.push(uvs[2], uvs[3]);
  33162. }
  33163. //indices
  33164. var vertexNb = positions.length / 3;
  33165. for (var i = 1; i < vertexNb - 1; i++) {
  33166. indices.push(i + 1, 0, i);
  33167. }
  33168. // result
  33169. VertexData.ComputeNormals(positions, indices, normals);
  33170. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33171. var vertexData = new VertexData();
  33172. vertexData.indices = indices;
  33173. vertexData.positions = positions;
  33174. vertexData.normals = normals;
  33175. vertexData.uvs = uvs;
  33176. return vertexData;
  33177. };
  33178. VertexData.CreateIcoSphere = function (options) {
  33179. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33180. var radius = options.radius || 1;
  33181. var flat = (options.flat === undefined) ? true : options.flat;
  33182. var subdivisions = options.subdivisions || 4;
  33183. var radiusX = options.radiusX || radius;
  33184. var radiusY = options.radiusY || radius;
  33185. var radiusZ = options.radiusZ || radius;
  33186. var t = (1 + Math.sqrt(5)) / 2;
  33187. // 12 vertex x,y,z
  33188. var ico_vertices = [
  33189. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33190. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33191. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33192. ];
  33193. // index of 3 vertex makes a face of icopshere
  33194. var ico_indices = [
  33195. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33196. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33197. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33198. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33199. ];
  33200. // vertex for uv have aliased position, not for UV
  33201. var vertices_unalias_id = [
  33202. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33203. // vertex alias
  33204. 0,
  33205. 2,
  33206. 3,
  33207. 3,
  33208. 3,
  33209. 4,
  33210. 7,
  33211. 8,
  33212. 9,
  33213. 9,
  33214. 10,
  33215. 11 // 23: B + 12
  33216. ];
  33217. // uv as integer step (not pixels !)
  33218. var ico_vertexuv = [
  33219. 5, 1, 3, 1, 6, 4, 0, 0,
  33220. 5, 3, 4, 2, 2, 2, 4, 0,
  33221. 2, 0, 1, 1, 6, 0, 6, 2,
  33222. // vertex alias (for same vertex on different faces)
  33223. 0, 4,
  33224. 3, 3,
  33225. 4, 4,
  33226. 3, 1,
  33227. 4, 2,
  33228. 4, 4,
  33229. 0, 2,
  33230. 1, 1,
  33231. 2, 2,
  33232. 3, 3,
  33233. 1, 3,
  33234. 2, 4 // 23: B + 12
  33235. ];
  33236. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33237. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33238. // First island of uv mapping
  33239. // v = 4h 3+ 2
  33240. // v = 3h 9+ 4
  33241. // v = 2h 9+ 5 B
  33242. // v = 1h 9 1 0
  33243. // v = 0h 3 8 7 A
  33244. // u = 0 1 2 3 4 5 6 *a
  33245. // Second island of uv mapping
  33246. // v = 4h 0+ B+ 4+
  33247. // v = 3h A+ 2+
  33248. // v = 2h 7+ 6 3+
  33249. // v = 1h 8+ 3+
  33250. // v = 0h
  33251. // u = 0 1 2 3 4 5 6 *a
  33252. // Face layout on texture UV mapping
  33253. // ============
  33254. // \ 4 /\ 16 / ======
  33255. // \ / \ / /\ 11 /
  33256. // \/ 7 \/ / \ /
  33257. // ======= / 10 \/
  33258. // /\ 17 /\ =======
  33259. // / \ / \ \ 15 /\
  33260. // / 8 \/ 12 \ \ / \
  33261. // ============ \/ 6 \
  33262. // \ 18 /\ ============
  33263. // \ / \ \ 5 /\ 0 /
  33264. // \/ 13 \ \ / \ /
  33265. // ======= \/ 1 \/
  33266. // =============
  33267. // /\ 19 /\ 2 /\
  33268. // / \ / \ / \
  33269. // / 14 \/ 9 \/ 3 \
  33270. // ===================
  33271. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33272. var ustep = 138 / 1024;
  33273. var vstep = 239 / 1024;
  33274. var uoffset = 60 / 1024;
  33275. var voffset = 26 / 1024;
  33276. // Second island should have margin, not to touch the first island
  33277. // avoid any borderline artefact in pixel rounding
  33278. var island_u_offset = -40 / 1024;
  33279. var island_v_offset = +20 / 1024;
  33280. // face is either island 0 or 1 :
  33281. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33282. var island = [
  33283. 0, 0, 0, 0, 1,
  33284. 0, 0, 1, 1, 0,
  33285. 0, 0, 1, 1, 0,
  33286. 0, 1, 1, 1, 0 // 15 - 19
  33287. ];
  33288. var indices = [];
  33289. var positions = [];
  33290. var normals = [];
  33291. var uvs = [];
  33292. var current_indice = 0;
  33293. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33294. var face_vertex_pos = new Array(3);
  33295. var face_vertex_uv = new Array(3);
  33296. var v012;
  33297. for (v012 = 0; v012 < 3; v012++) {
  33298. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33299. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33300. }
  33301. // create all with normals
  33302. for (var face = 0; face < 20; face++) {
  33303. // 3 vertex per face
  33304. for (v012 = 0; v012 < 3; v012++) {
  33305. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33306. var v_id = ico_indices[3 * face + v012];
  33307. // vertex have 3D position (x,y,z)
  33308. 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]);
  33309. // Normalize to get normal, then scale to radius
  33310. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33311. // uv Coordinates from vertex ID
  33312. 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);
  33313. }
  33314. // Subdivide the face (interpolate pos, norm, uv)
  33315. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33316. // - norm is linear interpolation of vertex corner normal
  33317. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33318. // - uv is linear interpolation
  33319. //
  33320. // Topology is as below for sub-divide by 2
  33321. // vertex shown as v0,v1,v2
  33322. // interp index is i1 to progress in range [v0,v1[
  33323. // interp index is i2 to progress in range [v0,v2[
  33324. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33325. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33326. //
  33327. //
  33328. // i2 v2
  33329. // ^ ^
  33330. // / / \
  33331. // / / \
  33332. // / / \
  33333. // / / (0,1) \
  33334. // / #---------\
  33335. // / / \ (0,0)'/ \
  33336. // / / \ / \
  33337. // / / \ / \
  33338. // / / (0,0) \ / (1,0) \
  33339. // / #---------#---------\
  33340. // v0 v1
  33341. //
  33342. // --------------------> i1
  33343. //
  33344. // interp of (i1,i2):
  33345. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33346. // along i1 : lerp(x0,x1, i1/(S-i2))
  33347. //
  33348. // centroid of triangle is needed to get help normal computation
  33349. // (c1,c2) are used for centroid location
  33350. var interp_vertex = function (i1, i2, c1, c2) {
  33351. // vertex is interpolated from
  33352. // - face_vertex_pos[0..2]
  33353. // - face_vertex_uv[0..2]
  33354. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33355. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33356. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33357. pos_interp.normalize();
  33358. var vertex_normal;
  33359. if (flat) {
  33360. // in flat mode, recalculate normal as face centroid normal
  33361. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33362. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33363. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33364. }
  33365. else {
  33366. // in smooth mode, recalculate normal from each single vertex position
  33367. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33368. }
  33369. // Vertex normal need correction due to X,Y,Z radius scaling
  33370. vertex_normal.x /= radiusX;
  33371. vertex_normal.y /= radiusY;
  33372. vertex_normal.z /= radiusZ;
  33373. vertex_normal.normalize();
  33374. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33375. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33376. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33377. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33378. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33379. uvs.push(uv_interp.x, uv_interp.y);
  33380. // push each vertex has member of a face
  33381. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33382. indices.push(current_indice);
  33383. current_indice++;
  33384. };
  33385. for (var i2 = 0; i2 < subdivisions; i2++) {
  33386. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33387. // face : (i1,i2) for /\ :
  33388. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33389. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33390. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33391. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33392. if (i1 + i2 + 1 < subdivisions) {
  33393. // face : (i1,i2)' for \/ :
  33394. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33395. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33396. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33397. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33398. }
  33399. }
  33400. }
  33401. }
  33402. // Sides
  33403. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33404. // Result
  33405. var vertexData = new VertexData();
  33406. vertexData.indices = indices;
  33407. vertexData.positions = positions;
  33408. vertexData.normals = normals;
  33409. vertexData.uvs = uvs;
  33410. return vertexData;
  33411. };
  33412. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33413. VertexData.CreatePolyhedron = function (options) {
  33414. // provided polyhedron types :
  33415. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33416. // 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)
  33417. var polyhedra = [];
  33418. 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]] };
  33419. 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]] };
  33420. polyhedra[2] = {
  33421. 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]],
  33422. 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]]
  33423. };
  33424. polyhedra[3] = {
  33425. 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]],
  33426. 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]]
  33427. };
  33428. polyhedra[4] = {
  33429. 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]],
  33430. 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]]
  33431. };
  33432. 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]] };
  33433. 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]] };
  33434. 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]] };
  33435. 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]] };
  33436. 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]] };
  33437. 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]] };
  33438. 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]] };
  33439. 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]] };
  33440. 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]] };
  33441. polyhedra[14] = {
  33442. 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]],
  33443. 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]]
  33444. };
  33445. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33446. var size = options.size;
  33447. var sizeX = options.sizeX || size || 1;
  33448. var sizeY = options.sizeY || size || 1;
  33449. var sizeZ = options.sizeZ || size || 1;
  33450. var data = options.custom || polyhedra[type];
  33451. var nbfaces = data.face.length;
  33452. var faceUV = options.faceUV || new Array(nbfaces);
  33453. var faceColors = options.faceColors;
  33454. var flat = (options.flat === undefined) ? true : options.flat;
  33455. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33456. var positions = [];
  33457. var indices = [];
  33458. var normals = [];
  33459. var uvs = [];
  33460. var colors = [];
  33461. var index = 0;
  33462. var faceIdx = 0; // face cursor in the array "indexes"
  33463. var indexes = [];
  33464. var i = 0;
  33465. var f = 0;
  33466. var u, v, ang, x, y, tmp;
  33467. // default face colors and UV if undefined
  33468. if (flat) {
  33469. for (f = 0; f < nbfaces; f++) {
  33470. if (faceColors && faceColors[f] === undefined) {
  33471. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33472. }
  33473. if (faceUV && faceUV[f] === undefined) {
  33474. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33475. }
  33476. }
  33477. }
  33478. if (!flat) {
  33479. for (i = 0; i < data.vertex.length; i++) {
  33480. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33481. uvs.push(0, 0);
  33482. }
  33483. for (f = 0; f < nbfaces; f++) {
  33484. for (i = 0; i < data.face[f].length - 2; i++) {
  33485. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33486. }
  33487. }
  33488. }
  33489. else {
  33490. for (f = 0; f < nbfaces; f++) {
  33491. var fl = data.face[f].length; // number of vertices of the current face
  33492. ang = 2 * Math.PI / fl;
  33493. x = 0.5 * Math.tan(ang / 2);
  33494. y = 0.5;
  33495. // positions, uvs, colors
  33496. for (i = 0; i < fl; i++) {
  33497. // positions
  33498. 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);
  33499. indexes.push(index);
  33500. index++;
  33501. // uvs
  33502. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33503. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33504. uvs.push(u, v);
  33505. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33506. y = x * Math.sin(ang) + y * Math.cos(ang);
  33507. x = tmp;
  33508. // colors
  33509. if (faceColors) {
  33510. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33511. }
  33512. }
  33513. // indices from indexes
  33514. for (i = 0; i < fl - 2; i++) {
  33515. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33516. }
  33517. faceIdx += fl;
  33518. }
  33519. }
  33520. VertexData.ComputeNormals(positions, indices, normals);
  33521. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33522. var vertexData = new VertexData();
  33523. vertexData.positions = positions;
  33524. vertexData.indices = indices;
  33525. vertexData.normals = normals;
  33526. vertexData.uvs = uvs;
  33527. if (faceColors && flat) {
  33528. vertexData.colors = colors;
  33529. }
  33530. return vertexData;
  33531. };
  33532. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33533. VertexData.CreateTorusKnot = function (options) {
  33534. var indices = [];
  33535. var positions = [];
  33536. var normals = [];
  33537. var uvs = [];
  33538. var radius = options.radius || 2;
  33539. var tube = options.tube || 0.5;
  33540. var radialSegments = options.radialSegments || 32;
  33541. var tubularSegments = options.tubularSegments || 32;
  33542. var p = options.p || 2;
  33543. var q = options.q || 3;
  33544. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33545. // Helper
  33546. var getPos = function (angle) {
  33547. var cu = Math.cos(angle);
  33548. var su = Math.sin(angle);
  33549. var quOverP = q / p * angle;
  33550. var cs = Math.cos(quOverP);
  33551. var tx = radius * (2 + cs) * 0.5 * cu;
  33552. var ty = radius * (2 + cs) * su * 0.5;
  33553. var tz = radius * Math.sin(quOverP) * 0.5;
  33554. return new BABYLON.Vector3(tx, ty, tz);
  33555. };
  33556. // Vertices
  33557. var i;
  33558. var j;
  33559. for (i = 0; i <= radialSegments; i++) {
  33560. var modI = i % radialSegments;
  33561. var u = modI / radialSegments * 2 * p * Math.PI;
  33562. var p1 = getPos(u);
  33563. var p2 = getPos(u + 0.01);
  33564. var tang = p2.subtract(p1);
  33565. var n = p2.add(p1);
  33566. var bitan = BABYLON.Vector3.Cross(tang, n);
  33567. n = BABYLON.Vector3.Cross(bitan, tang);
  33568. bitan.normalize();
  33569. n.normalize();
  33570. for (j = 0; j < tubularSegments; j++) {
  33571. var modJ = j % tubularSegments;
  33572. var v = modJ / tubularSegments * 2 * Math.PI;
  33573. var cx = -tube * Math.cos(v);
  33574. var cy = tube * Math.sin(v);
  33575. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33576. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33577. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33578. uvs.push(i / radialSegments);
  33579. uvs.push(j / tubularSegments);
  33580. }
  33581. }
  33582. for (i = 0; i < radialSegments; i++) {
  33583. for (j = 0; j < tubularSegments; j++) {
  33584. var jNext = (j + 1) % tubularSegments;
  33585. var a = i * tubularSegments + j;
  33586. var b = (i + 1) * tubularSegments + j;
  33587. var c = (i + 1) * tubularSegments + jNext;
  33588. var d = i * tubularSegments + jNext;
  33589. indices.push(d);
  33590. indices.push(b);
  33591. indices.push(a);
  33592. indices.push(d);
  33593. indices.push(c);
  33594. indices.push(b);
  33595. }
  33596. }
  33597. // Normals
  33598. VertexData.ComputeNormals(positions, indices, normals);
  33599. // Sides
  33600. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33601. // Result
  33602. var vertexData = new VertexData();
  33603. vertexData.indices = indices;
  33604. vertexData.positions = positions;
  33605. vertexData.normals = normals;
  33606. vertexData.uvs = uvs;
  33607. return vertexData;
  33608. };
  33609. // Tools
  33610. /**
  33611. * @param {any} - positions (number[] or Float32Array)
  33612. * @param {any} - indices (number[] or Uint16Array)
  33613. * @param {any} - normals (number[] or Float32Array)
  33614. */
  33615. VertexData.ComputeNormals = function (positions, indices, normals) {
  33616. var index = 0;
  33617. var p1p2x = 0.0;
  33618. var p1p2y = 0.0;
  33619. var p1p2z = 0.0;
  33620. var p3p2x = 0.0;
  33621. var p3p2y = 0.0;
  33622. var p3p2z = 0.0;
  33623. var faceNormalx = 0.0;
  33624. var faceNormaly = 0.0;
  33625. var faceNormalz = 0.0;
  33626. var length = 0.0;
  33627. var i1 = 0;
  33628. var i2 = 0;
  33629. var i3 = 0;
  33630. for (index = 0; index < positions.length; index++) {
  33631. normals[index] = 0.0;
  33632. }
  33633. // indice triplet = 1 face
  33634. var nbFaces = indices.length / 3;
  33635. for (index = 0; index < nbFaces; index++) {
  33636. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  33637. i2 = indices[index * 3 + 1];
  33638. i3 = indices[index * 3 + 2];
  33639. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  33640. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  33641. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  33642. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  33643. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  33644. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  33645. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  33646. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  33647. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  33648. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33649. length = (length === 0) ? 1.0 : length;
  33650. faceNormalx /= length; // normalize this normal
  33651. faceNormaly /= length;
  33652. faceNormalz /= length;
  33653. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  33654. normals[i1 * 3 + 1] += faceNormaly;
  33655. normals[i1 * 3 + 2] += faceNormalz;
  33656. normals[i2 * 3] += faceNormalx;
  33657. normals[i2 * 3 + 1] += faceNormaly;
  33658. normals[i2 * 3 + 2] += faceNormalz;
  33659. normals[i3 * 3] += faceNormalx;
  33660. normals[i3 * 3 + 1] += faceNormaly;
  33661. normals[i3 * 3 + 2] += faceNormalz;
  33662. }
  33663. // last normalization of each normal
  33664. for (index = 0; index < normals.length / 3; index++) {
  33665. faceNormalx = normals[index * 3];
  33666. faceNormaly = normals[index * 3 + 1];
  33667. faceNormalz = normals[index * 3 + 2];
  33668. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33669. length = (length === 0) ? 1.0 : length;
  33670. faceNormalx /= length;
  33671. faceNormaly /= length;
  33672. faceNormalz /= length;
  33673. normals[index * 3] = faceNormalx;
  33674. normals[index * 3 + 1] = faceNormaly;
  33675. normals[index * 3 + 2] = faceNormalz;
  33676. }
  33677. };
  33678. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  33679. var li = indices.length;
  33680. var ln = normals.length;
  33681. var i;
  33682. var n;
  33683. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33684. switch (sideOrientation) {
  33685. case BABYLON.Mesh.FRONTSIDE:
  33686. // nothing changed
  33687. break;
  33688. case BABYLON.Mesh.BACKSIDE:
  33689. var tmp;
  33690. // indices
  33691. for (i = 0; i < li; i += 3) {
  33692. tmp = indices[i];
  33693. indices[i] = indices[i + 2];
  33694. indices[i + 2] = tmp;
  33695. }
  33696. // normals
  33697. for (n = 0; n < ln; n++) {
  33698. normals[n] = -normals[n];
  33699. }
  33700. break;
  33701. case BABYLON.Mesh.DOUBLESIDE:
  33702. // positions
  33703. var lp = positions.length;
  33704. var l = lp / 3;
  33705. for (var p = 0; p < lp; p++) {
  33706. positions[lp + p] = positions[p];
  33707. }
  33708. // indices
  33709. for (i = 0; i < li; i += 3) {
  33710. indices[i + li] = indices[i + 2] + l;
  33711. indices[i + 1 + li] = indices[i + 1] + l;
  33712. indices[i + 2 + li] = indices[i] + l;
  33713. }
  33714. // normals
  33715. for (n = 0; n < ln; n++) {
  33716. normals[ln + n] = -normals[n];
  33717. }
  33718. // uvs
  33719. var lu = uvs.length;
  33720. for (var u = 0; u < lu; u++) {
  33721. uvs[u + lu] = uvs[u];
  33722. }
  33723. break;
  33724. }
  33725. };
  33726. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  33727. var vertexData = new VertexData();
  33728. // positions
  33729. var positions = parsedVertexData.positions;
  33730. if (positions) {
  33731. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  33732. }
  33733. // normals
  33734. var normals = parsedVertexData.normals;
  33735. if (normals) {
  33736. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  33737. }
  33738. // uvs
  33739. var uvs = parsedVertexData.uvs;
  33740. if (uvs) {
  33741. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  33742. }
  33743. // uv2s
  33744. var uv2s = parsedVertexData.uv2s;
  33745. if (uv2s) {
  33746. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  33747. }
  33748. // uv3s
  33749. var uv3s = parsedVertexData.uv3s;
  33750. if (uv3s) {
  33751. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  33752. }
  33753. // uv4s
  33754. var uv4s = parsedVertexData.uv4s;
  33755. if (uv4s) {
  33756. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  33757. }
  33758. // uv5s
  33759. var uv5s = parsedVertexData.uv5s;
  33760. if (uv5s) {
  33761. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  33762. }
  33763. // uv6s
  33764. var uv6s = parsedVertexData.uv6s;
  33765. if (uv6s) {
  33766. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  33767. }
  33768. // colors
  33769. var colors = parsedVertexData.colors;
  33770. if (colors) {
  33771. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  33772. }
  33773. // matricesIndices
  33774. var matricesIndices = parsedVertexData.matricesIndices;
  33775. if (matricesIndices) {
  33776. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  33777. }
  33778. // matricesWeights
  33779. var matricesWeights = parsedVertexData.matricesWeights;
  33780. if (matricesWeights) {
  33781. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  33782. }
  33783. // indices
  33784. var indices = parsedVertexData.indices;
  33785. if (indices) {
  33786. vertexData.indices = indices;
  33787. }
  33788. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  33789. };
  33790. return VertexData;
  33791. }());
  33792. BABYLON.VertexData = VertexData;
  33793. })(BABYLON || (BABYLON = {}));
  33794. //# sourceMappingURL=../Mesh/babylon.mesh.vertexData.js.map
  33795. var BABYLON;
  33796. (function (BABYLON) {
  33797. var Tags = (function () {
  33798. function Tags() {
  33799. }
  33800. Tags.EnableFor = function (obj) {
  33801. obj._tags = obj._tags || {};
  33802. obj.hasTags = function () {
  33803. return Tags.HasTags(obj);
  33804. };
  33805. obj.addTags = function (tagsString) {
  33806. return Tags.AddTagsTo(obj, tagsString);
  33807. };
  33808. obj.removeTags = function (tagsString) {
  33809. return Tags.RemoveTagsFrom(obj, tagsString);
  33810. };
  33811. obj.matchesTagsQuery = function (tagsQuery) {
  33812. return Tags.MatchesQuery(obj, tagsQuery);
  33813. };
  33814. };
  33815. Tags.DisableFor = function (obj) {
  33816. delete obj._tags;
  33817. delete obj.hasTags;
  33818. delete obj.addTags;
  33819. delete obj.removeTags;
  33820. delete obj.matchesTagsQuery;
  33821. };
  33822. Tags.HasTags = function (obj) {
  33823. if (!obj._tags) {
  33824. return false;
  33825. }
  33826. return !BABYLON.Tools.IsEmpty(obj._tags);
  33827. };
  33828. Tags.GetTags = function (obj, asString) {
  33829. if (asString === void 0) { asString = true; }
  33830. if (!obj._tags) {
  33831. return null;
  33832. }
  33833. if (asString) {
  33834. var tagsArray = [];
  33835. for (var tag in obj._tags) {
  33836. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  33837. tagsArray.push(tag);
  33838. }
  33839. }
  33840. return tagsArray.join(" ");
  33841. }
  33842. else {
  33843. return obj._tags;
  33844. }
  33845. };
  33846. // the tags 'true' and 'false' are reserved and cannot be used as tags
  33847. // a tag cannot start with '||', '&&', and '!'
  33848. // it cannot contain whitespaces
  33849. Tags.AddTagsTo = function (obj, tagsString) {
  33850. if (!tagsString) {
  33851. return;
  33852. }
  33853. if (typeof tagsString !== "string") {
  33854. return;
  33855. }
  33856. var tags = tagsString.split(" ");
  33857. tags.forEach(function (tag, index, array) {
  33858. Tags._AddTagTo(obj, tag);
  33859. });
  33860. };
  33861. Tags._AddTagTo = function (obj, tag) {
  33862. tag = tag.trim();
  33863. if (tag === "" || tag === "true" || tag === "false") {
  33864. return;
  33865. }
  33866. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  33867. return;
  33868. }
  33869. Tags.EnableFor(obj);
  33870. obj._tags[tag] = true;
  33871. };
  33872. Tags.RemoveTagsFrom = function (obj, tagsString) {
  33873. if (!Tags.HasTags(obj)) {
  33874. return;
  33875. }
  33876. var tags = tagsString.split(" ");
  33877. for (var t in tags) {
  33878. Tags._RemoveTagFrom(obj, tags[t]);
  33879. }
  33880. };
  33881. Tags._RemoveTagFrom = function (obj, tag) {
  33882. delete obj._tags[tag];
  33883. };
  33884. Tags.MatchesQuery = function (obj, tagsQuery) {
  33885. if (tagsQuery === undefined) {
  33886. return true;
  33887. }
  33888. if (tagsQuery === "") {
  33889. return Tags.HasTags(obj);
  33890. }
  33891. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  33892. };
  33893. return Tags;
  33894. }());
  33895. BABYLON.Tags = Tags;
  33896. })(BABYLON || (BABYLON = {}));
  33897. //# sourceMappingURL=../Tools/babylon.tags.js.map
  33898. var BABYLON;
  33899. (function (BABYLON) {
  33900. var Internals;
  33901. (function (Internals) {
  33902. var AndOrNotEvaluator = (function () {
  33903. function AndOrNotEvaluator() {
  33904. }
  33905. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  33906. if (!query.match(/\([^\(\)]*\)/g)) {
  33907. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  33908. }
  33909. else {
  33910. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  33911. // remove parenthesis
  33912. r = r.slice(1, r.length - 1);
  33913. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  33914. });
  33915. }
  33916. if (query === "true") {
  33917. return true;
  33918. }
  33919. if (query === "false") {
  33920. return false;
  33921. }
  33922. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  33923. };
  33924. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  33925. evaluateCallback = evaluateCallback || (function (r) {
  33926. return r === "true" ? true : false;
  33927. });
  33928. var result;
  33929. var or = parenthesisContent.split("||");
  33930. for (var i in or) {
  33931. if (or.hasOwnProperty(i)) {
  33932. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  33933. var and = ori.split("&&");
  33934. if (and.length > 1) {
  33935. for (var j = 0; j < and.length; ++j) {
  33936. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  33937. if (andj !== "true" && andj !== "false") {
  33938. if (andj[0] === "!") {
  33939. result = !evaluateCallback(andj.substring(1));
  33940. }
  33941. else {
  33942. result = evaluateCallback(andj);
  33943. }
  33944. }
  33945. else {
  33946. result = andj === "true" ? true : false;
  33947. }
  33948. if (!result) {
  33949. ori = "false";
  33950. break;
  33951. }
  33952. }
  33953. }
  33954. if (result || ori === "true") {
  33955. result = true;
  33956. break;
  33957. }
  33958. // result equals false (or undefined)
  33959. if (ori !== "true" && ori !== "false") {
  33960. if (ori[0] === "!") {
  33961. result = !evaluateCallback(ori.substring(1));
  33962. }
  33963. else {
  33964. result = evaluateCallback(ori);
  33965. }
  33966. }
  33967. else {
  33968. result = ori === "true" ? true : false;
  33969. }
  33970. }
  33971. }
  33972. // the whole parenthesis scope is replaced by 'true' or 'false'
  33973. return result ? "true" : "false";
  33974. };
  33975. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  33976. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  33977. // remove whitespaces
  33978. r = r.replace(/[\s]/g, function () { return ""; });
  33979. return r.length % 2 ? "!" : "";
  33980. });
  33981. booleanString = booleanString.trim();
  33982. if (booleanString === "!true") {
  33983. booleanString = "false";
  33984. }
  33985. else if (booleanString === "!false") {
  33986. booleanString = "true";
  33987. }
  33988. return booleanString;
  33989. };
  33990. return AndOrNotEvaluator;
  33991. }());
  33992. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  33993. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33994. })(BABYLON || (BABYLON = {}));
  33995. //# sourceMappingURL=../Tools/babylon.andOrNotEvaluator.js.map
  33996. var BABYLON;
  33997. (function (BABYLON) {
  33998. var PostProcessRenderPass = (function () {
  33999. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  34000. this._enabled = true;
  34001. this._refCount = 0;
  34002. this._name = name;
  34003. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  34004. this.setRenderList(renderList);
  34005. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  34006. this._renderTexture.onAfterRenderObservable.add(afterRender);
  34007. this._scene = scene;
  34008. this._renderList = renderList;
  34009. }
  34010. // private
  34011. PostProcessRenderPass.prototype._incRefCount = function () {
  34012. if (this._refCount === 0) {
  34013. this._scene.customRenderTargets.push(this._renderTexture);
  34014. }
  34015. return ++this._refCount;
  34016. };
  34017. PostProcessRenderPass.prototype._decRefCount = function () {
  34018. this._refCount--;
  34019. if (this._refCount <= 0) {
  34020. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  34021. }
  34022. return this._refCount;
  34023. };
  34024. PostProcessRenderPass.prototype._update = function () {
  34025. this.setRenderList(this._renderList);
  34026. };
  34027. // public
  34028. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  34029. this._renderTexture.renderList = renderList;
  34030. };
  34031. PostProcessRenderPass.prototype.getRenderTexture = function () {
  34032. return this._renderTexture;
  34033. };
  34034. return PostProcessRenderPass;
  34035. }());
  34036. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  34037. })(BABYLON || (BABYLON = {}));
  34038. //# sourceMappingURL=../../PostProcess/RenderPipeline/babylon.postProcessRenderPass.js.map
  34039. var BABYLON;
  34040. (function (BABYLON) {
  34041. var PostProcessRenderEffect = (function () {
  34042. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  34043. this._engine = engine;
  34044. this._name = name;
  34045. this._singleInstance = singleInstance || true;
  34046. this._getPostProcess = getPostProcess;
  34047. this._cameras = [];
  34048. this._indicesForCamera = [];
  34049. this._postProcesses = {};
  34050. this._renderPasses = {};
  34051. this._renderEffectAsPasses = {};
  34052. }
  34053. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  34054. get: function () {
  34055. for (var index in this._postProcesses) {
  34056. if (!this._postProcesses[index].isSupported) {
  34057. return false;
  34058. }
  34059. }
  34060. return true;
  34061. },
  34062. enumerable: true,
  34063. configurable: true
  34064. });
  34065. PostProcessRenderEffect.prototype._update = function () {
  34066. for (var renderPassName in this._renderPasses) {
  34067. this._renderPasses[renderPassName]._update();
  34068. }
  34069. };
  34070. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  34071. this._renderPasses[renderPass._name] = renderPass;
  34072. this._linkParameters();
  34073. };
  34074. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  34075. delete this._renderPasses[renderPass._name];
  34076. this._linkParameters();
  34077. };
  34078. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  34079. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  34080. this._linkParameters();
  34081. };
  34082. PostProcessRenderEffect.prototype.getPass = function (passName) {
  34083. for (var renderPassName in this._renderPasses) {
  34084. if (renderPassName === passName) {
  34085. return this._renderPasses[passName];
  34086. }
  34087. }
  34088. };
  34089. PostProcessRenderEffect.prototype.emptyPasses = function () {
  34090. this._renderPasses = {};
  34091. this._linkParameters();
  34092. };
  34093. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  34094. var cameraKey;
  34095. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34096. for (var i = 0; i < _cam.length; i++) {
  34097. var camera = _cam[i];
  34098. var cameraName = camera.name;
  34099. if (this._singleInstance) {
  34100. cameraKey = 0;
  34101. }
  34102. else {
  34103. cameraKey = cameraName;
  34104. }
  34105. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  34106. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  34107. if (!this._indicesForCamera[cameraName]) {
  34108. this._indicesForCamera[cameraName] = [];
  34109. }
  34110. this._indicesForCamera[cameraName].push(index);
  34111. if (this._cameras.indexOf(camera) === -1) {
  34112. this._cameras[cameraName] = camera;
  34113. }
  34114. for (var passName in this._renderPasses) {
  34115. this._renderPasses[passName]._incRefCount();
  34116. }
  34117. }
  34118. this._linkParameters();
  34119. };
  34120. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  34121. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34122. for (var i = 0; i < _cam.length; i++) {
  34123. var camera = _cam[i];
  34124. var cameraName = camera.name;
  34125. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  34126. var index = this._cameras.indexOf(cameraName);
  34127. this._indicesForCamera.splice(index, 1);
  34128. this._cameras.splice(index, 1);
  34129. for (var passName in this._renderPasses) {
  34130. this._renderPasses[passName]._decRefCount();
  34131. }
  34132. }
  34133. };
  34134. PostProcessRenderEffect.prototype._enable = function (cameras) {
  34135. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34136. for (var i = 0; i < _cam.length; i++) {
  34137. var camera = _cam[i];
  34138. var cameraName = camera.name;
  34139. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  34140. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  34141. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  34142. }
  34143. }
  34144. for (var passName in this._renderPasses) {
  34145. this._renderPasses[passName]._incRefCount();
  34146. }
  34147. }
  34148. };
  34149. PostProcessRenderEffect.prototype._disable = function (cameras) {
  34150. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34151. for (var i = 0; i < _cam.length; i++) {
  34152. var camera = _cam[i];
  34153. var cameraName = camera.Name;
  34154. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  34155. for (var passName in this._renderPasses) {
  34156. this._renderPasses[passName]._decRefCount();
  34157. }
  34158. }
  34159. };
  34160. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  34161. if (this._singleInstance) {
  34162. return this._postProcesses[0];
  34163. }
  34164. else {
  34165. return this._postProcesses[camera.name];
  34166. }
  34167. };
  34168. PostProcessRenderEffect.prototype._linkParameters = function () {
  34169. var _this = this;
  34170. for (var index in this._postProcesses) {
  34171. if (this.applyParameters) {
  34172. this.applyParameters(this._postProcesses[index]);
  34173. }
  34174. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  34175. _this._linkTextures(effect);
  34176. });
  34177. }
  34178. };
  34179. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  34180. for (var renderPassName in this._renderPasses) {
  34181. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  34182. }
  34183. for (var renderEffectName in this._renderEffectAsPasses) {
  34184. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  34185. }
  34186. };
  34187. return PostProcessRenderEffect;
  34188. }());
  34189. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  34190. })(BABYLON || (BABYLON = {}));
  34191. //# sourceMappingURL=../../PostProcess/RenderPipeline/babylon.postProcessRenderEffect.js.map
  34192. var BABYLON;
  34193. (function (BABYLON) {
  34194. var PostProcessRenderPipeline = (function () {
  34195. function PostProcessRenderPipeline(engine, name) {
  34196. this._engine = engine;
  34197. this._name = name;
  34198. this._renderEffects = {};
  34199. this._renderEffectsForIsolatedPass = {};
  34200. this._cameras = [];
  34201. }
  34202. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  34203. get: function () {
  34204. for (var renderEffectName in this._renderEffects) {
  34205. if (!this._renderEffects[renderEffectName].isSupported) {
  34206. return false;
  34207. }
  34208. }
  34209. return true;
  34210. },
  34211. enumerable: true,
  34212. configurable: true
  34213. });
  34214. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  34215. this._renderEffects[renderEffect._name] = renderEffect;
  34216. };
  34217. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  34218. var renderEffects = this._renderEffects[renderEffectName];
  34219. if (!renderEffects) {
  34220. return;
  34221. }
  34222. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  34223. };
  34224. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  34225. var renderEffects = this._renderEffects[renderEffectName];
  34226. if (!renderEffects) {
  34227. return;
  34228. }
  34229. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  34230. };
  34231. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  34232. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34233. var indicesToDelete = [];
  34234. var i;
  34235. for (i = 0; i < _cam.length; i++) {
  34236. var camera = _cam[i];
  34237. var cameraName = camera.name;
  34238. if (this._cameras.indexOf(camera) === -1) {
  34239. this._cameras[cameraName] = camera;
  34240. }
  34241. else if (unique) {
  34242. indicesToDelete.push(i);
  34243. }
  34244. }
  34245. for (i = 0; i < indicesToDelete.length; i++) {
  34246. cameras.splice(indicesToDelete[i], 1);
  34247. }
  34248. for (var renderEffectName in this._renderEffects) {
  34249. this._renderEffects[renderEffectName]._attachCameras(_cam);
  34250. }
  34251. };
  34252. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  34253. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34254. for (var renderEffectName in this._renderEffects) {
  34255. this._renderEffects[renderEffectName]._detachCameras(_cam);
  34256. }
  34257. for (var i = 0; i < _cam.length; i++) {
  34258. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  34259. }
  34260. };
  34261. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  34262. var _this = this;
  34263. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34264. var pass = null;
  34265. var renderEffectName;
  34266. for (renderEffectName in this._renderEffects) {
  34267. pass = this._renderEffects[renderEffectName].getPass(passName);
  34268. if (pass != null) {
  34269. break;
  34270. }
  34271. }
  34272. if (pass === null) {
  34273. return;
  34274. }
  34275. for (renderEffectName in this._renderEffects) {
  34276. this._renderEffects[renderEffectName]._disable(_cam);
  34277. }
  34278. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  34279. for (var i = 0; i < _cam.length; i++) {
  34280. var camera = _cam[i];
  34281. var cameraName = camera.name;
  34282. 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); });
  34283. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  34284. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  34285. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  34286. }
  34287. };
  34288. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  34289. var _this = this;
  34290. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34291. for (var i = 0; i < _cam.length; i++) {
  34292. var camera = _cam[i];
  34293. var cameraName = camera.name;
  34294. 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); });
  34295. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  34296. }
  34297. for (var renderEffectName in this._renderEffects) {
  34298. this._renderEffects[renderEffectName]._enable(_cam);
  34299. }
  34300. };
  34301. PostProcessRenderPipeline.prototype._update = function () {
  34302. for (var renderEffectName in this._renderEffects) {
  34303. this._renderEffects[renderEffectName]._update();
  34304. }
  34305. for (var i = 0; i < this._cameras.length; i++) {
  34306. var cameraName = this._cameras[i].name;
  34307. if (this._renderEffectsForIsolatedPass[cameraName]) {
  34308. this._renderEffectsForIsolatedPass[cameraName]._update();
  34309. }
  34310. }
  34311. };
  34312. PostProcessRenderPipeline.prototype.dispose = function () {
  34313. // Must be implemented by children
  34314. };
  34315. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  34316. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  34317. return PostProcessRenderPipeline;
  34318. }());
  34319. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  34320. })(BABYLON || (BABYLON = {}));
  34321. //# sourceMappingURL=../../PostProcess/RenderPipeline/babylon.postProcessRenderPipeline.js.map
  34322. var BABYLON;
  34323. (function (BABYLON) {
  34324. var PostProcessRenderPipelineManager = (function () {
  34325. function PostProcessRenderPipelineManager() {
  34326. this._renderPipelines = {};
  34327. }
  34328. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  34329. this._renderPipelines[renderPipeline._name] = renderPipeline;
  34330. };
  34331. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  34332. var renderPipeline = this._renderPipelines[renderPipelineName];
  34333. if (!renderPipeline) {
  34334. return;
  34335. }
  34336. renderPipeline._attachCameras(cameras, unique);
  34337. };
  34338. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  34339. var renderPipeline = this._renderPipelines[renderPipelineName];
  34340. if (!renderPipeline) {
  34341. return;
  34342. }
  34343. renderPipeline._detachCameras(cameras);
  34344. };
  34345. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  34346. var renderPipeline = this._renderPipelines[renderPipelineName];
  34347. if (!renderPipeline) {
  34348. return;
  34349. }
  34350. renderPipeline._enableEffect(renderEffectName, cameras);
  34351. };
  34352. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  34353. var renderPipeline = this._renderPipelines[renderPipelineName];
  34354. if (!renderPipeline) {
  34355. return;
  34356. }
  34357. renderPipeline._disableEffect(renderEffectName, cameras);
  34358. };
  34359. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  34360. var renderPipeline = this._renderPipelines[renderPipelineName];
  34361. if (!renderPipeline) {
  34362. return;
  34363. }
  34364. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  34365. };
  34366. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  34367. var renderPipeline = this._renderPipelines[renderPipelineName];
  34368. if (!renderPipeline) {
  34369. return;
  34370. }
  34371. renderPipeline._disableDisplayOnlyPass(cameras);
  34372. };
  34373. PostProcessRenderPipelineManager.prototype.update = function () {
  34374. for (var renderPipelineName in this._renderPipelines) {
  34375. var pipeline = this._renderPipelines[renderPipelineName];
  34376. if (!pipeline.isSupported) {
  34377. pipeline.dispose();
  34378. delete this._renderPipelines[renderPipelineName];
  34379. }
  34380. else {
  34381. pipeline._update();
  34382. }
  34383. }
  34384. };
  34385. return PostProcessRenderPipelineManager;
  34386. }());
  34387. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  34388. })(BABYLON || (BABYLON = {}));
  34389. //# sourceMappingURL=../../PostProcess/RenderPipeline/babylon.postProcessRenderPipelineManager.js.map
  34390. var BABYLON;
  34391. (function (BABYLON) {
  34392. var BoundingBoxRenderer = (function () {
  34393. function BoundingBoxRenderer(scene) {
  34394. this.frontColor = new BABYLON.Color3(1, 1, 1);
  34395. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  34396. this.showBackLines = true;
  34397. this.renderList = new BABYLON.SmartArray(32);
  34398. this._vertexBuffers = {};
  34399. this._scene = scene;
  34400. }
  34401. BoundingBoxRenderer.prototype._prepareRessources = function () {
  34402. if (this._colorShader) {
  34403. return;
  34404. }
  34405. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  34406. attributes: [BABYLON.VertexBuffer.PositionKind],
  34407. uniforms: ["worldViewProjection", "color"]
  34408. });
  34409. var engine = this._scene.getEngine();
  34410. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  34411. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  34412. 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]);
  34413. };
  34414. BoundingBoxRenderer.prototype.reset = function () {
  34415. this.renderList.reset();
  34416. };
  34417. BoundingBoxRenderer.prototype.render = function () {
  34418. if (this.renderList.length === 0) {
  34419. return;
  34420. }
  34421. this._prepareRessources();
  34422. if (!this._colorShader.isReady()) {
  34423. return;
  34424. }
  34425. var engine = this._scene.getEngine();
  34426. engine.setDepthWrite(false);
  34427. this._colorShader._preBind();
  34428. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  34429. var boundingBox = this.renderList.data[boundingBoxIndex];
  34430. var min = boundingBox.minimum;
  34431. var max = boundingBox.maximum;
  34432. var diff = max.subtract(min);
  34433. var median = min.add(diff.scale(0.5));
  34434. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  34435. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  34436. .multiply(boundingBox.getWorldMatrix());
  34437. // VBOs
  34438. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  34439. if (this.showBackLines) {
  34440. // Back
  34441. engine.setDepthFunctionToGreaterOrEqual();
  34442. this._scene.resetCachedMaterial();
  34443. this._colorShader.setColor4("color", this.backColor.toColor4());
  34444. this._colorShader.bind(worldMatrix);
  34445. // Draw order
  34446. engine.draw(false, 0, 24);
  34447. }
  34448. // Front
  34449. engine.setDepthFunctionToLess();
  34450. this._scene.resetCachedMaterial();
  34451. this._colorShader.setColor4("color", this.frontColor.toColor4());
  34452. this._colorShader.bind(worldMatrix);
  34453. // Draw order
  34454. engine.draw(false, 0, 24);
  34455. }
  34456. this._colorShader.unbind();
  34457. engine.setDepthFunctionToLessOrEqual();
  34458. engine.setDepthWrite(true);
  34459. };
  34460. BoundingBoxRenderer.prototype.dispose = function () {
  34461. if (!this._colorShader) {
  34462. return;
  34463. }
  34464. this._colorShader.dispose();
  34465. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34466. if (buffer) {
  34467. buffer.dispose();
  34468. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34469. }
  34470. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34471. };
  34472. return BoundingBoxRenderer;
  34473. }());
  34474. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  34475. })(BABYLON || (BABYLON = {}));
  34476. //# sourceMappingURL=../Rendering/babylon.boundingBoxRenderer.js.map
  34477. var BABYLON;
  34478. (function (BABYLON) {
  34479. var Condition = (function () {
  34480. function Condition(actionManager) {
  34481. this._actionManager = actionManager;
  34482. }
  34483. Condition.prototype.isValid = function () {
  34484. return true;
  34485. };
  34486. Condition.prototype._getProperty = function (propertyPath) {
  34487. return this._actionManager._getProperty(propertyPath);
  34488. };
  34489. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  34490. return this._actionManager._getEffectiveTarget(target, propertyPath);
  34491. };
  34492. Condition.prototype.serialize = function () {
  34493. };
  34494. Condition.prototype._serialize = function (serializedCondition) {
  34495. return {
  34496. type: 2,
  34497. children: [],
  34498. name: serializedCondition.name,
  34499. properties: serializedCondition.properties
  34500. };
  34501. };
  34502. return Condition;
  34503. }());
  34504. BABYLON.Condition = Condition;
  34505. var ValueCondition = (function (_super) {
  34506. __extends(ValueCondition, _super);
  34507. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  34508. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  34509. _super.call(this, actionManager);
  34510. this.propertyPath = propertyPath;
  34511. this.value = value;
  34512. this.operator = operator;
  34513. this._target = target;
  34514. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  34515. this._property = this._getProperty(this.propertyPath);
  34516. }
  34517. Object.defineProperty(ValueCondition, "IsEqual", {
  34518. get: function () {
  34519. return ValueCondition._IsEqual;
  34520. },
  34521. enumerable: true,
  34522. configurable: true
  34523. });
  34524. Object.defineProperty(ValueCondition, "IsDifferent", {
  34525. get: function () {
  34526. return ValueCondition._IsDifferent;
  34527. },
  34528. enumerable: true,
  34529. configurable: true
  34530. });
  34531. Object.defineProperty(ValueCondition, "IsGreater", {
  34532. get: function () {
  34533. return ValueCondition._IsGreater;
  34534. },
  34535. enumerable: true,
  34536. configurable: true
  34537. });
  34538. Object.defineProperty(ValueCondition, "IsLesser", {
  34539. get: function () {
  34540. return ValueCondition._IsLesser;
  34541. },
  34542. enumerable: true,
  34543. configurable: true
  34544. });
  34545. // Methods
  34546. ValueCondition.prototype.isValid = function () {
  34547. switch (this.operator) {
  34548. case ValueCondition.IsGreater:
  34549. return this._effectiveTarget[this._property] > this.value;
  34550. case ValueCondition.IsLesser:
  34551. return this._effectiveTarget[this._property] < this.value;
  34552. case ValueCondition.IsEqual:
  34553. case ValueCondition.IsDifferent:
  34554. var check;
  34555. if (this.value.equals) {
  34556. check = this.value.equals(this._effectiveTarget[this._property]);
  34557. }
  34558. else {
  34559. check = this.value === this._effectiveTarget[this._property];
  34560. }
  34561. return this.operator === ValueCondition.IsEqual ? check : !check;
  34562. }
  34563. return false;
  34564. };
  34565. ValueCondition.prototype.serialize = function () {
  34566. return this._serialize({
  34567. name: "ValueCondition",
  34568. properties: [
  34569. BABYLON.Action._GetTargetProperty(this._target),
  34570. { name: "propertyPath", value: this.propertyPath },
  34571. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34572. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  34573. ]
  34574. });
  34575. };
  34576. ValueCondition.GetOperatorName = function (operator) {
  34577. switch (operator) {
  34578. case ValueCondition._IsEqual: return "IsEqual";
  34579. case ValueCondition._IsDifferent: return "IsDifferent";
  34580. case ValueCondition._IsGreater: return "IsGreater";
  34581. case ValueCondition._IsLesser: return "IsLesser";
  34582. default: return "";
  34583. }
  34584. };
  34585. // Statics
  34586. ValueCondition._IsEqual = 0;
  34587. ValueCondition._IsDifferent = 1;
  34588. ValueCondition._IsGreater = 2;
  34589. ValueCondition._IsLesser = 3;
  34590. return ValueCondition;
  34591. }(Condition));
  34592. BABYLON.ValueCondition = ValueCondition;
  34593. var PredicateCondition = (function (_super) {
  34594. __extends(PredicateCondition, _super);
  34595. function PredicateCondition(actionManager, predicate) {
  34596. _super.call(this, actionManager);
  34597. this.predicate = predicate;
  34598. }
  34599. PredicateCondition.prototype.isValid = function () {
  34600. return this.predicate();
  34601. };
  34602. return PredicateCondition;
  34603. }(Condition));
  34604. BABYLON.PredicateCondition = PredicateCondition;
  34605. var StateCondition = (function (_super) {
  34606. __extends(StateCondition, _super);
  34607. function StateCondition(actionManager, target, value) {
  34608. _super.call(this, actionManager);
  34609. this.value = value;
  34610. this._target = target;
  34611. }
  34612. // Methods
  34613. StateCondition.prototype.isValid = function () {
  34614. return this._target.state === this.value;
  34615. };
  34616. StateCondition.prototype.serialize = function () {
  34617. return this._serialize({
  34618. name: "StateCondition",
  34619. properties: [
  34620. BABYLON.Action._GetTargetProperty(this._target),
  34621. { name: "value", value: this.value }
  34622. ]
  34623. });
  34624. };
  34625. return StateCondition;
  34626. }(Condition));
  34627. BABYLON.StateCondition = StateCondition;
  34628. })(BABYLON || (BABYLON = {}));
  34629. //# sourceMappingURL=../Actions/babylon.condition.js.map
  34630. var BABYLON;
  34631. (function (BABYLON) {
  34632. var Action = (function () {
  34633. function Action(triggerOptions, condition) {
  34634. this.triggerOptions = triggerOptions;
  34635. if (triggerOptions.parameter) {
  34636. this.trigger = triggerOptions.trigger;
  34637. this._triggerParameter = triggerOptions.parameter;
  34638. }
  34639. else {
  34640. this.trigger = triggerOptions;
  34641. }
  34642. this._nextActiveAction = this;
  34643. this._condition = condition;
  34644. }
  34645. // Methods
  34646. Action.prototype._prepare = function () {
  34647. };
  34648. Action.prototype.getTriggerParameter = function () {
  34649. return this._triggerParameter;
  34650. };
  34651. Action.prototype._executeCurrent = function (evt) {
  34652. if (this._nextActiveAction._condition) {
  34653. var condition = this._nextActiveAction._condition;
  34654. var currentRenderId = this._actionManager.getScene().getRenderId();
  34655. // We cache the current evaluation for the current frame
  34656. if (condition._evaluationId === currentRenderId) {
  34657. if (!condition._currentResult) {
  34658. return;
  34659. }
  34660. }
  34661. else {
  34662. condition._evaluationId = currentRenderId;
  34663. if (!condition.isValid()) {
  34664. condition._currentResult = false;
  34665. return;
  34666. }
  34667. condition._currentResult = true;
  34668. }
  34669. }
  34670. this._nextActiveAction.execute(evt);
  34671. this.skipToNextActiveAction();
  34672. };
  34673. Action.prototype.execute = function (evt) {
  34674. };
  34675. Action.prototype.skipToNextActiveAction = function () {
  34676. if (this._nextActiveAction._child) {
  34677. if (!this._nextActiveAction._child._actionManager) {
  34678. this._nextActiveAction._child._actionManager = this._actionManager;
  34679. }
  34680. this._nextActiveAction = this._nextActiveAction._child;
  34681. }
  34682. else {
  34683. this._nextActiveAction = this;
  34684. }
  34685. };
  34686. Action.prototype.then = function (action) {
  34687. this._child = action;
  34688. action._actionManager = this._actionManager;
  34689. action._prepare();
  34690. return action;
  34691. };
  34692. Action.prototype._getProperty = function (propertyPath) {
  34693. return this._actionManager._getProperty(propertyPath);
  34694. };
  34695. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  34696. return this._actionManager._getEffectiveTarget(target, propertyPath);
  34697. };
  34698. Action.prototype.serialize = function (parent) {
  34699. };
  34700. // Called by BABYLON.Action objects in serialize(...). Internal use
  34701. Action.prototype._serialize = function (serializedAction, parent) {
  34702. var serializationObject = {
  34703. type: 1,
  34704. children: [],
  34705. name: serializedAction.name,
  34706. properties: serializedAction.properties || []
  34707. };
  34708. // Serialize child
  34709. if (this._child) {
  34710. this._child.serialize(serializationObject);
  34711. }
  34712. // Check if "this" has a condition
  34713. if (this._condition) {
  34714. var serializedCondition = this._condition.serialize();
  34715. serializedCondition.children.push(serializationObject);
  34716. if (parent) {
  34717. parent.children.push(serializedCondition);
  34718. }
  34719. return serializedCondition;
  34720. }
  34721. if (parent) {
  34722. parent.children.push(serializationObject);
  34723. }
  34724. return serializationObject;
  34725. };
  34726. Action._SerializeValueAsString = function (value) {
  34727. if (typeof value === "number") {
  34728. return value.toString();
  34729. }
  34730. if (typeof value === "boolean") {
  34731. return value ? "true" : "false";
  34732. }
  34733. if (value instanceof BABYLON.Vector2) {
  34734. return value.x + ", " + value.y;
  34735. }
  34736. if (value instanceof BABYLON.Vector3) {
  34737. return value.x + ", " + value.y + ", " + value.z;
  34738. }
  34739. if (value instanceof BABYLON.Color3) {
  34740. return value.r + ", " + value.g + ", " + value.b;
  34741. }
  34742. if (value instanceof BABYLON.Color4) {
  34743. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  34744. }
  34745. return value; // string
  34746. };
  34747. Action._GetTargetProperty = function (target) {
  34748. return {
  34749. name: "target",
  34750. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  34751. : target instanceof BABYLON.Light ? "LightProperties"
  34752. : target instanceof BABYLON.Camera ? "CameraProperties"
  34753. : "SceneProperties",
  34754. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  34755. };
  34756. };
  34757. return Action;
  34758. }());
  34759. BABYLON.Action = Action;
  34760. })(BABYLON || (BABYLON = {}));
  34761. //# sourceMappingURL=../Actions/babylon.action.js.map
  34762. var BABYLON;
  34763. (function (BABYLON) {
  34764. /**
  34765. * ActionEvent is the event beint sent when an action is triggered.
  34766. */
  34767. var ActionEvent = (function () {
  34768. /**
  34769. * @constructor
  34770. * @param source The mesh or sprite that triggered the action.
  34771. * @param pointerX The X mouse cursor position at the time of the event
  34772. * @param pointerY The Y mouse cursor position at the time of the event
  34773. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  34774. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  34775. */
  34776. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  34777. this.source = source;
  34778. this.pointerX = pointerX;
  34779. this.pointerY = pointerY;
  34780. this.meshUnderPointer = meshUnderPointer;
  34781. this.sourceEvent = sourceEvent;
  34782. this.additionalData = additionalData;
  34783. }
  34784. /**
  34785. * Helper function to auto-create an ActionEvent from a source mesh.
  34786. * @param source The source mesh that triggered the event
  34787. * @param evt {Event} The original (browser) event
  34788. */
  34789. ActionEvent.CreateNew = function (source, evt, additionalData) {
  34790. var scene = source.getScene();
  34791. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  34792. };
  34793. /**
  34794. * Helper function to auto-create an ActionEvent from a source mesh.
  34795. * @param source The source sprite that triggered the event
  34796. * @param scene Scene associated with the sprite
  34797. * @param evt {Event} The original (browser) event
  34798. */
  34799. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  34800. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  34801. };
  34802. /**
  34803. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  34804. * @param scene the scene where the event occurred
  34805. * @param evt {Event} The original (browser) event
  34806. */
  34807. ActionEvent.CreateNewFromScene = function (scene, evt) {
  34808. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  34809. };
  34810. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  34811. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  34812. };
  34813. return ActionEvent;
  34814. }());
  34815. BABYLON.ActionEvent = ActionEvent;
  34816. /**
  34817. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  34818. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  34819. */
  34820. var ActionManager = (function () {
  34821. function ActionManager(scene) {
  34822. // Members
  34823. this.actions = new Array();
  34824. this.hoverCursor = '';
  34825. this._scene = scene;
  34826. scene._actionManagers.push(this);
  34827. }
  34828. Object.defineProperty(ActionManager, "NothingTrigger", {
  34829. get: function () {
  34830. return ActionManager._NothingTrigger;
  34831. },
  34832. enumerable: true,
  34833. configurable: true
  34834. });
  34835. Object.defineProperty(ActionManager, "OnPickTrigger", {
  34836. get: function () {
  34837. return ActionManager._OnPickTrigger;
  34838. },
  34839. enumerable: true,
  34840. configurable: true
  34841. });
  34842. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  34843. get: function () {
  34844. return ActionManager._OnLeftPickTrigger;
  34845. },
  34846. enumerable: true,
  34847. configurable: true
  34848. });
  34849. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  34850. get: function () {
  34851. return ActionManager._OnRightPickTrigger;
  34852. },
  34853. enumerable: true,
  34854. configurable: true
  34855. });
  34856. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  34857. get: function () {
  34858. return ActionManager._OnCenterPickTrigger;
  34859. },
  34860. enumerable: true,
  34861. configurable: true
  34862. });
  34863. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  34864. get: function () {
  34865. return ActionManager._OnPickDownTrigger;
  34866. },
  34867. enumerable: true,
  34868. configurable: true
  34869. });
  34870. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  34871. get: function () {
  34872. return ActionManager._OnPickUpTrigger;
  34873. },
  34874. enumerable: true,
  34875. configurable: true
  34876. });
  34877. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  34878. /// This trigger will only be raised if you also declared a OnPickDown
  34879. get: function () {
  34880. return ActionManager._OnPickOutTrigger;
  34881. },
  34882. enumerable: true,
  34883. configurable: true
  34884. });
  34885. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  34886. get: function () {
  34887. return ActionManager._OnLongPressTrigger;
  34888. },
  34889. enumerable: true,
  34890. configurable: true
  34891. });
  34892. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  34893. get: function () {
  34894. return ActionManager._OnPointerOverTrigger;
  34895. },
  34896. enumerable: true,
  34897. configurable: true
  34898. });
  34899. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  34900. get: function () {
  34901. return ActionManager._OnPointerOutTrigger;
  34902. },
  34903. enumerable: true,
  34904. configurable: true
  34905. });
  34906. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  34907. get: function () {
  34908. return ActionManager._OnEveryFrameTrigger;
  34909. },
  34910. enumerable: true,
  34911. configurable: true
  34912. });
  34913. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  34914. get: function () {
  34915. return ActionManager._OnIntersectionEnterTrigger;
  34916. },
  34917. enumerable: true,
  34918. configurable: true
  34919. });
  34920. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  34921. get: function () {
  34922. return ActionManager._OnIntersectionExitTrigger;
  34923. },
  34924. enumerable: true,
  34925. configurable: true
  34926. });
  34927. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  34928. get: function () {
  34929. return ActionManager._OnKeyDownTrigger;
  34930. },
  34931. enumerable: true,
  34932. configurable: true
  34933. });
  34934. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  34935. get: function () {
  34936. return ActionManager._OnKeyUpTrigger;
  34937. },
  34938. enumerable: true,
  34939. configurable: true
  34940. });
  34941. // Methods
  34942. ActionManager.prototype.dispose = function () {
  34943. var index = this._scene._actionManagers.indexOf(this);
  34944. if (index > -1) {
  34945. this._scene._actionManagers.splice(index, 1);
  34946. }
  34947. };
  34948. ActionManager.prototype.getScene = function () {
  34949. return this._scene;
  34950. };
  34951. /**
  34952. * Does this action manager handles actions of any of the given triggers
  34953. * @param {number[]} triggers - the triggers to be tested
  34954. * @return {boolean} whether one (or more) of the triggers is handeled
  34955. */
  34956. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  34957. for (var index = 0; index < this.actions.length; index++) {
  34958. var action = this.actions[index];
  34959. if (triggers.indexOf(action.trigger) > -1) {
  34960. return true;
  34961. }
  34962. }
  34963. return false;
  34964. };
  34965. /**
  34966. * Does this action manager handles actions of a given trigger
  34967. * @param {number} trigger - the trigger to be tested
  34968. * @return {boolean} whether the trigger is handeled
  34969. */
  34970. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  34971. for (var index = 0; index < this.actions.length; index++) {
  34972. var action = this.actions[index];
  34973. if (action.trigger === trigger) {
  34974. return true;
  34975. }
  34976. }
  34977. return false;
  34978. };
  34979. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  34980. /**
  34981. * Does this action manager has pointer triggers
  34982. * @return {boolean} whether or not it has pointer triggers
  34983. */
  34984. get: function () {
  34985. for (var index = 0; index < this.actions.length; index++) {
  34986. var action = this.actions[index];
  34987. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  34988. return true;
  34989. }
  34990. }
  34991. return false;
  34992. },
  34993. enumerable: true,
  34994. configurable: true
  34995. });
  34996. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  34997. /**
  34998. * Does this action manager has pick triggers
  34999. * @return {boolean} whether or not it has pick triggers
  35000. */
  35001. get: function () {
  35002. for (var index = 0; index < this.actions.length; index++) {
  35003. var action = this.actions[index];
  35004. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  35005. return true;
  35006. }
  35007. }
  35008. return false;
  35009. },
  35010. enumerable: true,
  35011. configurable: true
  35012. });
  35013. /**
  35014. * Registers an action to this action manager
  35015. * @param {BABYLON.Action} action - the action to be registered
  35016. * @return {BABYLON.Action} the action amended (prepared) after registration
  35017. */
  35018. ActionManager.prototype.registerAction = function (action) {
  35019. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  35020. if (this.getScene().actionManager !== this) {
  35021. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  35022. return null;
  35023. }
  35024. }
  35025. this.actions.push(action);
  35026. action._actionManager = this;
  35027. action._prepare();
  35028. return action;
  35029. };
  35030. /**
  35031. * Process a specific trigger
  35032. * @param {number} trigger - the trigger to process
  35033. * @param evt {BABYLON.ActionEvent} the event details to be processed
  35034. */
  35035. ActionManager.prototype.processTrigger = function (trigger, evt) {
  35036. for (var index = 0; index < this.actions.length; index++) {
  35037. var action = this.actions[index];
  35038. if (action.trigger === trigger) {
  35039. if (trigger === ActionManager.OnKeyUpTrigger
  35040. || trigger === ActionManager.OnKeyDownTrigger) {
  35041. var parameter = action.getTriggerParameter();
  35042. if (parameter) {
  35043. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  35044. var actualkey = String.fromCharCode(unicode).toLowerCase();
  35045. if (actualkey !== parameter.toLowerCase()) {
  35046. continue;
  35047. }
  35048. }
  35049. }
  35050. action._executeCurrent(evt);
  35051. }
  35052. }
  35053. };
  35054. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  35055. var properties = propertyPath.split(".");
  35056. for (var index = 0; index < properties.length - 1; index++) {
  35057. target = target[properties[index]];
  35058. }
  35059. return target;
  35060. };
  35061. ActionManager.prototype._getProperty = function (propertyPath) {
  35062. var properties = propertyPath.split(".");
  35063. return properties[properties.length - 1];
  35064. };
  35065. ActionManager.prototype.serialize = function (name) {
  35066. var root = {
  35067. children: [],
  35068. name: name,
  35069. type: 3,
  35070. properties: [] // Empty for root but required
  35071. };
  35072. for (var i = 0; i < this.actions.length; i++) {
  35073. var triggerObject = {
  35074. type: 0,
  35075. children: [],
  35076. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  35077. properties: []
  35078. };
  35079. var triggerOptions = this.actions[i].triggerOptions;
  35080. if (triggerOptions && typeof triggerOptions !== "number") {
  35081. if (triggerOptions.parameter instanceof BABYLON.Node) {
  35082. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  35083. }
  35084. else {
  35085. var parameter = {};
  35086. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  35087. if (triggerOptions.parameter.mesh) {
  35088. parameter._meshId = triggerOptions.parameter.mesh.id;
  35089. }
  35090. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  35091. }
  35092. }
  35093. // Serialize child action, recursively
  35094. this.actions[i].serialize(triggerObject);
  35095. // Add serialized trigger
  35096. root.children.push(triggerObject);
  35097. }
  35098. return root;
  35099. };
  35100. ActionManager.Parse = function (parsedActions, object, scene) {
  35101. var actionManager = new BABYLON.ActionManager(scene);
  35102. if (object === null)
  35103. scene.actionManager = actionManager;
  35104. else
  35105. object.actionManager = actionManager;
  35106. // instanciate a new object
  35107. var instanciate = function (name, params) {
  35108. var newInstance = Object.create(BABYLON[name].prototype);
  35109. newInstance.constructor.apply(newInstance, params);
  35110. return newInstance;
  35111. };
  35112. var parseParameter = function (name, value, target, propertyPath) {
  35113. if (propertyPath === null) {
  35114. // String, boolean or float
  35115. var floatValue = parseFloat(value);
  35116. if (value === "true" || value === "false")
  35117. return value === "true";
  35118. else
  35119. return isNaN(floatValue) ? value : floatValue;
  35120. }
  35121. var effectiveTarget = propertyPath.split(".");
  35122. var values = value.split(",");
  35123. // Get effective Target
  35124. for (var i = 0; i < effectiveTarget.length; i++) {
  35125. target = target[effectiveTarget[i]];
  35126. }
  35127. // Return appropriate value with its type
  35128. if (typeof (target) === "boolean")
  35129. return values[0] === "true";
  35130. if (typeof (target) === "string")
  35131. return values[0];
  35132. // Parameters with multiple values such as Vector3 etc.
  35133. var split = new Array();
  35134. for (var i = 0; i < values.length; i++)
  35135. split.push(parseFloat(values[i]));
  35136. if (target instanceof BABYLON.Vector3)
  35137. return BABYLON.Vector3.FromArray(split);
  35138. if (target instanceof BABYLON.Vector4)
  35139. return BABYLON.Vector4.FromArray(split);
  35140. if (target instanceof BABYLON.Color3)
  35141. return BABYLON.Color3.FromArray(split);
  35142. if (target instanceof BABYLON.Color4)
  35143. return BABYLON.Color4.FromArray(split);
  35144. return parseFloat(values[0]);
  35145. };
  35146. // traverse graph per trigger
  35147. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  35148. if (combineArray === void 0) { combineArray = null; }
  35149. if (parsedAction.detached)
  35150. return;
  35151. var parameters = new Array();
  35152. var target = null;
  35153. var propertyPath = null;
  35154. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  35155. // Parameters
  35156. if (parsedAction.type === 2)
  35157. parameters.push(actionManager);
  35158. else
  35159. parameters.push(trigger);
  35160. if (combine) {
  35161. var actions = new Array();
  35162. for (var j = 0; j < parsedAction.combine.length; j++) {
  35163. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  35164. }
  35165. parameters.push(actions);
  35166. }
  35167. else {
  35168. for (var i = 0; i < parsedAction.properties.length; i++) {
  35169. var value = parsedAction.properties[i].value;
  35170. var name = parsedAction.properties[i].name;
  35171. var targetType = parsedAction.properties[i].targetType;
  35172. if (name === "target")
  35173. if (targetType !== null && targetType === "SceneProperties")
  35174. value = target = scene;
  35175. else
  35176. value = target = scene.getNodeByName(value);
  35177. else if (name === "parent")
  35178. value = scene.getNodeByName(value);
  35179. else if (name === "sound")
  35180. value = scene.getSoundByName(value);
  35181. else if (name !== "propertyPath") {
  35182. if (parsedAction.type === 2 && name === "operator")
  35183. value = BABYLON.ValueCondition[value];
  35184. else
  35185. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  35186. }
  35187. else {
  35188. propertyPath = value;
  35189. }
  35190. parameters.push(value);
  35191. }
  35192. }
  35193. if (combineArray === null) {
  35194. parameters.push(condition);
  35195. }
  35196. else {
  35197. parameters.push(null);
  35198. }
  35199. // If interpolate value action
  35200. if (parsedAction.name === "InterpolateValueAction") {
  35201. var param = parameters[parameters.length - 2];
  35202. parameters[parameters.length - 1] = param;
  35203. parameters[parameters.length - 2] = condition;
  35204. }
  35205. // Action or condition(s) and not CombineAction
  35206. var newAction = instanciate(parsedAction.name, parameters);
  35207. if (newAction instanceof BABYLON.Condition && condition !== null) {
  35208. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  35209. if (action)
  35210. action.then(nothing);
  35211. else
  35212. actionManager.registerAction(nothing);
  35213. action = nothing;
  35214. }
  35215. if (combineArray === null) {
  35216. if (newAction instanceof BABYLON.Condition) {
  35217. condition = newAction;
  35218. newAction = action;
  35219. }
  35220. else {
  35221. condition = null;
  35222. if (action)
  35223. action.then(newAction);
  35224. else
  35225. actionManager.registerAction(newAction);
  35226. }
  35227. }
  35228. else {
  35229. combineArray.push(newAction);
  35230. }
  35231. for (var i = 0; i < parsedAction.children.length; i++)
  35232. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  35233. };
  35234. // triggers
  35235. for (var i = 0; i < parsedActions.children.length; i++) {
  35236. var triggerParams;
  35237. var trigger = parsedActions.children[i];
  35238. if (trigger.properties.length > 0) {
  35239. var param = trigger.properties[0].value;
  35240. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  35241. if (value._meshId) {
  35242. value.mesh = scene.getMeshByID(value._meshId);
  35243. }
  35244. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  35245. }
  35246. else
  35247. triggerParams = BABYLON.ActionManager[trigger.name];
  35248. for (var j = 0; j < trigger.children.length; j++) {
  35249. if (!trigger.detached)
  35250. traverse(trigger.children[j], triggerParams, null, null);
  35251. }
  35252. }
  35253. };
  35254. ActionManager.GetTriggerName = function (trigger) {
  35255. switch (trigger) {
  35256. case 0: return "NothingTrigger";
  35257. case 1: return "OnPickTrigger";
  35258. case 2: return "OnLeftPickTrigger";
  35259. case 3: return "OnRightPickTrigger";
  35260. case 4: return "OnCenterPickTrigger";
  35261. case 5: return "OnPickDownTrigger";
  35262. case 6: return "OnPickUpTrigger";
  35263. case 7: return "OnLongPressTrigger";
  35264. case 8: return "OnPointerOverTrigger";
  35265. case 9: return "OnPointerOutTrigger";
  35266. case 10: return "OnEveryFrameTrigger";
  35267. case 11: return "OnIntersectionEnterTrigger";
  35268. case 12: return "OnIntersectionExitTrigger";
  35269. case 13: return "OnKeyDownTrigger";
  35270. case 14: return "OnKeyUpTrigger";
  35271. case 15: return "OnPickOutTrigger";
  35272. default: return "";
  35273. }
  35274. };
  35275. // Statics
  35276. ActionManager._NothingTrigger = 0;
  35277. ActionManager._OnPickTrigger = 1;
  35278. ActionManager._OnLeftPickTrigger = 2;
  35279. ActionManager._OnRightPickTrigger = 3;
  35280. ActionManager._OnCenterPickTrigger = 4;
  35281. ActionManager._OnPickDownTrigger = 5;
  35282. ActionManager._OnPickUpTrigger = 6;
  35283. ActionManager._OnLongPressTrigger = 7;
  35284. ActionManager._OnPointerOverTrigger = 8;
  35285. ActionManager._OnPointerOutTrigger = 9;
  35286. ActionManager._OnEveryFrameTrigger = 10;
  35287. ActionManager._OnIntersectionEnterTrigger = 11;
  35288. ActionManager._OnIntersectionExitTrigger = 12;
  35289. ActionManager._OnKeyDownTrigger = 13;
  35290. ActionManager._OnKeyUpTrigger = 14;
  35291. ActionManager._OnPickOutTrigger = 15;
  35292. ActionManager.DragMovementThreshold = 10; // in pixels
  35293. ActionManager.LongPressDelay = 500; // in milliseconds
  35294. return ActionManager;
  35295. }());
  35296. BABYLON.ActionManager = ActionManager;
  35297. })(BABYLON || (BABYLON = {}));
  35298. //# sourceMappingURL=../Actions/babylon.actionManager.js.map
  35299. var BABYLON;
  35300. (function (BABYLON) {
  35301. var InterpolateValueAction = (function (_super) {
  35302. __extends(InterpolateValueAction, _super);
  35303. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  35304. if (duration === void 0) { duration = 1000; }
  35305. _super.call(this, triggerOptions, condition);
  35306. this.propertyPath = propertyPath;
  35307. this.value = value;
  35308. this.duration = duration;
  35309. this.stopOtherAnimations = stopOtherAnimations;
  35310. this.onInterpolationDone = onInterpolationDone;
  35311. this._target = this._effectiveTarget = target;
  35312. }
  35313. InterpolateValueAction.prototype._prepare = function () {
  35314. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35315. this._property = this._getProperty(this.propertyPath);
  35316. };
  35317. InterpolateValueAction.prototype.execute = function () {
  35318. var scene = this._actionManager.getScene();
  35319. var keys = [
  35320. {
  35321. frame: 0,
  35322. value: this._effectiveTarget[this._property]
  35323. }, {
  35324. frame: 100,
  35325. value: this.value
  35326. }
  35327. ];
  35328. var dataType;
  35329. if (typeof this.value === "number") {
  35330. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  35331. }
  35332. else if (this.value instanceof BABYLON.Color3) {
  35333. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  35334. }
  35335. else if (this.value instanceof BABYLON.Vector3) {
  35336. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  35337. }
  35338. else if (this.value instanceof BABYLON.Matrix) {
  35339. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  35340. }
  35341. else if (this.value instanceof BABYLON.Quaternion) {
  35342. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  35343. }
  35344. else {
  35345. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  35346. return;
  35347. }
  35348. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  35349. animation.setKeys(keys);
  35350. if (this.stopOtherAnimations) {
  35351. scene.stopAnimation(this._effectiveTarget);
  35352. }
  35353. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  35354. };
  35355. InterpolateValueAction.prototype.serialize = function (parent) {
  35356. return _super.prototype._serialize.call(this, {
  35357. name: "InterpolateValueAction",
  35358. properties: [
  35359. BABYLON.Action._GetTargetProperty(this._target),
  35360. { name: "propertyPath", value: this.propertyPath },
  35361. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35362. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  35363. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  35364. ]
  35365. }, parent);
  35366. };
  35367. return InterpolateValueAction;
  35368. }(BABYLON.Action));
  35369. BABYLON.InterpolateValueAction = InterpolateValueAction;
  35370. })(BABYLON || (BABYLON = {}));
  35371. //# sourceMappingURL=../Actions/babylon.interpolateValueAction.js.map
  35372. var BABYLON;
  35373. (function (BABYLON) {
  35374. var SwitchBooleanAction = (function (_super) {
  35375. __extends(SwitchBooleanAction, _super);
  35376. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  35377. _super.call(this, triggerOptions, condition);
  35378. this.propertyPath = propertyPath;
  35379. this._target = this._effectiveTarget = target;
  35380. }
  35381. SwitchBooleanAction.prototype._prepare = function () {
  35382. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35383. this._property = this._getProperty(this.propertyPath);
  35384. };
  35385. SwitchBooleanAction.prototype.execute = function () {
  35386. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  35387. };
  35388. SwitchBooleanAction.prototype.serialize = function (parent) {
  35389. return _super.prototype._serialize.call(this, {
  35390. name: "SwitchBooleanAction",
  35391. properties: [
  35392. BABYLON.Action._GetTargetProperty(this._target),
  35393. { name: "propertyPath", value: this.propertyPath }
  35394. ]
  35395. }, parent);
  35396. };
  35397. return SwitchBooleanAction;
  35398. }(BABYLON.Action));
  35399. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  35400. var SetStateAction = (function (_super) {
  35401. __extends(SetStateAction, _super);
  35402. function SetStateAction(triggerOptions, target, value, condition) {
  35403. _super.call(this, triggerOptions, condition);
  35404. this.value = value;
  35405. this._target = target;
  35406. }
  35407. SetStateAction.prototype.execute = function () {
  35408. this._target.state = this.value;
  35409. };
  35410. SetStateAction.prototype.serialize = function (parent) {
  35411. return _super.prototype._serialize.call(this, {
  35412. name: "SetStateAction",
  35413. properties: [
  35414. BABYLON.Action._GetTargetProperty(this._target),
  35415. { name: "value", value: this.value }
  35416. ]
  35417. }, parent);
  35418. };
  35419. return SetStateAction;
  35420. }(BABYLON.Action));
  35421. BABYLON.SetStateAction = SetStateAction;
  35422. var SetValueAction = (function (_super) {
  35423. __extends(SetValueAction, _super);
  35424. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  35425. _super.call(this, triggerOptions, condition);
  35426. this.propertyPath = propertyPath;
  35427. this.value = value;
  35428. this._target = this._effectiveTarget = target;
  35429. }
  35430. SetValueAction.prototype._prepare = function () {
  35431. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35432. this._property = this._getProperty(this.propertyPath);
  35433. };
  35434. SetValueAction.prototype.execute = function () {
  35435. this._effectiveTarget[this._property] = this.value;
  35436. if (this._target.markAsDirty) {
  35437. this._target.markAsDirty(this._property);
  35438. }
  35439. };
  35440. SetValueAction.prototype.serialize = function (parent) {
  35441. return _super.prototype._serialize.call(this, {
  35442. name: "SetValueAction",
  35443. properties: [
  35444. BABYLON.Action._GetTargetProperty(this._target),
  35445. { name: "propertyPath", value: this.propertyPath },
  35446. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35447. ]
  35448. }, parent);
  35449. };
  35450. return SetValueAction;
  35451. }(BABYLON.Action));
  35452. BABYLON.SetValueAction = SetValueAction;
  35453. var IncrementValueAction = (function (_super) {
  35454. __extends(IncrementValueAction, _super);
  35455. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  35456. _super.call(this, triggerOptions, condition);
  35457. this.propertyPath = propertyPath;
  35458. this.value = value;
  35459. this._target = this._effectiveTarget = target;
  35460. }
  35461. IncrementValueAction.prototype._prepare = function () {
  35462. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35463. this._property = this._getProperty(this.propertyPath);
  35464. if (typeof this._effectiveTarget[this._property] !== "number") {
  35465. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  35466. }
  35467. };
  35468. IncrementValueAction.prototype.execute = function () {
  35469. this._effectiveTarget[this._property] += this.value;
  35470. if (this._target.markAsDirty) {
  35471. this._target.markAsDirty(this._property);
  35472. }
  35473. };
  35474. IncrementValueAction.prototype.serialize = function (parent) {
  35475. return _super.prototype._serialize.call(this, {
  35476. name: "IncrementValueAction",
  35477. properties: [
  35478. BABYLON.Action._GetTargetProperty(this._target),
  35479. { name: "propertyPath", value: this.propertyPath },
  35480. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35481. ]
  35482. }, parent);
  35483. };
  35484. return IncrementValueAction;
  35485. }(BABYLON.Action));
  35486. BABYLON.IncrementValueAction = IncrementValueAction;
  35487. var PlayAnimationAction = (function (_super) {
  35488. __extends(PlayAnimationAction, _super);
  35489. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  35490. _super.call(this, triggerOptions, condition);
  35491. this.from = from;
  35492. this.to = to;
  35493. this.loop = loop;
  35494. this._target = target;
  35495. }
  35496. PlayAnimationAction.prototype._prepare = function () {
  35497. };
  35498. PlayAnimationAction.prototype.execute = function () {
  35499. var scene = this._actionManager.getScene();
  35500. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  35501. };
  35502. PlayAnimationAction.prototype.serialize = function (parent) {
  35503. return _super.prototype._serialize.call(this, {
  35504. name: "PlayAnimationAction",
  35505. properties: [
  35506. BABYLON.Action._GetTargetProperty(this._target),
  35507. { name: "from", value: String(this.from) },
  35508. { name: "to", value: String(this.to) },
  35509. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  35510. ]
  35511. }, parent);
  35512. };
  35513. return PlayAnimationAction;
  35514. }(BABYLON.Action));
  35515. BABYLON.PlayAnimationAction = PlayAnimationAction;
  35516. var StopAnimationAction = (function (_super) {
  35517. __extends(StopAnimationAction, _super);
  35518. function StopAnimationAction(triggerOptions, target, condition) {
  35519. _super.call(this, triggerOptions, condition);
  35520. this._target = target;
  35521. }
  35522. StopAnimationAction.prototype._prepare = function () {
  35523. };
  35524. StopAnimationAction.prototype.execute = function () {
  35525. var scene = this._actionManager.getScene();
  35526. scene.stopAnimation(this._target);
  35527. };
  35528. StopAnimationAction.prototype.serialize = function (parent) {
  35529. return _super.prototype._serialize.call(this, {
  35530. name: "StopAnimationAction",
  35531. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  35532. }, parent);
  35533. };
  35534. return StopAnimationAction;
  35535. }(BABYLON.Action));
  35536. BABYLON.StopAnimationAction = StopAnimationAction;
  35537. var DoNothingAction = (function (_super) {
  35538. __extends(DoNothingAction, _super);
  35539. function DoNothingAction(triggerOptions, condition) {
  35540. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  35541. _super.call(this, triggerOptions, condition);
  35542. }
  35543. DoNothingAction.prototype.execute = function () {
  35544. };
  35545. DoNothingAction.prototype.serialize = function (parent) {
  35546. return _super.prototype._serialize.call(this, {
  35547. name: "DoNothingAction",
  35548. properties: []
  35549. }, parent);
  35550. };
  35551. return DoNothingAction;
  35552. }(BABYLON.Action));
  35553. BABYLON.DoNothingAction = DoNothingAction;
  35554. var CombineAction = (function (_super) {
  35555. __extends(CombineAction, _super);
  35556. function CombineAction(triggerOptions, children, condition) {
  35557. _super.call(this, triggerOptions, condition);
  35558. this.children = children;
  35559. }
  35560. CombineAction.prototype._prepare = function () {
  35561. for (var index = 0; index < this.children.length; index++) {
  35562. this.children[index]._actionManager = this._actionManager;
  35563. this.children[index]._prepare();
  35564. }
  35565. };
  35566. CombineAction.prototype.execute = function (evt) {
  35567. for (var index = 0; index < this.children.length; index++) {
  35568. this.children[index].execute(evt);
  35569. }
  35570. };
  35571. CombineAction.prototype.serialize = function (parent) {
  35572. var serializationObject = _super.prototype._serialize.call(this, {
  35573. name: "CombineAction",
  35574. properties: [],
  35575. combine: []
  35576. }, parent);
  35577. for (var i = 0; i < this.children.length; i++) {
  35578. serializationObject.combine.push(this.children[i].serialize(null));
  35579. }
  35580. return serializationObject;
  35581. };
  35582. return CombineAction;
  35583. }(BABYLON.Action));
  35584. BABYLON.CombineAction = CombineAction;
  35585. var ExecuteCodeAction = (function (_super) {
  35586. __extends(ExecuteCodeAction, _super);
  35587. function ExecuteCodeAction(triggerOptions, func, condition) {
  35588. _super.call(this, triggerOptions, condition);
  35589. this.func = func;
  35590. }
  35591. ExecuteCodeAction.prototype.execute = function (evt) {
  35592. this.func(evt);
  35593. };
  35594. return ExecuteCodeAction;
  35595. }(BABYLON.Action));
  35596. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  35597. var SetParentAction = (function (_super) {
  35598. __extends(SetParentAction, _super);
  35599. function SetParentAction(triggerOptions, target, parent, condition) {
  35600. _super.call(this, triggerOptions, condition);
  35601. this._target = target;
  35602. this._parent = parent;
  35603. }
  35604. SetParentAction.prototype._prepare = function () {
  35605. };
  35606. SetParentAction.prototype.execute = function () {
  35607. if (this._target.parent === this._parent) {
  35608. return;
  35609. }
  35610. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  35611. invertParentWorldMatrix.invert();
  35612. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  35613. this._target.parent = this._parent;
  35614. };
  35615. SetParentAction.prototype.serialize = function (parent) {
  35616. return _super.prototype._serialize.call(this, {
  35617. name: "SetParentAction",
  35618. properties: [
  35619. BABYLON.Action._GetTargetProperty(this._target),
  35620. BABYLON.Action._GetTargetProperty(this._parent),
  35621. ]
  35622. }, parent);
  35623. };
  35624. return SetParentAction;
  35625. }(BABYLON.Action));
  35626. BABYLON.SetParentAction = SetParentAction;
  35627. var PlaySoundAction = (function (_super) {
  35628. __extends(PlaySoundAction, _super);
  35629. function PlaySoundAction(triggerOptions, sound, condition) {
  35630. _super.call(this, triggerOptions, condition);
  35631. this._sound = sound;
  35632. }
  35633. PlaySoundAction.prototype._prepare = function () {
  35634. };
  35635. PlaySoundAction.prototype.execute = function () {
  35636. if (this._sound !== undefined)
  35637. this._sound.play();
  35638. };
  35639. PlaySoundAction.prototype.serialize = function (parent) {
  35640. return _super.prototype._serialize.call(this, {
  35641. name: "PlaySoundAction",
  35642. properties: [{ name: "sound", value: this._sound.name }]
  35643. }, parent);
  35644. };
  35645. return PlaySoundAction;
  35646. }(BABYLON.Action));
  35647. BABYLON.PlaySoundAction = PlaySoundAction;
  35648. var StopSoundAction = (function (_super) {
  35649. __extends(StopSoundAction, _super);
  35650. function StopSoundAction(triggerOptions, sound, condition) {
  35651. _super.call(this, triggerOptions, condition);
  35652. this._sound = sound;
  35653. }
  35654. StopSoundAction.prototype._prepare = function () {
  35655. };
  35656. StopSoundAction.prototype.execute = function () {
  35657. if (this._sound !== undefined)
  35658. this._sound.stop();
  35659. };
  35660. StopSoundAction.prototype.serialize = function (parent) {
  35661. return _super.prototype._serialize.call(this, {
  35662. name: "StopSoundAction",
  35663. properties: [{ name: "sound", value: this._sound.name }]
  35664. }, parent);
  35665. };
  35666. return StopSoundAction;
  35667. }(BABYLON.Action));
  35668. BABYLON.StopSoundAction = StopSoundAction;
  35669. })(BABYLON || (BABYLON = {}));
  35670. //# sourceMappingURL=../Actions/babylon.directActions.js.map
  35671. var BABYLON;
  35672. (function (BABYLON) {
  35673. var Geometry = (function () {
  35674. function Geometry(id, scene, vertexData, updatable, mesh) {
  35675. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35676. this._totalVertices = 0;
  35677. this._isDisposed = false;
  35678. this.id = id;
  35679. this._engine = scene.getEngine();
  35680. this._meshes = [];
  35681. this._scene = scene;
  35682. //Init vertex buffer cache
  35683. this._vertexBuffers = {};
  35684. this._indices = [];
  35685. // vertexData
  35686. if (vertexData) {
  35687. this.setAllVerticesData(vertexData, updatable);
  35688. }
  35689. else {
  35690. this._totalVertices = 0;
  35691. this._indices = [];
  35692. }
  35693. // applyToMesh
  35694. if (mesh) {
  35695. if (mesh instanceof BABYLON.LinesMesh) {
  35696. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35697. this.updateExtend();
  35698. }
  35699. this.applyToMesh(mesh);
  35700. mesh.computeWorldMatrix(true);
  35701. }
  35702. }
  35703. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35704. /**
  35705. * 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
  35706. * @returns The Bias Vector
  35707. */
  35708. get: function () {
  35709. return this._boundingBias;
  35710. },
  35711. set: function (value) {
  35712. if (this._boundingBias && this._boundingBias.equals(value)) {
  35713. return;
  35714. }
  35715. this._boundingBias = value.clone();
  35716. this.updateBoundingInfo(true, null);
  35717. },
  35718. enumerable: true,
  35719. configurable: true
  35720. });
  35721. Object.defineProperty(Geometry.prototype, "extend", {
  35722. get: function () {
  35723. return this._extend;
  35724. },
  35725. enumerable: true,
  35726. configurable: true
  35727. });
  35728. Geometry.prototype.getScene = function () {
  35729. return this._scene;
  35730. };
  35731. Geometry.prototype.getEngine = function () {
  35732. return this._engine;
  35733. };
  35734. Geometry.prototype.isReady = function () {
  35735. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35736. };
  35737. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35738. get: function () {
  35739. for (var index = 0; index < this._meshes.length; index++) {
  35740. if (!this._meshes[index].doNotSerialize) {
  35741. return false;
  35742. }
  35743. }
  35744. return true;
  35745. },
  35746. enumerable: true,
  35747. configurable: true
  35748. });
  35749. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35750. vertexData.applyToGeometry(this, updatable);
  35751. this.notifyUpdate();
  35752. };
  35753. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35754. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35755. this.setVerticesBuffer(buffer);
  35756. };
  35757. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35758. var kind = buffer.getKind();
  35759. if (this._vertexBuffers[kind]) {
  35760. this._vertexBuffers[kind].dispose();
  35761. }
  35762. this._vertexBuffers[kind] = buffer;
  35763. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35764. var data = buffer.getData();
  35765. var stride = buffer.getStrideSize();
  35766. this._totalVertices = data.length / stride;
  35767. this.updateExtend(data, stride);
  35768. var meshes = this._meshes;
  35769. var numOfMeshes = meshes.length;
  35770. for (var index = 0; index < numOfMeshes; index++) {
  35771. var mesh = meshes[index];
  35772. mesh._resetPointsArrayCache();
  35773. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35774. mesh._createGlobalSubMesh();
  35775. mesh.computeWorldMatrix(true);
  35776. }
  35777. }
  35778. this.notifyUpdate(kind);
  35779. };
  35780. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35781. var vertexBuffer = this.getVertexBuffer(kind);
  35782. if (!vertexBuffer) {
  35783. return;
  35784. }
  35785. vertexBuffer.updateDirectly(data, offset);
  35786. this.notifyUpdate(kind);
  35787. };
  35788. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35789. var vertexBuffer = this.getVertexBuffer(kind);
  35790. if (!vertexBuffer) {
  35791. return;
  35792. }
  35793. vertexBuffer.update(data);
  35794. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35795. var stride = vertexBuffer.getStrideSize();
  35796. this._totalVertices = data.length / stride;
  35797. this.updateBoundingInfo(updateExtends, data);
  35798. }
  35799. this.notifyUpdate(kind);
  35800. };
  35801. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35802. if (updateExtends) {
  35803. this.updateExtend(data);
  35804. }
  35805. var meshes = this._meshes;
  35806. var numOfMeshes = meshes.length;
  35807. for (var index = 0; index < numOfMeshes; index++) {
  35808. var mesh = meshes[index];
  35809. mesh._resetPointsArrayCache();
  35810. if (updateExtends) {
  35811. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35812. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35813. var subMesh = mesh.subMeshes[subIndex];
  35814. subMesh.refreshBoundingInfo();
  35815. }
  35816. }
  35817. }
  35818. };
  35819. Geometry.prototype.getTotalVertices = function () {
  35820. if (!this.isReady()) {
  35821. return 0;
  35822. }
  35823. return this._totalVertices;
  35824. };
  35825. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  35826. var vertexBuffer = this.getVertexBuffer(kind);
  35827. if (!vertexBuffer) {
  35828. return null;
  35829. }
  35830. var orig = vertexBuffer.getData();
  35831. if (!copyWhenShared || this._meshes.length === 1) {
  35832. return orig;
  35833. }
  35834. else {
  35835. var len = orig.length;
  35836. var copy = [];
  35837. for (var i = 0; i < len; i++) {
  35838. copy.push(orig[i]);
  35839. }
  35840. return copy;
  35841. }
  35842. };
  35843. Geometry.prototype.getVertexBuffer = function (kind) {
  35844. if (!this.isReady()) {
  35845. return null;
  35846. }
  35847. return this._vertexBuffers[kind];
  35848. };
  35849. Geometry.prototype.getVertexBuffers = function () {
  35850. if (!this.isReady()) {
  35851. return null;
  35852. }
  35853. return this._vertexBuffers;
  35854. };
  35855. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35856. if (!this._vertexBuffers) {
  35857. if (this._delayInfo) {
  35858. return this._delayInfo.indexOf(kind) !== -1;
  35859. }
  35860. return false;
  35861. }
  35862. return this._vertexBuffers[kind] !== undefined;
  35863. };
  35864. Geometry.prototype.getVerticesDataKinds = function () {
  35865. var result = [];
  35866. var kind;
  35867. if (!this._vertexBuffers && this._delayInfo) {
  35868. for (kind in this._delayInfo) {
  35869. result.push(kind);
  35870. }
  35871. }
  35872. else {
  35873. for (kind in this._vertexBuffers) {
  35874. result.push(kind);
  35875. }
  35876. }
  35877. return result;
  35878. };
  35879. Geometry.prototype.setIndices = function (indices, totalVertices) {
  35880. if (this._indexBuffer) {
  35881. this._engine._releaseBuffer(this._indexBuffer);
  35882. }
  35883. this._indices = indices;
  35884. if (this._meshes.length !== 0 && this._indices) {
  35885. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35886. }
  35887. if (totalVertices !== undefined) {
  35888. this._totalVertices = totalVertices;
  35889. }
  35890. var meshes = this._meshes;
  35891. var numOfMeshes = meshes.length;
  35892. for (var index = 0; index < numOfMeshes; index++) {
  35893. meshes[index]._createGlobalSubMesh();
  35894. }
  35895. this.notifyUpdate();
  35896. };
  35897. Geometry.prototype.getTotalIndices = function () {
  35898. if (!this.isReady()) {
  35899. return 0;
  35900. }
  35901. return this._indices.length;
  35902. };
  35903. Geometry.prototype.getIndices = function (copyWhenShared) {
  35904. if (!this.isReady()) {
  35905. return null;
  35906. }
  35907. var orig = this._indices;
  35908. if (!copyWhenShared || this._meshes.length === 1) {
  35909. return orig;
  35910. }
  35911. else {
  35912. var len = orig.length;
  35913. var copy = [];
  35914. for (var i = 0; i < len; i++) {
  35915. copy.push(orig[i]);
  35916. }
  35917. return copy;
  35918. }
  35919. };
  35920. Geometry.prototype.getIndexBuffer = function () {
  35921. if (!this.isReady()) {
  35922. return null;
  35923. }
  35924. return this._indexBuffer;
  35925. };
  35926. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35927. var meshes = this._meshes;
  35928. var index = meshes.indexOf(mesh);
  35929. if (index === -1) {
  35930. return;
  35931. }
  35932. for (var kind in this._vertexBuffers) {
  35933. this._vertexBuffers[kind].dispose();
  35934. }
  35935. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  35936. this._indexBuffer = null;
  35937. }
  35938. meshes.splice(index, 1);
  35939. mesh._geometry = null;
  35940. if (meshes.length === 0 && shouldDispose) {
  35941. this.dispose();
  35942. }
  35943. };
  35944. Geometry.prototype.applyToMesh = function (mesh) {
  35945. if (mesh._geometry === this) {
  35946. return;
  35947. }
  35948. var previousGeometry = mesh._geometry;
  35949. if (previousGeometry) {
  35950. previousGeometry.releaseForMesh(mesh);
  35951. }
  35952. var meshes = this._meshes;
  35953. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35954. mesh._geometry = this;
  35955. this._scene.pushGeometry(this);
  35956. meshes.push(mesh);
  35957. if (this.isReady()) {
  35958. this._applyToMesh(mesh);
  35959. }
  35960. else {
  35961. mesh._boundingInfo = this._boundingInfo;
  35962. }
  35963. };
  35964. Geometry.prototype.updateExtend = function (data, stride) {
  35965. if (data === void 0) { data = null; }
  35966. if (!data) {
  35967. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35968. }
  35969. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35970. };
  35971. Geometry.prototype._applyToMesh = function (mesh) {
  35972. var numOfMeshes = this._meshes.length;
  35973. // vertexBuffers
  35974. for (var kind in this._vertexBuffers) {
  35975. if (numOfMeshes === 1) {
  35976. this._vertexBuffers[kind].create();
  35977. }
  35978. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  35979. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35980. mesh._resetPointsArrayCache();
  35981. if (!this._extend) {
  35982. this.updateExtend(this._vertexBuffers[kind].getData());
  35983. }
  35984. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35985. mesh._createGlobalSubMesh();
  35986. //bounding info was just created again, world matrix should be applied again.
  35987. mesh._updateBoundingInfo();
  35988. }
  35989. }
  35990. // indexBuffer
  35991. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35992. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35993. }
  35994. if (this._indexBuffer) {
  35995. this._indexBuffer.references = numOfMeshes;
  35996. }
  35997. };
  35998. Geometry.prototype.notifyUpdate = function (kind) {
  35999. if (this.onGeometryUpdated) {
  36000. this.onGeometryUpdated(this, kind);
  36001. }
  36002. };
  36003. Geometry.prototype.load = function (scene, onLoaded) {
  36004. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  36005. return;
  36006. }
  36007. if (this.isReady()) {
  36008. if (onLoaded) {
  36009. onLoaded();
  36010. }
  36011. return;
  36012. }
  36013. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  36014. this._queueLoad(scene, onLoaded);
  36015. };
  36016. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  36017. var _this = this;
  36018. scene._addPendingData(this);
  36019. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  36020. _this._delayLoadingFunction(JSON.parse(data), _this);
  36021. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36022. _this._delayInfo = [];
  36023. scene._removePendingData(_this);
  36024. var meshes = _this._meshes;
  36025. var numOfMeshes = meshes.length;
  36026. for (var index = 0; index < numOfMeshes; index++) {
  36027. _this._applyToMesh(meshes[index]);
  36028. }
  36029. if (onLoaded) {
  36030. onLoaded();
  36031. }
  36032. }, function () { }, scene.database);
  36033. };
  36034. /**
  36035. * Invert the geometry to move from a right handed system to a left handed one.
  36036. */
  36037. Geometry.prototype.toLeftHanded = function () {
  36038. // Flip faces
  36039. var tIndices = this.getIndices(false);
  36040. if (tIndices != null && tIndices.length > 0) {
  36041. for (var i = 0; i < tIndices.length; i += 3) {
  36042. var tTemp = tIndices[i + 0];
  36043. tIndices[i + 0] = tIndices[i + 2];
  36044. tIndices[i + 2] = tTemp;
  36045. }
  36046. this.setIndices(tIndices);
  36047. }
  36048. // Negate position.z
  36049. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  36050. if (tPositions != null && tPositions.length > 0) {
  36051. for (var i = 0; i < tPositions.length; i += 3) {
  36052. tPositions[i + 2] = -tPositions[i + 2];
  36053. }
  36054. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  36055. }
  36056. // Negate normal.z
  36057. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  36058. if (tNormals != null && tNormals.length > 0) {
  36059. for (var i = 0; i < tNormals.length; i += 3) {
  36060. tNormals[i + 2] = -tNormals[i + 2];
  36061. }
  36062. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  36063. }
  36064. };
  36065. Geometry.prototype.isDisposed = function () {
  36066. return this._isDisposed;
  36067. };
  36068. Geometry.prototype.dispose = function () {
  36069. var meshes = this._meshes;
  36070. var numOfMeshes = meshes.length;
  36071. var index;
  36072. for (index = 0; index < numOfMeshes; index++) {
  36073. this.releaseForMesh(meshes[index]);
  36074. }
  36075. this._meshes = [];
  36076. for (var kind in this._vertexBuffers) {
  36077. this._vertexBuffers[kind].dispose();
  36078. }
  36079. this._vertexBuffers = {};
  36080. this._totalVertices = 0;
  36081. if (this._indexBuffer) {
  36082. this._engine._releaseBuffer(this._indexBuffer);
  36083. }
  36084. this._indexBuffer = null;
  36085. this._indices = [];
  36086. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36087. this.delayLoadingFile = null;
  36088. this._delayLoadingFunction = null;
  36089. this._delayInfo = [];
  36090. this._boundingInfo = null;
  36091. this._scene.removeGeometry(this);
  36092. this._isDisposed = true;
  36093. };
  36094. Geometry.prototype.copy = function (id) {
  36095. var vertexData = new BABYLON.VertexData();
  36096. vertexData.indices = [];
  36097. var indices = this.getIndices();
  36098. for (var index = 0; index < indices.length; index++) {
  36099. vertexData.indices.push(indices[index]);
  36100. }
  36101. var updatable = false;
  36102. var stopChecking = false;
  36103. var kind;
  36104. for (kind in this._vertexBuffers) {
  36105. // using slice() to make a copy of the array and not just reference it
  36106. var data = this.getVerticesData(kind);
  36107. if (data instanceof Float32Array) {
  36108. vertexData.set(new Float32Array(data), kind);
  36109. }
  36110. else {
  36111. vertexData.set(data.slice(0), kind);
  36112. }
  36113. if (!stopChecking) {
  36114. updatable = this.getVertexBuffer(kind).isUpdatable();
  36115. stopChecking = !updatable;
  36116. }
  36117. }
  36118. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  36119. geometry.delayLoadState = this.delayLoadState;
  36120. geometry.delayLoadingFile = this.delayLoadingFile;
  36121. geometry._delayLoadingFunction = this._delayLoadingFunction;
  36122. for (kind in this._delayInfo) {
  36123. geometry._delayInfo = geometry._delayInfo || [];
  36124. geometry._delayInfo.push(kind);
  36125. }
  36126. // Bounding info
  36127. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36128. return geometry;
  36129. };
  36130. Geometry.prototype.serialize = function () {
  36131. var serializationObject = {};
  36132. serializationObject.id = this.id;
  36133. if (BABYLON.Tags.HasTags(this)) {
  36134. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36135. }
  36136. return serializationObject;
  36137. };
  36138. Geometry.prototype.serializeVerticeData = function () {
  36139. var serializationObject = this.serialize();
  36140. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36141. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36142. }
  36143. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36144. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36145. }
  36146. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36147. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36148. }
  36149. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36150. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  36151. }
  36152. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36153. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  36154. }
  36155. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36156. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  36157. }
  36158. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36159. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  36160. }
  36161. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36162. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  36163. }
  36164. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36165. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36166. }
  36167. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36168. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36169. serializationObject.matricesIndices._isExpanded = true;
  36170. }
  36171. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36172. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  36173. }
  36174. serializationObject.indices = this.getIndices();
  36175. return serializationObject;
  36176. };
  36177. // Statics
  36178. Geometry.ExtractFromMesh = function (mesh, id) {
  36179. var geometry = mesh._geometry;
  36180. if (!geometry) {
  36181. return null;
  36182. }
  36183. return geometry.copy(id);
  36184. };
  36185. /**
  36186. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36187. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36188. * Be aware Math.random() could cause collisions, but:
  36189. * "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"
  36190. */
  36191. Geometry.RandomId = function () {
  36192. return BABYLON.Tools.RandomId();
  36193. };
  36194. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  36195. var scene = mesh.getScene();
  36196. // Geometry
  36197. var geometryId = parsedGeometry.geometryId;
  36198. if (geometryId) {
  36199. var geometry = scene.getGeometryByID(geometryId);
  36200. if (geometry) {
  36201. geometry.applyToMesh(mesh);
  36202. }
  36203. }
  36204. else if (parsedGeometry instanceof ArrayBuffer) {
  36205. var binaryInfo = mesh._binaryInfo;
  36206. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36207. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36208. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36209. }
  36210. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36211. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36212. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36213. }
  36214. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36215. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36216. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36217. }
  36218. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36219. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36220. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36221. }
  36222. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36223. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36224. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36225. }
  36226. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36227. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36228. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36229. }
  36230. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36231. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36232. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36233. }
  36234. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36235. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36236. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36237. }
  36238. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36239. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36240. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36241. }
  36242. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36243. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36244. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36245. }
  36246. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36247. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36248. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36249. }
  36250. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36251. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36252. mesh.setIndices(indicesData);
  36253. }
  36254. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36255. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36256. mesh.subMeshes = [];
  36257. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36258. var materialIndex = subMeshesData[(i * 5) + 0];
  36259. var verticesStart = subMeshesData[(i * 5) + 1];
  36260. var verticesCount = subMeshesData[(i * 5) + 2];
  36261. var indexStart = subMeshesData[(i * 5) + 3];
  36262. var indexCount = subMeshesData[(i * 5) + 4];
  36263. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36264. }
  36265. }
  36266. }
  36267. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36268. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  36269. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  36270. if (parsedGeometry.uvs) {
  36271. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  36272. }
  36273. if (parsedGeometry.uvs2) {
  36274. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  36275. }
  36276. if (parsedGeometry.uvs3) {
  36277. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  36278. }
  36279. if (parsedGeometry.uvs4) {
  36280. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  36281. }
  36282. if (parsedGeometry.uvs5) {
  36283. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  36284. }
  36285. if (parsedGeometry.uvs6) {
  36286. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  36287. }
  36288. if (parsedGeometry.colors) {
  36289. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  36290. }
  36291. if (parsedGeometry.matricesIndices) {
  36292. if (!parsedGeometry.matricesIndices._isExpanded) {
  36293. var floatIndices = [];
  36294. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36295. var matricesIndex = parsedGeometry.matricesIndices[i];
  36296. floatIndices.push(matricesIndex & 0x000000FF);
  36297. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36298. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36299. floatIndices.push(matricesIndex >> 24);
  36300. }
  36301. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  36302. }
  36303. else {
  36304. delete parsedGeometry.matricesIndices._isExpanded;
  36305. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  36306. }
  36307. }
  36308. if (parsedGeometry.matricesIndicesExtra) {
  36309. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36310. var floatIndices = [];
  36311. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36312. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36313. floatIndices.push(matricesIndex & 0x000000FF);
  36314. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36315. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36316. floatIndices.push(matricesIndex >> 24);
  36317. }
  36318. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  36319. }
  36320. else {
  36321. delete parsedGeometry.matricesIndices._isExpanded;
  36322. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  36323. }
  36324. }
  36325. if (parsedGeometry.matricesWeights) {
  36326. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  36327. }
  36328. if (parsedGeometry.matricesWeightsExtra) {
  36329. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  36330. }
  36331. mesh.setIndices(parsedGeometry.indices);
  36332. }
  36333. // SubMeshes
  36334. if (parsedGeometry.subMeshes) {
  36335. mesh.subMeshes = [];
  36336. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36337. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36338. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36339. }
  36340. }
  36341. // Flat shading
  36342. if (mesh._shouldGenerateFlatShading) {
  36343. mesh.convertToFlatShadedMesh();
  36344. delete mesh._shouldGenerateFlatShading;
  36345. }
  36346. // Update
  36347. mesh.computeWorldMatrix(true);
  36348. // Octree
  36349. if (scene['_selectionOctree']) {
  36350. scene['_selectionOctree'].addMesh(mesh);
  36351. }
  36352. };
  36353. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36354. if (scene.getGeometryByID(parsedVertexData.id)) {
  36355. return null; // null since geometry could be something else than a box...
  36356. }
  36357. var geometry = new Geometry(parsedVertexData.id, scene);
  36358. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36359. if (parsedVertexData.delayLoadingFile) {
  36360. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36361. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36362. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36363. geometry._delayInfo = [];
  36364. if (parsedVertexData.hasUVs) {
  36365. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36366. }
  36367. if (parsedVertexData.hasUVs2) {
  36368. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36369. }
  36370. if (parsedVertexData.hasUVs3) {
  36371. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36372. }
  36373. if (parsedVertexData.hasUVs4) {
  36374. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36375. }
  36376. if (parsedVertexData.hasUVs5) {
  36377. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36378. }
  36379. if (parsedVertexData.hasUVs6) {
  36380. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36381. }
  36382. if (parsedVertexData.hasColors) {
  36383. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36384. }
  36385. if (parsedVertexData.hasMatricesIndices) {
  36386. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36387. }
  36388. if (parsedVertexData.hasMatricesWeights) {
  36389. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36390. }
  36391. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36392. }
  36393. else {
  36394. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36395. }
  36396. scene.pushGeometry(geometry, true);
  36397. return geometry;
  36398. };
  36399. return Geometry;
  36400. }());
  36401. BABYLON.Geometry = Geometry;
  36402. /////// Primitives //////////////////////////////////////////////
  36403. var Geometry;
  36404. (function (Geometry) {
  36405. var Primitives;
  36406. (function (Primitives) {
  36407. /// Abstract class
  36408. var _Primitive = (function (_super) {
  36409. __extends(_Primitive, _super);
  36410. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  36411. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  36412. this._canBeRegenerated = _canBeRegenerated;
  36413. this._beingRegenerated = true;
  36414. this.regenerate();
  36415. this._beingRegenerated = false;
  36416. }
  36417. _Primitive.prototype.canBeRegenerated = function () {
  36418. return this._canBeRegenerated;
  36419. };
  36420. _Primitive.prototype.regenerate = function () {
  36421. if (!this._canBeRegenerated) {
  36422. return;
  36423. }
  36424. this._beingRegenerated = true;
  36425. this.setAllVerticesData(this._regenerateVertexData(), false);
  36426. this._beingRegenerated = false;
  36427. };
  36428. _Primitive.prototype.asNewGeometry = function (id) {
  36429. return _super.prototype.copy.call(this, id);
  36430. };
  36431. // overrides
  36432. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  36433. if (!this._beingRegenerated) {
  36434. return;
  36435. }
  36436. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36437. };
  36438. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  36439. if (!this._beingRegenerated) {
  36440. return;
  36441. }
  36442. _super.prototype.setVerticesData.call(this, kind, data, false);
  36443. };
  36444. // to override
  36445. // protected
  36446. _Primitive.prototype._regenerateVertexData = function () {
  36447. throw new Error("Abstract method");
  36448. };
  36449. _Primitive.prototype.copy = function (id) {
  36450. throw new Error("Must be overriden in sub-classes.");
  36451. };
  36452. _Primitive.prototype.serialize = function () {
  36453. var serializationObject = _super.prototype.serialize.call(this);
  36454. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36455. return serializationObject;
  36456. };
  36457. return _Primitive;
  36458. }(Geometry));
  36459. Primitives._Primitive = _Primitive;
  36460. var Ribbon = (function (_super) {
  36461. __extends(Ribbon, _super);
  36462. // Members
  36463. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  36464. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36465. _super.call(this, id, scene, canBeRegenerated, mesh);
  36466. this.pathArray = pathArray;
  36467. this.closeArray = closeArray;
  36468. this.closePath = closePath;
  36469. this.offset = offset;
  36470. this.side = side;
  36471. }
  36472. Ribbon.prototype._regenerateVertexData = function () {
  36473. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36474. };
  36475. Ribbon.prototype.copy = function (id) {
  36476. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  36477. };
  36478. return Ribbon;
  36479. }(_Primitive));
  36480. Primitives.Ribbon = Ribbon;
  36481. var Box = (function (_super) {
  36482. __extends(Box, _super);
  36483. // Members
  36484. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  36485. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36486. _super.call(this, id, scene, canBeRegenerated, mesh);
  36487. this.size = size;
  36488. this.side = side;
  36489. }
  36490. Box.prototype._regenerateVertexData = function () {
  36491. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36492. };
  36493. Box.prototype.copy = function (id) {
  36494. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36495. };
  36496. Box.prototype.serialize = function () {
  36497. var serializationObject = _super.prototype.serialize.call(this);
  36498. serializationObject.size = this.size;
  36499. return serializationObject;
  36500. };
  36501. Box.Parse = function (parsedBox, scene) {
  36502. if (scene.getGeometryByID(parsedBox.id)) {
  36503. return null; // null since geometry could be something else than a box...
  36504. }
  36505. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36506. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36507. scene.pushGeometry(box, true);
  36508. return box;
  36509. };
  36510. return Box;
  36511. }(_Primitive));
  36512. Primitives.Box = Box;
  36513. var Sphere = (function (_super) {
  36514. __extends(Sphere, _super);
  36515. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  36516. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36517. _super.call(this, id, scene, canBeRegenerated, mesh);
  36518. this.segments = segments;
  36519. this.diameter = diameter;
  36520. this.side = side;
  36521. }
  36522. Sphere.prototype._regenerateVertexData = function () {
  36523. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36524. };
  36525. Sphere.prototype.copy = function (id) {
  36526. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36527. };
  36528. Sphere.prototype.serialize = function () {
  36529. var serializationObject = _super.prototype.serialize.call(this);
  36530. serializationObject.segments = this.segments;
  36531. serializationObject.diameter = this.diameter;
  36532. return serializationObject;
  36533. };
  36534. Sphere.Parse = function (parsedSphere, scene) {
  36535. if (scene.getGeometryByID(parsedSphere.id)) {
  36536. return null; // null since geometry could be something else than a sphere...
  36537. }
  36538. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36539. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36540. scene.pushGeometry(sphere, true);
  36541. return sphere;
  36542. };
  36543. return Sphere;
  36544. }(_Primitive));
  36545. Primitives.Sphere = Sphere;
  36546. var Disc = (function (_super) {
  36547. __extends(Disc, _super);
  36548. // Members
  36549. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  36550. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36551. _super.call(this, id, scene, canBeRegenerated, mesh);
  36552. this.radius = radius;
  36553. this.tessellation = tessellation;
  36554. this.side = side;
  36555. }
  36556. Disc.prototype._regenerateVertexData = function () {
  36557. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36558. };
  36559. Disc.prototype.copy = function (id) {
  36560. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36561. };
  36562. return Disc;
  36563. }(_Primitive));
  36564. Primitives.Disc = Disc;
  36565. var Cylinder = (function (_super) {
  36566. __extends(Cylinder, _super);
  36567. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  36568. if (subdivisions === void 0) { subdivisions = 1; }
  36569. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36570. _super.call(this, id, scene, canBeRegenerated, mesh);
  36571. this.height = height;
  36572. this.diameterTop = diameterTop;
  36573. this.diameterBottom = diameterBottom;
  36574. this.tessellation = tessellation;
  36575. this.subdivisions = subdivisions;
  36576. this.side = side;
  36577. }
  36578. Cylinder.prototype._regenerateVertexData = function () {
  36579. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36580. };
  36581. Cylinder.prototype.copy = function (id) {
  36582. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36583. };
  36584. Cylinder.prototype.serialize = function () {
  36585. var serializationObject = _super.prototype.serialize.call(this);
  36586. serializationObject.height = this.height;
  36587. serializationObject.diameterTop = this.diameterTop;
  36588. serializationObject.diameterBottom = this.diameterBottom;
  36589. serializationObject.tessellation = this.tessellation;
  36590. return serializationObject;
  36591. };
  36592. Cylinder.Parse = function (parsedCylinder, scene) {
  36593. if (scene.getGeometryByID(parsedCylinder.id)) {
  36594. return null; // null since geometry could be something else than a cylinder...
  36595. }
  36596. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36597. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36598. scene.pushGeometry(cylinder, true);
  36599. return cylinder;
  36600. };
  36601. return Cylinder;
  36602. }(_Primitive));
  36603. Primitives.Cylinder = Cylinder;
  36604. var Torus = (function (_super) {
  36605. __extends(Torus, _super);
  36606. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  36607. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36608. _super.call(this, id, scene, canBeRegenerated, mesh);
  36609. this.diameter = diameter;
  36610. this.thickness = thickness;
  36611. this.tessellation = tessellation;
  36612. this.side = side;
  36613. }
  36614. Torus.prototype._regenerateVertexData = function () {
  36615. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36616. };
  36617. Torus.prototype.copy = function (id) {
  36618. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36619. };
  36620. Torus.prototype.serialize = function () {
  36621. var serializationObject = _super.prototype.serialize.call(this);
  36622. serializationObject.diameter = this.diameter;
  36623. serializationObject.thickness = this.thickness;
  36624. serializationObject.tessellation = this.tessellation;
  36625. return serializationObject;
  36626. };
  36627. Torus.Parse = function (parsedTorus, scene) {
  36628. if (scene.getGeometryByID(parsedTorus.id)) {
  36629. return null; // null since geometry could be something else than a torus...
  36630. }
  36631. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36632. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36633. scene.pushGeometry(torus, true);
  36634. return torus;
  36635. };
  36636. return Torus;
  36637. }(_Primitive));
  36638. Primitives.Torus = Torus;
  36639. var Ground = (function (_super) {
  36640. __extends(Ground, _super);
  36641. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  36642. _super.call(this, id, scene, canBeRegenerated, mesh);
  36643. this.width = width;
  36644. this.height = height;
  36645. this.subdivisions = subdivisions;
  36646. }
  36647. Ground.prototype._regenerateVertexData = function () {
  36648. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36649. };
  36650. Ground.prototype.copy = function (id) {
  36651. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36652. };
  36653. Ground.prototype.serialize = function () {
  36654. var serializationObject = _super.prototype.serialize.call(this);
  36655. serializationObject.width = this.width;
  36656. serializationObject.height = this.height;
  36657. serializationObject.subdivisions = this.subdivisions;
  36658. return serializationObject;
  36659. };
  36660. Ground.Parse = function (parsedGround, scene) {
  36661. if (scene.getGeometryByID(parsedGround.id)) {
  36662. return null; // null since geometry could be something else than a ground...
  36663. }
  36664. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36665. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36666. scene.pushGeometry(ground, true);
  36667. return ground;
  36668. };
  36669. return Ground;
  36670. }(_Primitive));
  36671. Primitives.Ground = Ground;
  36672. var TiledGround = (function (_super) {
  36673. __extends(TiledGround, _super);
  36674. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  36675. _super.call(this, id, scene, canBeRegenerated, mesh);
  36676. this.xmin = xmin;
  36677. this.zmin = zmin;
  36678. this.xmax = xmax;
  36679. this.zmax = zmax;
  36680. this.subdivisions = subdivisions;
  36681. this.precision = precision;
  36682. }
  36683. TiledGround.prototype._regenerateVertexData = function () {
  36684. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36685. };
  36686. TiledGround.prototype.copy = function (id) {
  36687. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36688. };
  36689. return TiledGround;
  36690. }(_Primitive));
  36691. Primitives.TiledGround = TiledGround;
  36692. var Plane = (function (_super) {
  36693. __extends(Plane, _super);
  36694. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  36695. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36696. _super.call(this, id, scene, canBeRegenerated, mesh);
  36697. this.size = size;
  36698. this.side = side;
  36699. }
  36700. Plane.prototype._regenerateVertexData = function () {
  36701. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36702. };
  36703. Plane.prototype.copy = function (id) {
  36704. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36705. };
  36706. Plane.prototype.serialize = function () {
  36707. var serializationObject = _super.prototype.serialize.call(this);
  36708. serializationObject.size = this.size;
  36709. return serializationObject;
  36710. };
  36711. Plane.Parse = function (parsedPlane, scene) {
  36712. if (scene.getGeometryByID(parsedPlane.id)) {
  36713. return null; // null since geometry could be something else than a ground...
  36714. }
  36715. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36716. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36717. scene.pushGeometry(plane, true);
  36718. return plane;
  36719. };
  36720. return Plane;
  36721. }(_Primitive));
  36722. Primitives.Plane = Plane;
  36723. var TorusKnot = (function (_super) {
  36724. __extends(TorusKnot, _super);
  36725. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  36726. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36727. _super.call(this, id, scene, canBeRegenerated, mesh);
  36728. this.radius = radius;
  36729. this.tube = tube;
  36730. this.radialSegments = radialSegments;
  36731. this.tubularSegments = tubularSegments;
  36732. this.p = p;
  36733. this.q = q;
  36734. this.side = side;
  36735. }
  36736. TorusKnot.prototype._regenerateVertexData = function () {
  36737. 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 });
  36738. };
  36739. TorusKnot.prototype.copy = function (id) {
  36740. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36741. };
  36742. TorusKnot.prototype.serialize = function () {
  36743. var serializationObject = _super.prototype.serialize.call(this);
  36744. serializationObject.radius = this.radius;
  36745. serializationObject.tube = this.tube;
  36746. serializationObject.radialSegments = this.radialSegments;
  36747. serializationObject.tubularSegments = this.tubularSegments;
  36748. serializationObject.p = this.p;
  36749. serializationObject.q = this.q;
  36750. return serializationObject;
  36751. };
  36752. ;
  36753. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  36754. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36755. return null; // null since geometry could be something else than a ground...
  36756. }
  36757. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36758. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36759. scene.pushGeometry(torusKnot, true);
  36760. return torusKnot;
  36761. };
  36762. return TorusKnot;
  36763. }(_Primitive));
  36764. Primitives.TorusKnot = TorusKnot;
  36765. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  36766. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  36767. })(BABYLON || (BABYLON = {}));
  36768. //# sourceMappingURL=../Mesh/babylon.geometry.js.map
  36769. var BABYLON;
  36770. (function (BABYLON) {
  36771. var GroundMesh = (function (_super) {
  36772. __extends(GroundMesh, _super);
  36773. function GroundMesh(name, scene) {
  36774. _super.call(this, name, scene);
  36775. this.generateOctree = false;
  36776. this._worldInverse = new BABYLON.Matrix();
  36777. }
  36778. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  36779. get: function () {
  36780. return Math.min(this._subdivisionsX, this._subdivisionsY);
  36781. },
  36782. enumerable: true,
  36783. configurable: true
  36784. });
  36785. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  36786. get: function () {
  36787. return this._subdivisionsX;
  36788. },
  36789. enumerable: true,
  36790. configurable: true
  36791. });
  36792. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  36793. get: function () {
  36794. return this._subdivisionsY;
  36795. },
  36796. enumerable: true,
  36797. configurable: true
  36798. });
  36799. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  36800. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  36801. this._subdivisionsX = chunksCount;
  36802. this._subdivisionsY = chunksCount;
  36803. this.subdivide(chunksCount);
  36804. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  36805. };
  36806. /**
  36807. * Returns a height (y) value in the Worl system :
  36808. * the ground altitude at the coordinates (x, z) expressed in the World system.
  36809. * Returns the ground y position if (x, z) are outside the ground surface.
  36810. * Not pertinent if the ground is rotated.
  36811. */
  36812. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  36813. // express x and y in the ground local system
  36814. x -= this.position.x;
  36815. z -= this.position.z;
  36816. x /= this.scaling.x;
  36817. z /= this.scaling.z;
  36818. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  36819. return this.position.y;
  36820. }
  36821. if (!this._heightQuads || this._heightQuads.length == 0) {
  36822. this._initHeightQuads();
  36823. this._computeHeightQuads();
  36824. }
  36825. var facet = this._getFacetAt(x, z);
  36826. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  36827. // return y in the World system
  36828. return y * this.scaling.y + this.position.y;
  36829. };
  36830. /**
  36831. * Returns a normalized vector (Vector3) orthogonal to the ground
  36832. * at the ground coordinates (x, z) expressed in the World system.
  36833. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  36834. * Not pertinent if the ground is rotated.
  36835. */
  36836. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  36837. var normal = new BABYLON.Vector3(0, 1, 0);
  36838. this.getNormalAtCoordinatesToRef(x, z, normal);
  36839. return normal;
  36840. };
  36841. /**
  36842. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  36843. * at the ground coordinates (x, z) expressed in the World system.
  36844. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  36845. * Not pertinent if the ground is rotated.
  36846. */
  36847. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  36848. // express x and y in the ground local system
  36849. x -= this.position.x;
  36850. z -= this.position.z;
  36851. x /= this.scaling.x;
  36852. z /= this.scaling.z;
  36853. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  36854. return;
  36855. }
  36856. if (!this._heightQuads || this._heightQuads.length == 0) {
  36857. this._initHeightQuads();
  36858. this._computeHeightQuads();
  36859. }
  36860. var facet = this._getFacetAt(x, z);
  36861. ref.x = facet.x;
  36862. ref.y = facet.y;
  36863. ref.z = facet.z;
  36864. };
  36865. /**
  36866. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  36867. * if the ground has been updated.
  36868. * This can be used in the render loop
  36869. */
  36870. GroundMesh.prototype.updateCoordinateHeights = function () {
  36871. if (!this._heightQuads || this._heightQuads.length == 0) {
  36872. this._initHeightQuads();
  36873. }
  36874. this._computeHeightQuads();
  36875. };
  36876. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  36877. GroundMesh.prototype._getFacetAt = function (x, z) {
  36878. // retrieve col and row from x, z coordinates in the ground local system
  36879. var subdivisionsX = this._subdivisionsX;
  36880. var subdivisionsY = this._subdivisionsY;
  36881. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  36882. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  36883. var quad = this._heightQuads[row * this._subdivisionsX + col];
  36884. var facet;
  36885. if (z < quad.slope.x * x + quad.slope.y) {
  36886. facet = quad.facet1;
  36887. }
  36888. else {
  36889. facet = quad.facet2;
  36890. }
  36891. return facet;
  36892. };
  36893. // Creates and populates the heightMap array with "facet" elements :
  36894. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  36895. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  36896. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  36897. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  36898. GroundMesh.prototype._initHeightQuads = function () {
  36899. var subdivisionsX = this._subdivisionsX;
  36900. var subdivisionsY = this._subdivisionsY;
  36901. this._heightQuads = new Array();
  36902. for (var row = 0; row < subdivisionsY; row++) {
  36903. for (var col = 0; col < subdivisionsX; col++) {
  36904. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  36905. this._heightQuads[row * subdivisionsX + col] = quad;
  36906. }
  36907. }
  36908. };
  36909. // Compute each quad element values and update the the heightMap array :
  36910. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  36911. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  36912. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  36913. GroundMesh.prototype._computeHeightQuads = function () {
  36914. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36915. var v1 = BABYLON.Tmp.Vector3[3];
  36916. var v2 = BABYLON.Tmp.Vector3[2];
  36917. var v3 = BABYLON.Tmp.Vector3[1];
  36918. var v4 = BABYLON.Tmp.Vector3[0];
  36919. var v1v2 = BABYLON.Tmp.Vector3[4];
  36920. var v1v3 = BABYLON.Tmp.Vector3[5];
  36921. var v1v4 = BABYLON.Tmp.Vector3[6];
  36922. var norm1 = BABYLON.Tmp.Vector3[7];
  36923. var norm2 = BABYLON.Tmp.Vector3[8];
  36924. var i = 0;
  36925. var j = 0;
  36926. var k = 0;
  36927. var cd = 0; // 2D slope coefficient : z = cd * x + h
  36928. var h = 0;
  36929. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  36930. var d2 = 0;
  36931. var subdivisionsX = this._subdivisionsX;
  36932. var subdivisionsY = this._subdivisionsY;
  36933. for (var row = 0; row < subdivisionsY; row++) {
  36934. for (var col = 0; col < subdivisionsX; col++) {
  36935. i = col * 3;
  36936. j = row * (subdivisionsX + 1) * 3;
  36937. k = (row + 1) * (subdivisionsX + 1) * 3;
  36938. v1.x = positions[j + i];
  36939. v1.y = positions[j + i + 1];
  36940. v1.z = positions[j + i + 2];
  36941. v2.x = positions[j + i + 3];
  36942. v2.y = positions[j + i + 4];
  36943. v2.z = positions[j + i + 5];
  36944. v3.x = positions[k + i];
  36945. v3.y = positions[k + i + 1];
  36946. v3.z = positions[k + i + 2];
  36947. v4.x = positions[k + i + 3];
  36948. v4.y = positions[k + i + 4];
  36949. v4.z = positions[k + i + 5];
  36950. // 2D slope V1V4
  36951. cd = (v4.z - v1.z) / (v4.x - v1.x);
  36952. h = v1.z - cd * v1.x; // v1 belongs to the slope
  36953. // facet equations :
  36954. // we compute each facet normal vector
  36955. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  36956. // we compute the value d by applying the equation to v1 which belongs to the plane
  36957. // then we store the facet equation in a Vector4
  36958. v2.subtractToRef(v1, v1v2);
  36959. v3.subtractToRef(v1, v1v3);
  36960. v4.subtractToRef(v1, v1v4);
  36961. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  36962. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  36963. norm1.normalize();
  36964. norm2.normalize();
  36965. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  36966. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  36967. var quad = this._heightQuads[row * subdivisionsX + col];
  36968. quad.slope.copyFromFloats(cd, h);
  36969. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  36970. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  36971. }
  36972. }
  36973. };
  36974. return GroundMesh;
  36975. }(BABYLON.Mesh));
  36976. BABYLON.GroundMesh = GroundMesh;
  36977. })(BABYLON || (BABYLON = {}));
  36978. //# sourceMappingURL=../Mesh/babylon.groundMesh.js.map
  36979. var BABYLON;
  36980. (function (BABYLON) {
  36981. var LinesMesh = (function (_super) {
  36982. __extends(LinesMesh, _super);
  36983. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  36984. if (parent === void 0) { parent = null; }
  36985. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  36986. this.color = new BABYLON.Color3(1, 1, 1);
  36987. this.alpha = 1;
  36988. this._positionBuffer = {};
  36989. if (source) {
  36990. this.color = source.color.clone();
  36991. this.alpha = source.alpha;
  36992. }
  36993. this._intersectionThreshold = 0.1;
  36994. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  36995. attributes: [BABYLON.VertexBuffer.PositionKind],
  36996. uniforms: ["worldViewProjection", "color"],
  36997. needAlphaBlending: true
  36998. });
  36999. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  37000. }
  37001. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  37002. /**
  37003. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37004. * This margin is expressed in world space coordinates, so its value may vary.
  37005. * Default value is 0.1
  37006. * @returns the intersection Threshold value.
  37007. */
  37008. get: function () {
  37009. return this._intersectionThreshold;
  37010. },
  37011. /**
  37012. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37013. * This margin is expressed in world space coordinates, so its value may vary.
  37014. * @param value the new threshold to apply
  37015. */
  37016. set: function (value) {
  37017. if (this._intersectionThreshold === value) {
  37018. return;
  37019. }
  37020. this._intersectionThreshold = value;
  37021. if (this.geometry) {
  37022. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  37023. }
  37024. },
  37025. enumerable: true,
  37026. configurable: true
  37027. });
  37028. Object.defineProperty(LinesMesh.prototype, "material", {
  37029. get: function () {
  37030. return this._colorShader;
  37031. },
  37032. enumerable: true,
  37033. configurable: true
  37034. });
  37035. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  37036. get: function () {
  37037. return false;
  37038. },
  37039. enumerable: true,
  37040. configurable: true
  37041. });
  37042. LinesMesh.prototype.createInstance = function (name) {
  37043. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  37044. return null;
  37045. };
  37046. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  37047. var engine = this.getScene().getEngine();
  37048. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  37049. // VBOs
  37050. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  37051. // Color
  37052. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  37053. };
  37054. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  37055. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  37056. return;
  37057. }
  37058. var engine = this.getScene().getEngine();
  37059. // Draw order
  37060. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  37061. };
  37062. LinesMesh.prototype.dispose = function (doNotRecurse) {
  37063. this._colorShader.dispose();
  37064. _super.prototype.dispose.call(this, doNotRecurse);
  37065. };
  37066. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  37067. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  37068. };
  37069. return LinesMesh;
  37070. }(BABYLON.Mesh));
  37071. BABYLON.LinesMesh = LinesMesh;
  37072. })(BABYLON || (BABYLON = {}));
  37073. //# sourceMappingURL=../Mesh/babylon.linesMesh.js.map
  37074. var BABYLON;
  37075. (function (BABYLON) {
  37076. var DefaultLoadingScreen = (function () {
  37077. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  37078. var _this = this;
  37079. if (_loadingText === void 0) { _loadingText = ""; }
  37080. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  37081. this._renderingCanvas = _renderingCanvas;
  37082. this._loadingText = _loadingText;
  37083. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  37084. // Resize
  37085. this._resizeLoadingUI = function () {
  37086. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  37087. _this._loadingDiv.style.position = "absolute";
  37088. _this._loadingDiv.style.left = canvasRect.left + "px";
  37089. _this._loadingDiv.style.top = canvasRect.top + "px";
  37090. _this._loadingDiv.style.width = canvasRect.width + "px";
  37091. _this._loadingDiv.style.height = canvasRect.height + "px";
  37092. };
  37093. }
  37094. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  37095. var _this = this;
  37096. if (this._loadingDiv) {
  37097. // Do not add a loading screen if there is already one
  37098. return;
  37099. }
  37100. this._loadingDiv = document.createElement("div");
  37101. this._loadingDiv.id = "babylonjsLoadingDiv";
  37102. this._loadingDiv.style.opacity = "0";
  37103. this._loadingDiv.style.transition = "opacity 1.5s ease";
  37104. // Loading text
  37105. this._loadingTextDiv = document.createElement("div");
  37106. this._loadingTextDiv.style.position = "absolute";
  37107. this._loadingTextDiv.style.left = "0";
  37108. this._loadingTextDiv.style.top = "50%";
  37109. this._loadingTextDiv.style.marginTop = "80px";
  37110. this._loadingTextDiv.style.width = "100%";
  37111. this._loadingTextDiv.style.height = "20px";
  37112. this._loadingTextDiv.style.fontFamily = "Arial";
  37113. this._loadingTextDiv.style.fontSize = "14px";
  37114. this._loadingTextDiv.style.color = "white";
  37115. this._loadingTextDiv.style.textAlign = "center";
  37116. this._loadingTextDiv.innerHTML = "Loading";
  37117. this._loadingDiv.appendChild(this._loadingTextDiv);
  37118. //set the predefined text
  37119. this._loadingTextDiv.innerHTML = this._loadingText;
  37120. // Loading img
  37121. var imgBack = new Image();
  37122. 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==";
  37123. imgBack.style.position = "absolute";
  37124. imgBack.style.left = "50%";
  37125. imgBack.style.top = "50%";
  37126. imgBack.style.marginLeft = "-50px";
  37127. imgBack.style.marginTop = "-50px";
  37128. imgBack.style.transition = "transform 1.0s ease";
  37129. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  37130. var deg = 360;
  37131. var onTransitionEnd = function () {
  37132. deg += 360;
  37133. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  37134. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  37135. };
  37136. imgBack.addEventListener("transitionend", onTransitionEnd);
  37137. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  37138. this._loadingDiv.appendChild(imgBack);
  37139. // front image
  37140. var imgFront = new Image();
  37141. 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=";
  37142. imgFront.style.position = "absolute";
  37143. imgFront.style.left = "50%";
  37144. imgFront.style.top = "50%";
  37145. imgFront.style.marginLeft = "-50px";
  37146. imgFront.style.marginTop = "-50px";
  37147. this._loadingDiv.appendChild(imgFront);
  37148. this._resizeLoadingUI();
  37149. window.addEventListener("resize", this._resizeLoadingUI);
  37150. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  37151. document.body.appendChild(this._loadingDiv);
  37152. setTimeout(function () {
  37153. _this._loadingDiv.style.opacity = "1";
  37154. imgBack.style.transform = "rotateZ(360deg)";
  37155. imgBack.style.webkitTransform = "rotateZ(360deg)";
  37156. }, 0);
  37157. };
  37158. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  37159. var _this = this;
  37160. if (!this._loadingDiv) {
  37161. return;
  37162. }
  37163. var onTransitionEnd = function () {
  37164. if (!_this._loadingDiv) {
  37165. return;
  37166. }
  37167. document.body.removeChild(_this._loadingDiv);
  37168. window.removeEventListener("resize", _this._resizeLoadingUI);
  37169. _this._loadingDiv = null;
  37170. };
  37171. this._loadingDiv.style.opacity = "0";
  37172. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  37173. };
  37174. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  37175. set: function (text) {
  37176. this._loadingText = text;
  37177. if (this._loadingTextDiv) {
  37178. this._loadingTextDiv.innerHTML = this._loadingText;
  37179. }
  37180. },
  37181. enumerable: true,
  37182. configurable: true
  37183. });
  37184. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  37185. get: function () {
  37186. return this._loadingDivBackgroundColor;
  37187. },
  37188. set: function (color) {
  37189. this._loadingDivBackgroundColor = color;
  37190. if (!this._loadingDiv) {
  37191. return;
  37192. }
  37193. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  37194. },
  37195. enumerable: true,
  37196. configurable: true
  37197. });
  37198. return DefaultLoadingScreen;
  37199. }());
  37200. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  37201. })(BABYLON || (BABYLON = {}));
  37202. //# sourceMappingURL=../Tools/babylon.loadingScreen.js.map
  37203. var BABYLON;
  37204. (function (BABYLON) {
  37205. var AudioEngine = (function () {
  37206. function AudioEngine() {
  37207. this._audioContext = null;
  37208. this._audioContextInitialized = false;
  37209. this.canUseWebAudio = false;
  37210. this.WarnedWebAudioUnsupported = false;
  37211. this.unlocked = false;
  37212. this.isMP3supported = false;
  37213. this.isOGGsupported = false;
  37214. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  37215. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  37216. this.canUseWebAudio = true;
  37217. }
  37218. var audioElem = document.createElement('audio');
  37219. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  37220. this.isMP3supported = true;
  37221. }
  37222. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  37223. this.isOGGsupported = true;
  37224. }
  37225. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  37226. this._unlockiOSaudio();
  37227. }
  37228. else {
  37229. this.unlocked = true;
  37230. }
  37231. }
  37232. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  37233. get: function () {
  37234. if (!this._audioContextInitialized) {
  37235. this._initializeAudioContext();
  37236. }
  37237. return this._audioContext;
  37238. },
  37239. enumerable: true,
  37240. configurable: true
  37241. });
  37242. AudioEngine.prototype._unlockiOSaudio = function () {
  37243. var _this = this;
  37244. var unlockaudio = function () {
  37245. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  37246. var source = _this.audioContext.createBufferSource();
  37247. source.buffer = buffer;
  37248. source.connect(_this.audioContext.destination);
  37249. source.start(0);
  37250. setTimeout(function () {
  37251. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  37252. _this.unlocked = true;
  37253. window.removeEventListener('touchend', unlockaudio, false);
  37254. if (_this.onAudioUnlocked) {
  37255. _this.onAudioUnlocked();
  37256. }
  37257. }
  37258. }, 0);
  37259. };
  37260. window.addEventListener('touchend', unlockaudio, false);
  37261. };
  37262. AudioEngine.prototype._initializeAudioContext = function () {
  37263. try {
  37264. if (this.canUseWebAudio) {
  37265. this._audioContext = new AudioContext();
  37266. // create a global volume gain node
  37267. this.masterGain = this._audioContext.createGain();
  37268. this.masterGain.gain.value = 1;
  37269. this.masterGain.connect(this._audioContext.destination);
  37270. this._audioContextInitialized = true;
  37271. }
  37272. }
  37273. catch (e) {
  37274. this.canUseWebAudio = false;
  37275. BABYLON.Tools.Error("Web Audio: " + e.message);
  37276. }
  37277. };
  37278. AudioEngine.prototype.dispose = function () {
  37279. if (this.canUseWebAudio && this._audioContextInitialized) {
  37280. if (this._connectedAnalyser) {
  37281. this._connectedAnalyser.stopDebugCanvas();
  37282. this._connectedAnalyser.dispose();
  37283. this.masterGain.disconnect();
  37284. this.masterGain.connect(this._audioContext.destination);
  37285. this._connectedAnalyser = null;
  37286. }
  37287. this.masterGain.gain.value = 1;
  37288. }
  37289. this.WarnedWebAudioUnsupported = false;
  37290. };
  37291. AudioEngine.prototype.getGlobalVolume = function () {
  37292. if (this.canUseWebAudio && this._audioContextInitialized) {
  37293. return this.masterGain.gain.value;
  37294. }
  37295. else {
  37296. return -1;
  37297. }
  37298. };
  37299. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  37300. if (this.canUseWebAudio && this._audioContextInitialized) {
  37301. this.masterGain.gain.value = newVolume;
  37302. }
  37303. };
  37304. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  37305. if (this._connectedAnalyser) {
  37306. this._connectedAnalyser.stopDebugCanvas();
  37307. }
  37308. if (this.canUseWebAudio && this._audioContextInitialized) {
  37309. this._connectedAnalyser = analyser;
  37310. this.masterGain.disconnect();
  37311. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  37312. }
  37313. };
  37314. return AudioEngine;
  37315. }());
  37316. BABYLON.AudioEngine = AudioEngine;
  37317. })(BABYLON || (BABYLON = {}));
  37318. //# sourceMappingURL=../Audio/babylon.audioEngine.js.map
  37319. var BABYLON;
  37320. (function (BABYLON) {
  37321. var Sound = (function () {
  37322. /**
  37323. * Create a sound and attach it to a scene
  37324. * @param name Name of your sound
  37325. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  37326. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  37327. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  37328. */
  37329. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  37330. var _this = this;
  37331. this.autoplay = false;
  37332. this.loop = false;
  37333. this.useCustomAttenuation = false;
  37334. this.spatialSound = false;
  37335. this.refDistance = 1;
  37336. this.rolloffFactor = 1;
  37337. this.maxDistance = 100;
  37338. this.distanceModel = "linear";
  37339. this._panningModel = "equalpower";
  37340. this._playbackRate = 1;
  37341. this._streaming = false;
  37342. this._startTime = 0;
  37343. this._startOffset = 0;
  37344. this._position = BABYLON.Vector3.Zero();
  37345. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  37346. this._volume = 1;
  37347. this._isLoaded = false;
  37348. this._isReadyToPlay = false;
  37349. this.isPlaying = false;
  37350. this.isPaused = false;
  37351. this._isDirectional = false;
  37352. // Used if you'd like to create a directional sound.
  37353. // If not set, the sound will be omnidirectional
  37354. this._coneInnerAngle = 360;
  37355. this._coneOuterAngle = 360;
  37356. this._coneOuterGain = 0;
  37357. this._isOutputConnected = false;
  37358. this._urlType = "Unknown";
  37359. this.name = name;
  37360. this._scene = scene;
  37361. this._readyToPlayCallback = readyToPlayCallback;
  37362. // Default custom attenuation function is a linear attenuation
  37363. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  37364. if (currentDistance < maxDistance) {
  37365. return currentVolume * (1 - currentDistance / maxDistance);
  37366. }
  37367. else {
  37368. return 0;
  37369. }
  37370. };
  37371. if (options) {
  37372. this.autoplay = options.autoplay || false;
  37373. this.loop = options.loop || false;
  37374. // if volume === 0, we need another way to check this option
  37375. if (options.volume !== undefined) {
  37376. this._volume = options.volume;
  37377. }
  37378. this.spatialSound = options.spatialSound || false;
  37379. this.maxDistance = options.maxDistance || 100;
  37380. this.useCustomAttenuation = options.useCustomAttenuation || false;
  37381. this.rolloffFactor = options.rolloffFactor || 1;
  37382. this.refDistance = options.refDistance || 1;
  37383. this.distanceModel = options.distanceModel || "linear";
  37384. this._playbackRate = options.playbackRate || 1;
  37385. this._streaming = options.streaming || false;
  37386. }
  37387. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37388. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  37389. this._soundGain.gain.value = this._volume;
  37390. this._inputAudioNode = this._soundGain;
  37391. this._ouputAudioNode = this._soundGain;
  37392. if (this.spatialSound) {
  37393. this._createSpatialParameters();
  37394. }
  37395. this._scene.mainSoundTrack.AddSound(this);
  37396. var validParameter = true;
  37397. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  37398. if (urlOrArrayBuffer) {
  37399. if (typeof (urlOrArrayBuffer) === "string")
  37400. this._urlType = "String";
  37401. if (Array.isArray(urlOrArrayBuffer))
  37402. this._urlType = "Array";
  37403. if (urlOrArrayBuffer instanceof ArrayBuffer)
  37404. this._urlType = "ArrayBuffer";
  37405. var urls = [];
  37406. var codecSupportedFound = false;
  37407. switch (this._urlType) {
  37408. case "ArrayBuffer":
  37409. if (urlOrArrayBuffer.byteLength > 0) {
  37410. codecSupportedFound = true;
  37411. this._soundLoaded(urlOrArrayBuffer);
  37412. }
  37413. break;
  37414. case "String":
  37415. urls.push(urlOrArrayBuffer);
  37416. case "Array":
  37417. if (urls.length === 0)
  37418. urls = urlOrArrayBuffer;
  37419. // If we found a supported format, we load it immediately and stop the loop
  37420. for (var i = 0; i < urls.length; i++) {
  37421. var url = urls[i];
  37422. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  37423. codecSupportedFound = true;
  37424. }
  37425. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  37426. codecSupportedFound = true;
  37427. }
  37428. if (url.indexOf(".wav", url.length - 4) !== -1) {
  37429. codecSupportedFound = true;
  37430. }
  37431. if (codecSupportedFound) {
  37432. // Loading sound using XHR2
  37433. if (!this._streaming) {
  37434. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  37435. }
  37436. else {
  37437. this._htmlAudioElement = new Audio(url);
  37438. this._htmlAudioElement.controls = false;
  37439. this._htmlAudioElement.loop = this.loop;
  37440. this._htmlAudioElement.crossOrigin = "anonymous";
  37441. this._htmlAudioElement.preload = "auto";
  37442. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  37443. _this._isReadyToPlay = true;
  37444. if (_this.autoplay) {
  37445. _this.play();
  37446. }
  37447. if (_this._readyToPlayCallback) {
  37448. _this._readyToPlayCallback();
  37449. }
  37450. });
  37451. document.body.appendChild(this._htmlAudioElement);
  37452. }
  37453. break;
  37454. }
  37455. }
  37456. break;
  37457. default:
  37458. validParameter = false;
  37459. break;
  37460. }
  37461. if (!validParameter) {
  37462. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  37463. }
  37464. else {
  37465. if (!codecSupportedFound) {
  37466. this._isReadyToPlay = true;
  37467. // Simulating a ready to play event to avoid breaking code path
  37468. if (this._readyToPlayCallback) {
  37469. window.setTimeout(function () {
  37470. _this._readyToPlayCallback();
  37471. }, 1000);
  37472. }
  37473. }
  37474. }
  37475. }
  37476. }
  37477. else {
  37478. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  37479. this._scene.mainSoundTrack.AddSound(this);
  37480. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  37481. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  37482. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  37483. }
  37484. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  37485. if (this._readyToPlayCallback) {
  37486. window.setTimeout(function () {
  37487. _this._readyToPlayCallback();
  37488. }, 1000);
  37489. }
  37490. }
  37491. }
  37492. Sound.prototype.dispose = function () {
  37493. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  37494. if (this.isPlaying) {
  37495. this.stop();
  37496. }
  37497. this._isReadyToPlay = false;
  37498. if (this.soundTrackId === -1) {
  37499. this._scene.mainSoundTrack.RemoveSound(this);
  37500. }
  37501. else {
  37502. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  37503. }
  37504. if (this._soundGain) {
  37505. this._soundGain.disconnect();
  37506. this._soundGain = null;
  37507. }
  37508. if (this._soundPanner) {
  37509. this._soundPanner.disconnect();
  37510. this._soundPanner = null;
  37511. }
  37512. if (this._soundSource) {
  37513. this._soundSource.disconnect();
  37514. this._soundSource = null;
  37515. }
  37516. this._audioBuffer = null;
  37517. if (this._htmlAudioElement) {
  37518. this._htmlAudioElement.pause();
  37519. this._htmlAudioElement.src = "";
  37520. document.body.removeChild(this._htmlAudioElement);
  37521. }
  37522. if (this._connectedMesh) {
  37523. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  37524. this._connectedMesh = null;
  37525. }
  37526. }
  37527. };
  37528. Sound.prototype._soundLoaded = function (audioData) {
  37529. var _this = this;
  37530. this._isLoaded = true;
  37531. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  37532. _this._audioBuffer = buffer;
  37533. _this._isReadyToPlay = true;
  37534. if (_this.autoplay) {
  37535. _this.play();
  37536. }
  37537. if (_this._readyToPlayCallback) {
  37538. _this._readyToPlayCallback();
  37539. }
  37540. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  37541. };
  37542. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  37543. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37544. this._audioBuffer = audioBuffer;
  37545. this._isReadyToPlay = true;
  37546. }
  37547. };
  37548. Sound.prototype.updateOptions = function (options) {
  37549. if (options) {
  37550. this.loop = options.loop || this.loop;
  37551. this.maxDistance = options.maxDistance || this.maxDistance;
  37552. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  37553. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  37554. this.refDistance = options.refDistance || this.refDistance;
  37555. this.distanceModel = options.distanceModel || this.distanceModel;
  37556. this._playbackRate = options.playbackRate || this._playbackRate;
  37557. this._updateSpatialParameters();
  37558. if (this.isPlaying) {
  37559. if (this._streaming) {
  37560. this._htmlAudioElement.playbackRate = this._playbackRate;
  37561. }
  37562. else {
  37563. this._soundSource.playbackRate.value = this._playbackRate;
  37564. }
  37565. }
  37566. }
  37567. };
  37568. Sound.prototype._createSpatialParameters = function () {
  37569. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37570. if (this._scene.headphone) {
  37571. this._panningModel = "HRTF";
  37572. }
  37573. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  37574. this._updateSpatialParameters();
  37575. this._soundPanner.connect(this._ouputAudioNode);
  37576. this._inputAudioNode = this._soundPanner;
  37577. }
  37578. };
  37579. Sound.prototype._updateSpatialParameters = function () {
  37580. if (this.spatialSound) {
  37581. if (this.useCustomAttenuation) {
  37582. // Tricks to disable in a way embedded Web Audio attenuation
  37583. this._soundPanner.distanceModel = "linear";
  37584. this._soundPanner.maxDistance = Number.MAX_VALUE;
  37585. this._soundPanner.refDistance = 1;
  37586. this._soundPanner.rolloffFactor = 1;
  37587. this._soundPanner.panningModel = this._panningModel;
  37588. }
  37589. else {
  37590. this._soundPanner.distanceModel = this.distanceModel;
  37591. this._soundPanner.maxDistance = this.maxDistance;
  37592. this._soundPanner.refDistance = this.refDistance;
  37593. this._soundPanner.rolloffFactor = this.rolloffFactor;
  37594. this._soundPanner.panningModel = this._panningModel;
  37595. }
  37596. }
  37597. };
  37598. Sound.prototype.switchPanningModelToHRTF = function () {
  37599. this._panningModel = "HRTF";
  37600. this._switchPanningModel();
  37601. };
  37602. Sound.prototype.switchPanningModelToEqualPower = function () {
  37603. this._panningModel = "equalpower";
  37604. this._switchPanningModel();
  37605. };
  37606. Sound.prototype._switchPanningModel = function () {
  37607. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  37608. this._soundPanner.panningModel = this._panningModel;
  37609. }
  37610. };
  37611. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  37612. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37613. if (this._isOutputConnected) {
  37614. this._ouputAudioNode.disconnect();
  37615. }
  37616. this._ouputAudioNode.connect(soundTrackAudioNode);
  37617. this._isOutputConnected = true;
  37618. }
  37619. };
  37620. /**
  37621. * Transform this sound into a directional source
  37622. * @param coneInnerAngle Size of the inner cone in degree
  37623. * @param coneOuterAngle Size of the outer cone in degree
  37624. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  37625. */
  37626. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  37627. if (coneOuterAngle < coneInnerAngle) {
  37628. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  37629. return;
  37630. }
  37631. this._coneInnerAngle = coneInnerAngle;
  37632. this._coneOuterAngle = coneOuterAngle;
  37633. this._coneOuterGain = coneOuterGain;
  37634. this._isDirectional = true;
  37635. if (this.isPlaying && this.loop) {
  37636. this.stop();
  37637. this.play();
  37638. }
  37639. };
  37640. Sound.prototype.setPosition = function (newPosition) {
  37641. this._position = newPosition;
  37642. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  37643. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  37644. }
  37645. };
  37646. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  37647. this._localDirection = newLocalDirection;
  37648. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  37649. this._updateDirection();
  37650. }
  37651. };
  37652. Sound.prototype._updateDirection = function () {
  37653. var mat = this._connectedMesh.getWorldMatrix();
  37654. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  37655. direction.normalize();
  37656. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  37657. };
  37658. Sound.prototype.updateDistanceFromListener = function () {
  37659. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  37660. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  37661. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  37662. }
  37663. };
  37664. Sound.prototype.setAttenuationFunction = function (callback) {
  37665. this._customAttenuationFunction = callback;
  37666. };
  37667. /**
  37668. * Play the sound
  37669. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  37670. * @param offset (optional) Start the sound setting it at a specific time
  37671. */
  37672. Sound.prototype.play = function (time, offset) {
  37673. var _this = this;
  37674. if (this._isReadyToPlay && this._scene.audioEnabled) {
  37675. try {
  37676. if (this._startOffset < 0) {
  37677. time = -this._startOffset;
  37678. this._startOffset = 0;
  37679. }
  37680. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  37681. if (!this._soundSource || !this._streamingSource) {
  37682. if (this.spatialSound) {
  37683. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  37684. if (this._isDirectional) {
  37685. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  37686. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  37687. this._soundPanner.coneOuterGain = this._coneOuterGain;
  37688. if (this._connectedMesh) {
  37689. this._updateDirection();
  37690. }
  37691. else {
  37692. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  37693. }
  37694. }
  37695. }
  37696. }
  37697. if (this._streaming) {
  37698. if (!this._streamingSource) {
  37699. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  37700. this._htmlAudioElement.onended = function () { _this._onended(); };
  37701. this._htmlAudioElement.playbackRate = this._playbackRate;
  37702. }
  37703. this._streamingSource.disconnect();
  37704. this._streamingSource.connect(this._inputAudioNode);
  37705. this._htmlAudioElement.play();
  37706. }
  37707. else {
  37708. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  37709. this._soundSource.buffer = this._audioBuffer;
  37710. this._soundSource.connect(this._inputAudioNode);
  37711. this._soundSource.loop = this.loop;
  37712. this._soundSource.playbackRate.value = this._playbackRate;
  37713. this._soundSource.onended = function () { _this._onended(); };
  37714. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  37715. }
  37716. this._startTime = startTime;
  37717. this.isPlaying = true;
  37718. this.isPaused = false;
  37719. }
  37720. catch (ex) {
  37721. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  37722. }
  37723. }
  37724. };
  37725. Sound.prototype._onended = function () {
  37726. this.isPlaying = false;
  37727. if (this.onended) {
  37728. this.onended();
  37729. }
  37730. };
  37731. /**
  37732. * Stop the sound
  37733. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  37734. */
  37735. Sound.prototype.stop = function (time) {
  37736. if (this.isPlaying) {
  37737. if (this._streaming) {
  37738. this._htmlAudioElement.pause();
  37739. // Test needed for Firefox or it will generate an Invalid State Error
  37740. if (this._htmlAudioElement.currentTime > 0) {
  37741. this._htmlAudioElement.currentTime = 0;
  37742. }
  37743. }
  37744. else {
  37745. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  37746. this._soundSource.stop(stopTime);
  37747. this._soundSource.onended = null;
  37748. if (!this.isPaused) {
  37749. this._startOffset = 0;
  37750. }
  37751. }
  37752. this.isPlaying = false;
  37753. }
  37754. };
  37755. Sound.prototype.pause = function () {
  37756. if (this.isPlaying) {
  37757. this.isPaused = true;
  37758. if (this._streaming) {
  37759. this._htmlAudioElement.pause();
  37760. }
  37761. else {
  37762. this.stop(0);
  37763. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  37764. }
  37765. }
  37766. };
  37767. Sound.prototype.setVolume = function (newVolume, time) {
  37768. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37769. if (time) {
  37770. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  37771. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  37772. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  37773. }
  37774. else {
  37775. this._soundGain.gain.value = newVolume;
  37776. }
  37777. }
  37778. this._volume = newVolume;
  37779. };
  37780. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  37781. this._playbackRate = newPlaybackRate;
  37782. if (this.isPlaying) {
  37783. if (this._streaming) {
  37784. this._htmlAudioElement.playbackRate = this._playbackRate;
  37785. }
  37786. else {
  37787. this._soundSource.playbackRate.value = this._playbackRate;
  37788. }
  37789. }
  37790. };
  37791. Sound.prototype.getVolume = function () {
  37792. return this._volume;
  37793. };
  37794. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  37795. var _this = this;
  37796. if (this._connectedMesh) {
  37797. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  37798. this._registerFunc = null;
  37799. }
  37800. this._connectedMesh = meshToConnectTo;
  37801. if (!this.spatialSound) {
  37802. this.spatialSound = true;
  37803. this._createSpatialParameters();
  37804. if (this.isPlaying && this.loop) {
  37805. this.stop();
  37806. this.play();
  37807. }
  37808. }
  37809. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  37810. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  37811. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  37812. };
  37813. Sound.prototype.detachFromMesh = function () {
  37814. if (this._connectedMesh) {
  37815. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  37816. this._registerFunc = null;
  37817. this._connectedMesh = null;
  37818. }
  37819. };
  37820. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  37821. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  37822. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  37823. this._updateDirection();
  37824. }
  37825. };
  37826. Sound.prototype.clone = function () {
  37827. var _this = this;
  37828. if (!this._streaming) {
  37829. var setBufferAndRun = function () {
  37830. if (_this._isReadyToPlay) {
  37831. clonedSound._audioBuffer = _this.getAudioBuffer();
  37832. clonedSound._isReadyToPlay = true;
  37833. if (clonedSound.autoplay) {
  37834. clonedSound.play();
  37835. }
  37836. }
  37837. else {
  37838. window.setTimeout(setBufferAndRun, 300);
  37839. }
  37840. };
  37841. var currentOptions = {
  37842. autoplay: this.autoplay, loop: this.loop,
  37843. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  37844. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  37845. refDistance: this.refDistance, distanceModel: this.distanceModel
  37846. };
  37847. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  37848. if (this.useCustomAttenuation) {
  37849. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  37850. }
  37851. clonedSound.setPosition(this._position);
  37852. clonedSound.setPlaybackRate(this._playbackRate);
  37853. setBufferAndRun();
  37854. return clonedSound;
  37855. }
  37856. else {
  37857. return null;
  37858. }
  37859. };
  37860. Sound.prototype.getAudioBuffer = function () {
  37861. return this._audioBuffer;
  37862. };
  37863. Sound.prototype.serialize = function () {
  37864. var serializationObject = {
  37865. name: this.name,
  37866. url: this.name,
  37867. autoplay: this.autoplay,
  37868. loop: this.loop,
  37869. volume: this._volume,
  37870. spatialSound: this.spatialSound,
  37871. maxDistance: this.maxDistance,
  37872. rolloffFactor: this.rolloffFactor,
  37873. refDistance: this.refDistance,
  37874. distanceModel: this.distanceModel,
  37875. playbackRate: this._playbackRate,
  37876. panningModel: this._panningModel,
  37877. soundTrackId: this.soundTrackId
  37878. };
  37879. if (this.spatialSound) {
  37880. if (this._connectedMesh)
  37881. serializationObject.connectedMeshId = this._connectedMesh.id;
  37882. serializationObject.position = this._position.asArray();
  37883. serializationObject.refDistance = this.refDistance;
  37884. serializationObject.distanceModel = this.distanceModel;
  37885. serializationObject.isDirectional = this._isDirectional;
  37886. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  37887. serializationObject.coneInnerAngle = this._coneInnerAngle;
  37888. serializationObject.coneOuterAngle = this._coneOuterAngle;
  37889. serializationObject.coneOuterGain = this._coneOuterGain;
  37890. }
  37891. return serializationObject;
  37892. };
  37893. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  37894. var soundName = parsedSound.name;
  37895. var soundUrl;
  37896. if (parsedSound.url) {
  37897. soundUrl = rootUrl + parsedSound.url;
  37898. }
  37899. else {
  37900. soundUrl = rootUrl + soundName;
  37901. }
  37902. var options = {
  37903. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  37904. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  37905. rolloffFactor: parsedSound.rolloffFactor,
  37906. refDistance: parsedSound.refDistance,
  37907. distanceModel: parsedSound.distanceModel,
  37908. playbackRate: parsedSound.playbackRate
  37909. };
  37910. var newSound;
  37911. if (!sourceSound) {
  37912. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  37913. scene._addPendingData(newSound);
  37914. }
  37915. else {
  37916. var setBufferAndRun = function () {
  37917. if (sourceSound._isReadyToPlay) {
  37918. newSound._audioBuffer = sourceSound.getAudioBuffer();
  37919. newSound._isReadyToPlay = true;
  37920. if (newSound.autoplay) {
  37921. newSound.play();
  37922. }
  37923. }
  37924. else {
  37925. window.setTimeout(setBufferAndRun, 300);
  37926. }
  37927. };
  37928. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  37929. setBufferAndRun();
  37930. }
  37931. if (parsedSound.position) {
  37932. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  37933. newSound.setPosition(soundPosition);
  37934. }
  37935. if (parsedSound.isDirectional) {
  37936. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  37937. if (parsedSound.localDirectionToMesh) {
  37938. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  37939. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  37940. }
  37941. }
  37942. if (parsedSound.connectedMeshId) {
  37943. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  37944. if (connectedMesh) {
  37945. newSound.attachToMesh(connectedMesh);
  37946. }
  37947. }
  37948. return newSound;
  37949. };
  37950. return Sound;
  37951. }());
  37952. BABYLON.Sound = Sound;
  37953. })(BABYLON || (BABYLON = {}));
  37954. //# sourceMappingURL=../Audio/babylon.sound.js.map
  37955. var BABYLON;
  37956. (function (BABYLON) {
  37957. var SoundTrack = (function () {
  37958. function SoundTrack(scene, options) {
  37959. this.id = -1;
  37960. this._isMainTrack = false;
  37961. this._isInitialized = false;
  37962. this._scene = scene;
  37963. this.soundCollection = new Array();
  37964. this._options = options;
  37965. if (!this._isMainTrack) {
  37966. this._scene.soundTracks.push(this);
  37967. this.id = this._scene.soundTracks.length - 1;
  37968. }
  37969. }
  37970. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  37971. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37972. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  37973. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  37974. if (this._options) {
  37975. if (this._options.volume) {
  37976. this._outputAudioNode.gain.value = this._options.volume;
  37977. }
  37978. if (this._options.mainTrack) {
  37979. this._isMainTrack = this._options.mainTrack;
  37980. }
  37981. }
  37982. this._isInitialized = true;
  37983. }
  37984. };
  37985. SoundTrack.prototype.dispose = function () {
  37986. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37987. if (this._connectedAnalyser) {
  37988. this._connectedAnalyser.stopDebugCanvas();
  37989. }
  37990. while (this.soundCollection.length) {
  37991. this.soundCollection[0].dispose();
  37992. }
  37993. if (this._outputAudioNode) {
  37994. this._outputAudioNode.disconnect();
  37995. }
  37996. this._outputAudioNode = null;
  37997. }
  37998. };
  37999. SoundTrack.prototype.AddSound = function (sound) {
  38000. if (!this._isInitialized) {
  38001. this._initializeSoundTrackAudioGraph();
  38002. }
  38003. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38004. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  38005. }
  38006. if (sound.soundTrackId) {
  38007. if (sound.soundTrackId === -1) {
  38008. this._scene.mainSoundTrack.RemoveSound(sound);
  38009. }
  38010. else {
  38011. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  38012. }
  38013. }
  38014. this.soundCollection.push(sound);
  38015. sound.soundTrackId = this.id;
  38016. };
  38017. SoundTrack.prototype.RemoveSound = function (sound) {
  38018. var index = this.soundCollection.indexOf(sound);
  38019. if (index !== -1) {
  38020. this.soundCollection.splice(index, 1);
  38021. }
  38022. };
  38023. SoundTrack.prototype.setVolume = function (newVolume) {
  38024. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38025. this._outputAudioNode.gain.value = newVolume;
  38026. }
  38027. };
  38028. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  38029. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38030. for (var i = 0; i < this.soundCollection.length; i++) {
  38031. this.soundCollection[i].switchPanningModelToHRTF();
  38032. }
  38033. }
  38034. };
  38035. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  38036. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38037. for (var i = 0; i < this.soundCollection.length; i++) {
  38038. this.soundCollection[i].switchPanningModelToEqualPower();
  38039. }
  38040. }
  38041. };
  38042. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  38043. if (this._connectedAnalyser) {
  38044. this._connectedAnalyser.stopDebugCanvas();
  38045. }
  38046. this._connectedAnalyser = analyser;
  38047. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38048. this._outputAudioNode.disconnect();
  38049. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  38050. }
  38051. };
  38052. return SoundTrack;
  38053. }());
  38054. BABYLON.SoundTrack = SoundTrack;
  38055. })(BABYLON || (BABYLON = {}));
  38056. //# sourceMappingURL=../Audio/babylon.soundtrack.js.map
  38057. var BABYLON;
  38058. (function (BABYLON) {
  38059. /**
  38060. * Special Glow Blur post process only blurring the alpha channel
  38061. * It enforces keeping the most luminous color in the color channel.
  38062. */
  38063. var GlowBlurPostProcess = (function (_super) {
  38064. __extends(GlowBlurPostProcess, _super);
  38065. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  38066. var _this = this;
  38067. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38068. _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  38069. this.direction = direction;
  38070. this.blurWidth = blurWidth;
  38071. this.onApplyObservable.add(function (effect) {
  38072. effect.setFloat2("screenSize", _this.width, _this.height);
  38073. effect.setVector2("direction", _this.direction);
  38074. effect.setFloat("blurWidth", _this.blurWidth);
  38075. });
  38076. }
  38077. return GlowBlurPostProcess;
  38078. }(BABYLON.PostProcess));
  38079. /**
  38080. * The highlight layer Helps adding a glow effect around a mesh.
  38081. *
  38082. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  38083. * glowy meshes to your scene.
  38084. *
  38085. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  38086. */
  38087. var HighlightLayer = (function () {
  38088. /**
  38089. * Instantiates a new highlight Layer and references it to the scene..
  38090. * @param name The name of the layer
  38091. * @param scene The scene to use the layer in
  38092. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  38093. */
  38094. function HighlightLayer(name, scene, options) {
  38095. this._vertexBuffers = {};
  38096. this._mainTextureDesiredSize = { width: 0, height: 0 };
  38097. this._meshes = {};
  38098. this._maxSize = 0;
  38099. this._shouldRender = false;
  38100. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  38101. this._excludedMeshes = {};
  38102. /**
  38103. * Specifies whether or not the inner glow is ACTIVE in the layer.
  38104. */
  38105. this.innerGlow = true;
  38106. /**
  38107. * Specifies whether or not the outer glow is ACTIVE in the layer.
  38108. */
  38109. this.outerGlow = true;
  38110. /**
  38111. * Specifies wether the highlight layer is enabled or not.
  38112. */
  38113. this.isEnabled = true;
  38114. /**
  38115. * An event triggered when the highlight layer has been disposed.
  38116. * @type {BABYLON.Observable}
  38117. */
  38118. this.onDisposeObservable = new BABYLON.Observable();
  38119. /**
  38120. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  38121. * @type {BABYLON.Observable}
  38122. */
  38123. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  38124. /**
  38125. * An event triggered when the highlight layer is being blurred.
  38126. * @type {BABYLON.Observable}
  38127. */
  38128. this.onBeforeBlurObservable = new BABYLON.Observable();
  38129. /**
  38130. * An event triggered when the highlight layer has been blurred.
  38131. * @type {BABYLON.Observable}
  38132. */
  38133. this.onAfterBlurObservable = new BABYLON.Observable();
  38134. /**
  38135. * An event triggered when the glowing blurred texture is being merged in the scene.
  38136. * @type {BABYLON.Observable}
  38137. */
  38138. this.onBeforeComposeObservable = new BABYLON.Observable();
  38139. /**
  38140. * An event triggered when the glowing blurred texture has been merged in the scene.
  38141. * @type {BABYLON.Observable}
  38142. */
  38143. this.onAfterComposeObservable = new BABYLON.Observable();
  38144. /**
  38145. * An event triggered when the highlight layer changes its size.
  38146. * @type {BABYLON.Observable}
  38147. */
  38148. this.onSizeChangedObservable = new BABYLON.Observable();
  38149. this._scene = scene;
  38150. var engine = scene.getEngine();
  38151. this._engine = engine;
  38152. this._maxSize = this._engine.getCaps().maxTextureSize;
  38153. this._scene.highlightLayers.push(this);
  38154. // Warn on stencil.
  38155. if (!this._engine.isStencilEnable) {
  38156. 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 }");
  38157. }
  38158. // Adapt options
  38159. this._options = options || {
  38160. mainTextureRatio: 0.25,
  38161. blurTextureSizeRatio: 0.5,
  38162. blurHorizontalSize: 1,
  38163. blurVerticalSize: 1,
  38164. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  38165. };
  38166. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  38167. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  38168. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  38169. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  38170. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  38171. // VBO
  38172. var vertices = [];
  38173. vertices.push(1, 1);
  38174. vertices.push(-1, 1);
  38175. vertices.push(-1, -1);
  38176. vertices.push(1, -1);
  38177. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  38178. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  38179. // Indices
  38180. var indices = [];
  38181. indices.push(0);
  38182. indices.push(1);
  38183. indices.push(2);
  38184. indices.push(0);
  38185. indices.push(2);
  38186. indices.push(3);
  38187. this._indexBuffer = engine.createIndexBuffer(indices);
  38188. // Effect
  38189. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  38190. // Render target
  38191. this.setMainTextureSize();
  38192. // Create Textures and post processes
  38193. this.createTextureAndPostProcesses();
  38194. }
  38195. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  38196. /**
  38197. * Gets the horizontal size of the blur.
  38198. */
  38199. get: function () {
  38200. return this._horizontalBlurPostprocess.blurWidth;
  38201. },
  38202. /**
  38203. * Specifies the horizontal size of the blur.
  38204. */
  38205. set: function (value) {
  38206. this._horizontalBlurPostprocess.blurWidth = value;
  38207. },
  38208. enumerable: true,
  38209. configurable: true
  38210. });
  38211. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  38212. /**
  38213. * Gets the vertical size of the blur.
  38214. */
  38215. get: function () {
  38216. return this._verticalBlurPostprocess.blurWidth;
  38217. },
  38218. /**
  38219. * Specifies the vertical size of the blur.
  38220. */
  38221. set: function (value) {
  38222. this._verticalBlurPostprocess.blurWidth = value;
  38223. },
  38224. enumerable: true,
  38225. configurable: true
  38226. });
  38227. Object.defineProperty(HighlightLayer.prototype, "camera", {
  38228. /**
  38229. * Gets the camera attached to the layer.
  38230. */
  38231. get: function () {
  38232. return this._options.camera;
  38233. },
  38234. enumerable: true,
  38235. configurable: true
  38236. });
  38237. /**
  38238. * Creates the render target textures and post processes used in the highlight layer.
  38239. */
  38240. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  38241. var _this = this;
  38242. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  38243. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  38244. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  38245. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  38246. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  38247. width: this._mainTextureDesiredSize.width,
  38248. height: this._mainTextureDesiredSize.height
  38249. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38250. this._mainTexture.activeCamera = this._options.camera;
  38251. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38252. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38253. this._mainTexture.anisotropicFilteringLevel = 1;
  38254. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38255. this._mainTexture.renderParticles = false;
  38256. this._mainTexture.renderList = null;
  38257. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  38258. width: blurTextureWidth,
  38259. height: blurTextureHeight
  38260. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38261. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38262. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38263. this._blurTexture.anisotropicFilteringLevel = 16;
  38264. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  38265. this._blurTexture.renderParticles = false;
  38266. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38267. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  38268. effect.setTexture("textureSampler", _this._mainTexture);
  38269. });
  38270. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38271. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  38272. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38273. });
  38274. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38275. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  38276. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38277. });
  38278. this._mainTexture.onAfterUnbindObservable.add(function () {
  38279. _this.onBeforeBlurObservable.notifyObservers(_this);
  38280. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  38281. _this.onAfterBlurObservable.notifyObservers(_this);
  38282. });
  38283. // Custom render function
  38284. var renderSubMesh = function (subMesh) {
  38285. var mesh = subMesh.getRenderingMesh();
  38286. var scene = _this._scene;
  38287. var engine = scene.getEngine();
  38288. // Culling
  38289. engine.setState(subMesh.getMaterial().backFaceCulling);
  38290. // Managing instances
  38291. var batch = mesh._getInstancesRenderList(subMesh._id);
  38292. if (batch.mustReturn) {
  38293. return;
  38294. }
  38295. // Excluded Mesh
  38296. if (_this._excludedMeshes[mesh.id]) {
  38297. return;
  38298. }
  38299. ;
  38300. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  38301. var highlightLayerMesh = _this._meshes[mesh.id];
  38302. var material = subMesh.getMaterial();
  38303. var emissiveTexture = null;
  38304. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  38305. emissiveTexture = material.emissiveTexture;
  38306. }
  38307. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  38308. engine.enableEffect(_this._glowMapGenerationEffect);
  38309. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  38310. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  38311. if (highlightLayerMesh) {
  38312. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  38313. }
  38314. else {
  38315. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  38316. }
  38317. // Alpha test
  38318. if (material && material.needAlphaTesting()) {
  38319. var alphaTexture = material.getAlphaTestTexture();
  38320. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  38321. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  38322. }
  38323. // Glow emissive only
  38324. if (emissiveTexture) {
  38325. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  38326. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  38327. }
  38328. // Bones
  38329. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38330. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  38331. }
  38332. // Draw
  38333. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  38334. }
  38335. else {
  38336. // Need to reset refresh rate of the shadowMap
  38337. _this._mainTexture.resetRefreshCounter();
  38338. }
  38339. };
  38340. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  38341. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  38342. var index;
  38343. for (index = 0; index < opaqueSubMeshes.length; index++) {
  38344. renderSubMesh(opaqueSubMeshes.data[index]);
  38345. }
  38346. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  38347. renderSubMesh(alphaTestSubMeshes.data[index]);
  38348. }
  38349. for (index = 0; index < transparentSubMeshes.length; index++) {
  38350. renderSubMesh(transparentSubMeshes.data[index]);
  38351. }
  38352. };
  38353. this._mainTexture.onClearObservable.add(function (engine) {
  38354. engine.clear(HighlightLayer.neutralColor, true, true, true);
  38355. });
  38356. };
  38357. /**
  38358. * Checks for the readiness of the element composing the layer.
  38359. * @param subMesh the mesh to check for
  38360. * @param useInstances specify wether or not to use instances to render the mesh
  38361. * @param emissiveTexture the associated emissive texture used to generate the glow
  38362. * @return true if ready otherwise, false
  38363. */
  38364. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  38365. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  38366. return false;
  38367. }
  38368. var defines = [];
  38369. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38370. var mesh = subMesh.getMesh();
  38371. var material = subMesh.getMaterial();
  38372. var uv1 = false;
  38373. var uv2 = false;
  38374. // Alpha test
  38375. if (material && material.needAlphaTesting()) {
  38376. var alphaTexture = material.getAlphaTestTexture();
  38377. if (alphaTexture) {
  38378. defines.push("#define ALPHATEST");
  38379. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  38380. alphaTexture.coordinatesIndex === 1) {
  38381. defines.push("#define DIFFUSEUV2");
  38382. uv2 = true;
  38383. }
  38384. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38385. defines.push("#define DIFFUSEUV1");
  38386. uv1 = true;
  38387. }
  38388. }
  38389. }
  38390. // Emissive
  38391. if (emissiveTexture) {
  38392. defines.push("#define EMISSIVE");
  38393. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  38394. emissiveTexture.coordinatesIndex === 1) {
  38395. defines.push("#define EMISSIVEUV2");
  38396. uv2 = true;
  38397. }
  38398. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38399. defines.push("#define EMISSIVEUV1");
  38400. uv1 = true;
  38401. }
  38402. }
  38403. if (uv1) {
  38404. attribs.push(BABYLON.VertexBuffer.UVKind);
  38405. defines.push("#define UV1");
  38406. }
  38407. if (uv2) {
  38408. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38409. defines.push("#define UV2");
  38410. }
  38411. // Bones
  38412. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38413. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38414. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38415. if (mesh.numBoneInfluencers > 4) {
  38416. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38417. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38418. }
  38419. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38420. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38421. }
  38422. else {
  38423. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38424. }
  38425. // Instances
  38426. if (useInstances) {
  38427. defines.push("#define INSTANCES");
  38428. attribs.push("world0");
  38429. attribs.push("world1");
  38430. attribs.push("world2");
  38431. attribs.push("world3");
  38432. }
  38433. // Get correct effect
  38434. var join = defines.join("\n");
  38435. if (this._cachedDefines !== join) {
  38436. this._cachedDefines = join;
  38437. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  38438. }
  38439. return this._glowMapGenerationEffect.isReady();
  38440. };
  38441. /**
  38442. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  38443. */
  38444. HighlightLayer.prototype.render = function () {
  38445. var currentEffect = this._glowMapMergeEffect;
  38446. // Check
  38447. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  38448. return;
  38449. var engine = this._scene.getEngine();
  38450. this.onBeforeComposeObservable.notifyObservers(this);
  38451. // Render
  38452. engine.enableEffect(currentEffect);
  38453. engine.setState(false);
  38454. // Cache
  38455. var previousStencilBuffer = engine.getStencilBuffer();
  38456. var previousStencilFunction = engine.getStencilFunction();
  38457. var previousStencilMask = engine.getStencilMask();
  38458. var previousAlphaMode = engine.getAlphaMode();
  38459. // Texture
  38460. currentEffect.setTexture("textureSampler", this._blurTexture);
  38461. // VBOs
  38462. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  38463. // Draw order
  38464. engine.setAlphaMode(this._options.alphaBlendingMode);
  38465. engine.setStencilMask(0x00);
  38466. engine.setStencilBuffer(true);
  38467. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  38468. if (this.outerGlow) {
  38469. currentEffect.setFloat("offset", 0);
  38470. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  38471. engine.draw(true, 0, 6);
  38472. }
  38473. if (this.innerGlow) {
  38474. currentEffect.setFloat("offset", 1);
  38475. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  38476. engine.draw(true, 0, 6);
  38477. }
  38478. // Restore Cache
  38479. engine.setStencilFunction(previousStencilFunction);
  38480. engine.setStencilMask(previousStencilMask);
  38481. engine.setAlphaMode(previousAlphaMode);
  38482. engine.setStencilBuffer(previousStencilBuffer);
  38483. this.onAfterComposeObservable.notifyObservers(this);
  38484. // Handle size changes.
  38485. var size = this._mainTexture.getSize();
  38486. this.setMainTextureSize();
  38487. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  38488. // Recreate RTT and post processes on size change.
  38489. this.onSizeChangedObservable.notifyObservers(this);
  38490. this.disposeTextureAndPostProcesses();
  38491. this.createTextureAndPostProcesses();
  38492. }
  38493. };
  38494. /**
  38495. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  38496. * @param mesh The mesh to exclude from the highlight layer
  38497. */
  38498. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  38499. var meshExcluded = this._excludedMeshes[mesh.id];
  38500. if (!meshExcluded) {
  38501. this._excludedMeshes[mesh.id] = {
  38502. mesh: mesh,
  38503. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  38504. mesh.getEngine().setStencilBuffer(false);
  38505. }),
  38506. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  38507. mesh.getEngine().setStencilBuffer(true);
  38508. }),
  38509. };
  38510. }
  38511. };
  38512. /**
  38513. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  38514. * @param mesh The mesh to highlight
  38515. */
  38516. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  38517. var meshExcluded = this._excludedMeshes[mesh.id];
  38518. if (meshExcluded) {
  38519. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  38520. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  38521. }
  38522. this._excludedMeshes[mesh.id] = undefined;
  38523. };
  38524. /**
  38525. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  38526. * @param mesh The mesh to highlight
  38527. * @param color The color of the highlight
  38528. * @param glowEmissiveOnly Extract the glow from the emissive texture
  38529. */
  38530. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  38531. var _this = this;
  38532. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  38533. var meshHighlight = this._meshes[mesh.id];
  38534. if (meshHighlight) {
  38535. meshHighlight.color = color;
  38536. }
  38537. else {
  38538. this._meshes[mesh.id] = {
  38539. mesh: mesh,
  38540. color: color,
  38541. // Lambda required for capture due to Observable this context
  38542. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  38543. if (_this._excludedMeshes[mesh.id]) {
  38544. _this.defaultStencilReference(mesh);
  38545. }
  38546. else {
  38547. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  38548. }
  38549. }),
  38550. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  38551. glowEmissiveOnly: glowEmissiveOnly
  38552. };
  38553. }
  38554. this._shouldRender = true;
  38555. };
  38556. /**
  38557. * Remove a mesh from the highlight layer in order to make it stop glowing.
  38558. * @param mesh The mesh to highlight
  38559. */
  38560. HighlightLayer.prototype.removeMesh = function (mesh) {
  38561. var meshHighlight = this._meshes[mesh.id];
  38562. if (meshHighlight) {
  38563. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  38564. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  38565. }
  38566. this._meshes[mesh.id] = undefined;
  38567. this._shouldRender = false;
  38568. for (var meshHighlightToCheck in this._meshes) {
  38569. if (meshHighlightToCheck) {
  38570. this._shouldRender = true;
  38571. break;
  38572. }
  38573. }
  38574. };
  38575. /**
  38576. * Returns true if the layer contains information to display, otherwise false.
  38577. */
  38578. HighlightLayer.prototype.shouldRender = function () {
  38579. return this.isEnabled && this._shouldRender;
  38580. };
  38581. /**
  38582. * Sets the main texture desired size which is the closest power of two
  38583. * of the engine canvas size.
  38584. */
  38585. HighlightLayer.prototype.setMainTextureSize = function () {
  38586. if (this._options.mainTextureFixedSize) {
  38587. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  38588. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  38589. }
  38590. else {
  38591. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  38592. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  38593. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  38594. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  38595. }
  38596. };
  38597. /**
  38598. * Force the stencil to the normal expected value for none glowing parts
  38599. */
  38600. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  38601. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  38602. };
  38603. /**
  38604. * Dispose only the render target textures and post process.
  38605. */
  38606. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  38607. this._blurTexture.dispose();
  38608. this._mainTexture.dispose();
  38609. this._downSamplePostprocess.dispose();
  38610. this._horizontalBlurPostprocess.dispose();
  38611. this._verticalBlurPostprocess.dispose();
  38612. };
  38613. /**
  38614. * Dispose the highlight layer and free resources.
  38615. */
  38616. HighlightLayer.prototype.dispose = function () {
  38617. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38618. if (vertexBuffer) {
  38619. vertexBuffer.dispose();
  38620. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  38621. }
  38622. if (this._indexBuffer) {
  38623. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38624. this._indexBuffer = null;
  38625. }
  38626. // Clean textures and post processes
  38627. this.disposeTextureAndPostProcesses();
  38628. // Clean mesh references
  38629. for (var id in this._meshes) {
  38630. var meshHighlight = this._meshes[id];
  38631. if (meshHighlight && meshHighlight.mesh) {
  38632. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  38633. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  38634. }
  38635. }
  38636. this._meshes = null;
  38637. for (var id in this._excludedMeshes) {
  38638. var meshHighlight = this._excludedMeshes[id];
  38639. if (meshHighlight) {
  38640. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  38641. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  38642. }
  38643. }
  38644. this._excludedMeshes = null;
  38645. // Remove from scene
  38646. var index = this._scene.highlightLayers.indexOf(this, 0);
  38647. if (index > -1) {
  38648. this._scene.highlightLayers.splice(index, 1);
  38649. }
  38650. // Callback
  38651. this.onDisposeObservable.notifyObservers(this);
  38652. this.onDisposeObservable.clear();
  38653. this.onBeforeRenderMainTextureObservable.clear();
  38654. this.onBeforeBlurObservable.clear();
  38655. this.onBeforeComposeObservable.clear();
  38656. this.onAfterComposeObservable.clear();
  38657. this.onSizeChangedObservable.clear();
  38658. };
  38659. /**
  38660. * The neutral color used during the preparation of the glow effect.
  38661. * This is black by default as the blend operation is a blend operation.
  38662. */
  38663. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  38664. /**
  38665. * Stencil value used for glowing meshes.
  38666. */
  38667. HighlightLayer.glowingMeshStencilReference = 0x02;
  38668. /**
  38669. * Stencil value used for the other meshes in the scene.
  38670. */
  38671. HighlightLayer.normalMeshStencilReference = 0x01;
  38672. return HighlightLayer;
  38673. }());
  38674. BABYLON.HighlightLayer = HighlightLayer;
  38675. })(BABYLON || (BABYLON = {}));
  38676. //# sourceMappingURL=../Layer/babylon.highlightlayer.js.map
  38677. var BABYLON;
  38678. (function (BABYLON) {
  38679. var SIMDVector3 = (function () {
  38680. function SIMDVector3() {
  38681. }
  38682. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  38683. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  38684. };
  38685. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  38686. var m = transformation.m;
  38687. var m0 = SIMD.Float32x4.load(m, 0);
  38688. var m1 = SIMD.Float32x4.load(m, 4);
  38689. var m2 = SIMD.Float32x4.load(m, 8);
  38690. var m3 = SIMD.Float32x4.load(m, 12);
  38691. 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));
  38692. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  38693. result.x = SIMD.Float32x4.extractLane(r, 0);
  38694. result.y = SIMD.Float32x4.extractLane(r, 1);
  38695. result.z = SIMD.Float32x4.extractLane(r, 2);
  38696. };
  38697. return SIMDVector3;
  38698. }());
  38699. var SIMDMatrix = (function () {
  38700. function SIMDMatrix() {
  38701. }
  38702. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  38703. var tm = this.m;
  38704. var om = other.m;
  38705. var m0 = SIMD.Float32x4.load(om, 0);
  38706. var m1 = SIMD.Float32x4.load(om, 4);
  38707. var m2 = SIMD.Float32x4.load(om, 8);
  38708. var m3 = SIMD.Float32x4.load(om, 12);
  38709. for (var i = 0; i < 16; i += 4) {
  38710. 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)))));
  38711. }
  38712. return this;
  38713. };
  38714. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  38715. var src = this.m;
  38716. var dest = other.m;
  38717. // Load the 4 rows
  38718. var src0 = SIMD.Float32x4.load(src, 0);
  38719. var src1 = SIMD.Float32x4.load(src, 4);
  38720. var src2 = SIMD.Float32x4.load(src, 8);
  38721. var src3 = SIMD.Float32x4.load(src, 12);
  38722. // Transpose the source matrix. Sort of. Not a true transpose operation
  38723. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  38724. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  38725. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  38726. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  38727. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  38728. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  38729. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  38730. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  38731. // This is a true transposition, but it will lead to an incorrect result
  38732. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  38733. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  38734. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  38735. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  38736. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  38737. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  38738. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  38739. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  38740. // ----
  38741. tmp1 = SIMD.Float32x4.mul(row2, row3);
  38742. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38743. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  38744. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  38745. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38746. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  38747. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  38748. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  38749. // ----
  38750. tmp1 = SIMD.Float32x4.mul(row1, row2);
  38751. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38752. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  38753. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  38754. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38755. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  38756. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  38757. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  38758. // ----
  38759. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  38760. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38761. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  38762. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  38763. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  38764. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38765. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  38766. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  38767. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  38768. // ----
  38769. tmp1 = SIMD.Float32x4.mul(row0, row1);
  38770. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38771. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  38772. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  38773. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38774. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  38775. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  38776. // ----
  38777. tmp1 = SIMD.Float32x4.mul(row0, row3);
  38778. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38779. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  38780. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  38781. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38782. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  38783. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  38784. // ----
  38785. tmp1 = SIMD.Float32x4.mul(row0, row2);
  38786. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  38787. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  38788. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  38789. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  38790. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  38791. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  38792. // Compute determinant
  38793. var det = SIMD.Float32x4.mul(row0, minor0);
  38794. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  38795. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  38796. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  38797. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  38798. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  38799. // These shuffles aren't necessary if the faulty transposition is done
  38800. // up at the top of this function.
  38801. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  38802. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  38803. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  38804. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  38805. // Compute final values by multiplying with 1/det
  38806. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  38807. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  38808. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  38809. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  38810. return this;
  38811. };
  38812. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  38813. var out = result.m;
  38814. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  38815. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  38816. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  38817. // cc.kmVec3Subtract(f, pCenter, pEye);
  38818. var f = SIMD.Float32x4.sub(center, eye);
  38819. // cc.kmVec3Normalize(f, f);
  38820. var tmp = SIMD.Float32x4.mul(f, f);
  38821. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  38822. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  38823. // cc.kmVec3Assign(up, pUp);
  38824. // cc.kmVec3Normalize(up, up);
  38825. tmp = SIMD.Float32x4.mul(up, up);
  38826. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  38827. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  38828. // cc.kmVec3Cross(s, f, up);
  38829. 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)));
  38830. // cc.kmVec3Normalize(s, s);
  38831. tmp = SIMD.Float32x4.mul(s, s);
  38832. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  38833. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  38834. // cc.kmVec3Cross(u, s, f);
  38835. 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)));
  38836. // cc.kmVec3Normalize(s, s);
  38837. tmp = SIMD.Float32x4.mul(s, s);
  38838. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  38839. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  38840. var zero = SIMD.Float32x4.splat(0.0);
  38841. s = SIMD.Float32x4.neg(s);
  38842. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  38843. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  38844. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  38845. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  38846. 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);
  38847. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  38848. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  38849. 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)))));
  38850. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  38851. 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)))));
  38852. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  38853. 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)))));
  38854. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  38855. 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)))));
  38856. };
  38857. return SIMDMatrix;
  38858. }());
  38859. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  38860. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  38861. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  38862. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  38863. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  38864. var SIMDHelper = (function () {
  38865. function SIMDHelper() {
  38866. }
  38867. Object.defineProperty(SIMDHelper, "IsEnabled", {
  38868. get: function () {
  38869. return SIMDHelper._isEnabled;
  38870. },
  38871. enumerable: true,
  38872. configurable: true
  38873. });
  38874. SIMDHelper.DisableSIMD = function () {
  38875. // Replace functions
  38876. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  38877. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  38878. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  38879. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  38880. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  38881. SIMDHelper._isEnabled = false;
  38882. };
  38883. SIMDHelper.EnableSIMD = function () {
  38884. if (self.SIMD === undefined) {
  38885. return;
  38886. }
  38887. // check if polyfills needed
  38888. if (!self.Math.fround) {
  38889. self.Math.fround = (function (array) { return function (x) {
  38890. return array[0] = x, array[0];
  38891. }; })(new Float32Array(1));
  38892. }
  38893. if (!self.Math.imul) {
  38894. self.Math.imul = function (a, b) {
  38895. var ah = (a >>> 16) & 0xffff;
  38896. var al = a & 0xffff;
  38897. var bh = (b >>> 16) & 0xffff;
  38898. var bl = b & 0xffff;
  38899. // the shift by 0 fixes the sign on the high part
  38900. // the final |0 converts the unsigned value into a signed value
  38901. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  38902. };
  38903. }
  38904. // Replace functions
  38905. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  38906. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  38907. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  38908. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  38909. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  38910. SIMDHelper._isEnabled = true;
  38911. };
  38912. SIMDHelper._isEnabled = false;
  38913. return SIMDHelper;
  38914. }());
  38915. BABYLON.SIMDHelper = SIMDHelper;
  38916. })(BABYLON || (BABYLON = {}));
  38917. //# sourceMappingURL=../Math/babylon.math.SIMD.js.map
  38918. var BABYLON;
  38919. (function (BABYLON) {
  38920. /**
  38921. * This class describe a rectangle that were added to the map.
  38922. * You have access to its coordinates either in pixel or normalized (UV)
  38923. */
  38924. var PackedRect = (function () {
  38925. function PackedRect(root, parent, pos, size) {
  38926. this._pos = pos;
  38927. this._size = size;
  38928. this._root = root;
  38929. this._parent = parent;
  38930. this._contentSize = null;
  38931. this._bottomNode = null;
  38932. this._leftNode = null;
  38933. this._initialSize = null;
  38934. this._rightNode = null;
  38935. }
  38936. Object.defineProperty(PackedRect.prototype, "pos", {
  38937. /**
  38938. * @returns the position of this node into the map
  38939. */
  38940. get: function () {
  38941. return this._pos;
  38942. },
  38943. enumerable: true,
  38944. configurable: true
  38945. });
  38946. Object.defineProperty(PackedRect.prototype, "contentSize", {
  38947. /**
  38948. * @returns the size of the rectangle this node handles
  38949. */
  38950. get: function () {
  38951. return this._contentSize;
  38952. },
  38953. enumerable: true,
  38954. configurable: true
  38955. });
  38956. Object.defineProperty(PackedRect.prototype, "UVs", {
  38957. /**
  38958. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  38959. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  38960. */
  38961. get: function () {
  38962. return this.getUVsForCustomSize(this._root._size);
  38963. },
  38964. enumerable: true,
  38965. configurable: true
  38966. });
  38967. /**
  38968. * 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.
  38969. * This method will return the UVs for this part by given the custom size of what you really use
  38970. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  38971. */
  38972. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  38973. var mainWidth = this._root._size.width;
  38974. var mainHeight = this._root._size.height;
  38975. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  38976. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  38977. var uvs = new Array();
  38978. uvs.push(topLeft);
  38979. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  38980. uvs.push(rightBottom);
  38981. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  38982. return uvs;
  38983. };
  38984. /**
  38985. * Free this rectangle from the map.
  38986. * Call this method when you no longer need the rectangle to be in the map.
  38987. */
  38988. PackedRect.prototype.freeContent = function () {
  38989. if (!this.contentSize) {
  38990. return;
  38991. }
  38992. this._contentSize = null;
  38993. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  38994. this.attemptDefrag();
  38995. };
  38996. Object.defineProperty(PackedRect.prototype, "isUsed", {
  38997. get: function () {
  38998. return this._contentSize != null || this._leftNode != null;
  38999. },
  39000. enumerable: true,
  39001. configurable: true
  39002. });
  39003. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  39004. var node = this.findNode(contentSize);
  39005. // Not enough space...
  39006. if (!node) {
  39007. return null;
  39008. }
  39009. node.splitNode(contentSize);
  39010. return node;
  39011. };
  39012. PackedRect.prototype.findNode = function (size) {
  39013. var resNode = null;
  39014. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  39015. if (this.isUsed) {
  39016. if (this._leftNode) {
  39017. resNode = this._leftNode.findNode(size);
  39018. }
  39019. if (!resNode && this._rightNode) {
  39020. resNode = this._rightNode.findNode(size);
  39021. }
  39022. if (!resNode && this._bottomNode) {
  39023. resNode = this._bottomNode.findNode(size);
  39024. }
  39025. }
  39026. else if (this._initialSize) {
  39027. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  39028. resNode = this;
  39029. }
  39030. else {
  39031. return null;
  39032. }
  39033. }
  39034. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  39035. resNode = this;
  39036. }
  39037. return resNode;
  39038. };
  39039. PackedRect.prototype.splitNode = function (contentSize) {
  39040. // 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)
  39041. if (!this._contentSize && this._initialSize) {
  39042. this._contentSize = contentSize.clone();
  39043. 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));
  39044. return this._leftNode.splitNode(contentSize);
  39045. }
  39046. else {
  39047. this._contentSize = contentSize.clone();
  39048. this._initialSize = contentSize.clone();
  39049. if (contentSize.width !== this._size.width) {
  39050. 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));
  39051. }
  39052. if (contentSize.height !== this._size.height) {
  39053. 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));
  39054. }
  39055. return this;
  39056. }
  39057. };
  39058. PackedRect.prototype.attemptDefrag = function () {
  39059. if (!this.isUsed && this.isRecursiveFree) {
  39060. this.clearNode();
  39061. if (this._parent) {
  39062. this._parent.attemptDefrag();
  39063. }
  39064. }
  39065. };
  39066. PackedRect.prototype.clearNode = function () {
  39067. this._initialSize = null;
  39068. this._rightNode = null;
  39069. this._bottomNode = null;
  39070. };
  39071. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  39072. get: function () {
  39073. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  39074. },
  39075. enumerable: true,
  39076. configurable: true
  39077. });
  39078. PackedRect.prototype.evalFreeSize = function (size) {
  39079. var levelSize = 0;
  39080. if (!this.isUsed) {
  39081. if (this._initialSize) {
  39082. levelSize = this._initialSize.surface;
  39083. }
  39084. else {
  39085. levelSize = this._size.surface;
  39086. }
  39087. }
  39088. if (this._rightNode) {
  39089. levelSize += this._rightNode.evalFreeSize(0);
  39090. }
  39091. if (this._bottomNode) {
  39092. levelSize += this._bottomNode.evalFreeSize(0);
  39093. }
  39094. return levelSize + size;
  39095. };
  39096. return PackedRect;
  39097. }());
  39098. BABYLON.PackedRect = PackedRect;
  39099. /**
  39100. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  39101. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  39102. * 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.
  39103. */
  39104. var RectPackingMap = (function (_super) {
  39105. __extends(RectPackingMap, _super);
  39106. /**
  39107. * Create an instance of the object with a dimension using the given size
  39108. * @param size The dimension of the rectangle that will contain all the sub ones.
  39109. */
  39110. function RectPackingMap(size) {
  39111. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  39112. this._root = this;
  39113. }
  39114. /**
  39115. * Add a rectangle, finding the best location to store it into the map
  39116. * @param size the dimension of the rectangle to store
  39117. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  39118. */
  39119. RectPackingMap.prototype.addRect = function (size) {
  39120. var node = this.findAndSplitNode(size);
  39121. return node;
  39122. };
  39123. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  39124. /**
  39125. * Return the current space free normalized between [0;1]
  39126. * @returns {}
  39127. */
  39128. get: function () {
  39129. var freeSize = 0;
  39130. freeSize = this.evalFreeSize(freeSize);
  39131. return freeSize / (this._size.width * this._size.height);
  39132. },
  39133. enumerable: true,
  39134. configurable: true
  39135. });
  39136. return RectPackingMap;
  39137. }(PackedRect));
  39138. BABYLON.RectPackingMap = RectPackingMap;
  39139. })(BABYLON || (BABYLON = {}));
  39140. //# sourceMappingURL=../Tools/babylon.rectPackingMap.js.map
  39141. var BABYLON;
  39142. (function (BABYLON) {
  39143. var DynamicFloatArrayElementInfo = (function () {
  39144. function DynamicFloatArrayElementInfo() {
  39145. }
  39146. return DynamicFloatArrayElementInfo;
  39147. }());
  39148. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  39149. /**
  39150. * 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.
  39151. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  39152. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  39153. * 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.
  39154. * 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.
  39155. * 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".
  39156. */
  39157. var DynamicFloatArray = (function () {
  39158. /**
  39159. * Construct an instance of the dynamic float array
  39160. * @param stride size of one element in float (i.e. not bytes!)
  39161. * @param initialElementCount the number of available entries at construction
  39162. */
  39163. function DynamicFloatArray(stride, initialElementCount) {
  39164. this.compareValueOffset = null;
  39165. this.sortingAscending = true;
  39166. this._stride = stride;
  39167. this.buffer = new Float32Array(stride * initialElementCount);
  39168. this._lastUsed = 0;
  39169. this._firstFree = 0;
  39170. this._allEntries = new Array(initialElementCount);
  39171. this._freeEntries = new Array(initialElementCount);
  39172. for (var i = 0; i < initialElementCount; i++) {
  39173. var element = new DynamicFloatArrayElementInfo();
  39174. element.offset = i * stride;
  39175. this._allEntries[i] = element;
  39176. this._freeEntries[initialElementCount - i - 1] = element;
  39177. }
  39178. }
  39179. /**
  39180. * Allocate an element in the array.
  39181. * @return the element info instance that contains the offset into the main buffer of the element's location.
  39182. * Beware, this offset may change when you call pack()
  39183. */
  39184. DynamicFloatArray.prototype.allocElement = function () {
  39185. if (this._freeEntries.length === 0) {
  39186. this._growBuffer();
  39187. }
  39188. var el = this._freeEntries.pop();
  39189. this._lastUsed = Math.max(el.offset, this._lastUsed);
  39190. if (el.offset === this._firstFree) {
  39191. if (this._freeEntries.length > 0) {
  39192. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  39193. }
  39194. else {
  39195. this._firstFree += this._stride;
  39196. }
  39197. }
  39198. return el;
  39199. };
  39200. /**
  39201. * Free the element corresponding to the given element info
  39202. * @param elInfo the element that describe the allocated element
  39203. */
  39204. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  39205. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  39206. this._freeEntries.push(elInfo);
  39207. };
  39208. /**
  39209. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  39210. * 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().
  39211. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  39212. */
  39213. DynamicFloatArray.prototype.pack = function () {
  39214. // no free slot? no need to pack
  39215. if (this._freeEntries.length === 0) {
  39216. return this.buffer;
  39217. }
  39218. // If the buffer is already packed the last used will always be lower than the first free
  39219. // 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.
  39220. if (this._lastUsed < this._firstFree) {
  39221. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  39222. return elementsBuffer_1;
  39223. }
  39224. var s = this._stride;
  39225. // 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
  39226. var lastFree = new DynamicFloatArrayElementInfo();
  39227. lastFree.offset = this.totalElementCount * s;
  39228. this._freeEntries.push(lastFree);
  39229. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  39230. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  39231. var firstFreeSlotOffset = sortedFree[0].offset;
  39232. var freeZoneSize = 1;
  39233. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  39234. var prevOffset = sortedFree[0].offset;
  39235. for (var i = 1; i < sortedFree.length; i++) {
  39236. // 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
  39237. if (firstFreeSlotOffset >= occupiedZoneSize) {
  39238. break;
  39239. }
  39240. var curFree = sortedFree[i];
  39241. var curOffset = curFree.offset;
  39242. // Compute the distance between this offset and the previous
  39243. var distance = curOffset - prevOffset;
  39244. // If the distance is the stride size, they are adjacent, it good, move to the next
  39245. if (distance === s) {
  39246. // Free zone is one element bigger
  39247. ++freeZoneSize;
  39248. // as we're about to iterate to the next, the cur becomes the previous...
  39249. prevOffset = curOffset;
  39250. continue;
  39251. }
  39252. // Distance is bigger, which means there's x element between the previous free and this one
  39253. var usedRange = (distance / s) - 1;
  39254. // Two cases the free zone is smaller than the data to move or bigger
  39255. // Copy what can fit in the free zone
  39256. var curMoveOffset = curOffset - s;
  39257. var copyCount = Math.min(freeZoneSize, usedRange);
  39258. for (var j = 0; j < copyCount; j++) {
  39259. var freeI = firstFreeSlotOffset / s;
  39260. var curI = curMoveOffset / s;
  39261. var moveEl = sortedAll[curI];
  39262. this._moveElement(moveEl, firstFreeSlotOffset);
  39263. var replacedEl = sortedAll[freeI];
  39264. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  39265. replacedEl.offset = curMoveOffset;
  39266. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  39267. sortedAll[freeI] = moveEl;
  39268. sortedAll[curI] = replacedEl;
  39269. curMoveOffset -= s;
  39270. firstFreeSlotOffset += s;
  39271. }
  39272. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  39273. if (freeZoneSize <= usedRange) {
  39274. firstFreeSlotOffset = curMoveOffset + s;
  39275. freeZoneSize = 1 + copyCount;
  39276. }
  39277. else {
  39278. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  39279. }
  39280. // as we're about to iterate to the next, the cur becomes the previous...
  39281. prevOffset = curOffset;
  39282. }
  39283. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  39284. this._lastUsed = firstFreeSlotOffset - s;
  39285. this._firstFree = firstFreeSlotOffset;
  39286. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  39287. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  39288. this._allEntries = sortedAll;
  39289. return elementsBuffer;
  39290. };
  39291. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  39292. for (var i = 0; i < this._stride; i++) {
  39293. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  39294. }
  39295. element.offset = destOffset;
  39296. };
  39297. DynamicFloatArray.prototype._growBuffer = function () {
  39298. // Allocate the new buffer with 50% more entries, copy the content of the current one
  39299. var newElCount = Math.floor(this.totalElementCount * 1.5);
  39300. var newBuffer = new Float32Array(newElCount * this._stride);
  39301. newBuffer.set(this.buffer);
  39302. var curCount = this.totalElementCount;
  39303. var addedCount = newElCount - this.totalElementCount;
  39304. for (var i = 0; i < addedCount; i++) {
  39305. var element = new DynamicFloatArrayElementInfo();
  39306. element.offset = (curCount + i) * this.stride;
  39307. this._allEntries.push(element);
  39308. this._freeEntries[addedCount - i - 1] = element;
  39309. }
  39310. this._firstFree = curCount * this.stride;
  39311. this.buffer = newBuffer;
  39312. };
  39313. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  39314. /**
  39315. * Get the total count of entries that can fit in the current buffer
  39316. * @returns the elements count
  39317. */
  39318. get: function () {
  39319. return this._allEntries.length;
  39320. },
  39321. enumerable: true,
  39322. configurable: true
  39323. });
  39324. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  39325. /**
  39326. * Get the count of free entries that can still be allocated without resizing the buffer
  39327. * @returns the free elements count
  39328. */
  39329. get: function () {
  39330. return this._freeEntries.length;
  39331. },
  39332. enumerable: true,
  39333. configurable: true
  39334. });
  39335. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  39336. /**
  39337. * Get the count of allocated elements
  39338. * @returns the allocated elements count
  39339. */
  39340. get: function () {
  39341. return this._allEntries.length - this._freeEntries.length;
  39342. },
  39343. enumerable: true,
  39344. configurable: true
  39345. });
  39346. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  39347. /**
  39348. * Return the size of one element in float
  39349. * @returns the size in float
  39350. */
  39351. get: function () {
  39352. return this._stride;
  39353. },
  39354. enumerable: true,
  39355. configurable: true
  39356. });
  39357. DynamicFloatArray.prototype.sort = function () {
  39358. var _this = this;
  39359. if (!this.compareValueOffset) {
  39360. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  39361. }
  39362. var count = this.usedElementCount;
  39363. // Do we have to (re)create the sort table?
  39364. if (!this._sortTable || this._sortTable.length < count) {
  39365. // 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...
  39366. var newCount = Math.min(this.totalElementCount, count * 2);
  39367. this._sortTable = new Array(newCount);
  39368. }
  39369. if (!this._sortedTable || this._sortedTable.length !== count) {
  39370. this._sortedTable = new Array(count);
  39371. }
  39372. // Because, you know...
  39373. this.pack();
  39374. //let stride = this.stride;
  39375. //for (let i = 0; i < count; i++) {
  39376. // let si = this._sortTable[i];
  39377. // if (!si) {
  39378. // si = new SortInfo();
  39379. // this._sortTable[i] = si;
  39380. // }
  39381. // si.entry = this._allEntries[i];
  39382. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  39383. // si.swapedOffset = null;
  39384. // this._sortedTable[i] = si;
  39385. //}
  39386. var curOffset = 0;
  39387. var stride = this.stride;
  39388. for (var i = 0; i < count; i++, curOffset += stride) {
  39389. var si = this._sortTable[i];
  39390. if (!si) {
  39391. si = new SortInfo();
  39392. this._sortTable[i] = si;
  39393. }
  39394. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  39395. si.offset = curOffset;
  39396. si.swapedOffset = null;
  39397. this._sortedTable[i] = si;
  39398. }
  39399. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  39400. if (this.sortingAscending) {
  39401. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  39402. }
  39403. else {
  39404. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  39405. }
  39406. var swapElements = function (src, dst) {
  39407. for (var i = 0; i < stride; i++) {
  39408. var tps = _this.buffer[dst + i];
  39409. _this.buffer[dst + i] = _this.buffer[src + i];
  39410. _this.buffer[src + i] = tps;
  39411. }
  39412. };
  39413. // 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:
  39414. // 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),
  39415. // and I still want something with a good algorithm complexity.
  39416. // 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,
  39417. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  39418. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  39419. // 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
  39420. // until we find a SortInfo object without a swapedOffset which means we got the right location
  39421. // 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
  39422. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  39423. for (var i = 0; i < count; i++) {
  39424. // Get the element to move
  39425. var sourceSI = this._sortedTable[i];
  39426. var destSI = this._sortTable[i];
  39427. var sourceOff = sourceSI.offset;
  39428. // If the source changed location, find the new one
  39429. if (sourceSI.swapedOffset) {
  39430. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  39431. var curSI = sourceSI;
  39432. while (curSI.swapedOffset) {
  39433. curSI = this._sortTable[curSI.swapedOffset / stride];
  39434. }
  39435. // Finally get the right location
  39436. sourceOff = curSI.offset;
  39437. }
  39438. // Tag the element being replaced with its new location
  39439. destSI.swapedOffset = sourceOff;
  39440. // Swap elements (only if needed)
  39441. if (sourceOff !== destSI.offset) {
  39442. swapElements(sourceOff, destSI.offset);
  39443. }
  39444. // Update the offset in the corresponding DFAE
  39445. //sourceSI.entry.offset = destSI.entry.offset;
  39446. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  39447. }
  39448. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  39449. return true;
  39450. };
  39451. return DynamicFloatArray;
  39452. }());
  39453. BABYLON.DynamicFloatArray = DynamicFloatArray;
  39454. var SortInfo = (function () {
  39455. function SortInfo() {
  39456. this.compareData = this.offset = this.swapedOffset = null;
  39457. }
  39458. return SortInfo;
  39459. }());
  39460. })(BABYLON || (BABYLON = {}));
  39461. //# sourceMappingURL=../Tools/babylon.dynamicFloatArray.js.map
  39462. var BABYLON;
  39463. (function (BABYLON) {
  39464. /**
  39465. * This class given information about a given character.
  39466. */
  39467. var CharInfo = (function () {
  39468. function CharInfo() {
  39469. }
  39470. return CharInfo;
  39471. }());
  39472. BABYLON.CharInfo = CharInfo;
  39473. var FontTexture = (function (_super) {
  39474. __extends(FontTexture, _super);
  39475. /**
  39476. * Create a new instance of the FontTexture class
  39477. * @param name the name of the texture
  39478. * @param font the font to use, use the W3C CSS notation
  39479. * @param scene the scene that owns the texture
  39480. * @param maxCharCount the approximative maximum count of characters that could fit in the texture. This is an approximation because most of the fonts are proportional (each char has its own Width). The 'W' character's width is used to compute the size of the texture based on the given maxCharCount
  39481. * @param samplingMode the texture sampling mode
  39482. * @param superSample if true the FontTexture will be created with a font of a size twice bigger than the given one but all properties (lineHeight, charWidth, etc.) will be according to the original size. This is made to improve the text quality.
  39483. */
  39484. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
  39485. if (maxCharCount === void 0) { maxCharCount = 200; }
  39486. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39487. if (superSample === void 0) { superSample = false; }
  39488. if (signedDistanceField === void 0) { signedDistanceField = false; }
  39489. _super.call(this, null, scene, true, false, samplingMode);
  39490. this._charInfos = {};
  39491. this._curCharCount = 0;
  39492. this._lastUpdateCharCount = -1;
  39493. this._usedCounter = 1;
  39494. this.name = name;
  39495. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39496. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39497. this._sdfScale = 8;
  39498. this._signedDistanceField = signedDistanceField;
  39499. this._superSample = false;
  39500. // SDF will use supersample no matter what, the resolution is otherwise too poor to produce correct result
  39501. if (superSample || signedDistanceField) {
  39502. var sfont = this.getSuperSampleFont(font);
  39503. if (sfont) {
  39504. this._superSample = true;
  39505. font = sfont;
  39506. }
  39507. }
  39508. // First canvas creation to determine the size of the texture to create
  39509. this._canvas = document.createElement("canvas");
  39510. this._context = this._canvas.getContext("2d");
  39511. this._context.font = font;
  39512. this._context.fillStyle = "white";
  39513. this._context.textBaseline = "top";
  39514. this._cachedFontId = null;
  39515. var res = this.getFontHeight(font);
  39516. this._lineHeightSuper = res.height + 4;
  39517. this._lineHeight = this._superSample ? (Math.ceil(this._lineHeightSuper / 2)) : this._lineHeightSuper;
  39518. this._offset = res.offset - 1;
  39519. this._xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  39520. this._yMargin = this._xMargin;
  39521. var maxCharWidth = this._context.measureText("W").width;
  39522. this._spaceWidthSuper = this._context.measureText(" ").width;
  39523. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  39524. // This is an approximate size, but should always be able to fit at least the maxCharCount
  39525. var totalEstSurface = (this._lineHeightSuper + this._yMargin) * (maxCharWidth + this._xMargin) * maxCharCount;
  39526. var edge = Math.sqrt(totalEstSurface);
  39527. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  39528. // Create the texture that will store the font characters
  39529. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  39530. var textureSize = this.getSize();
  39531. this.hasAlpha = this._signedDistanceField === false;
  39532. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  39533. this._canvas = document.createElement("canvas");
  39534. this._canvas.width = textureSize.width;
  39535. this._canvas.height = textureSize.height;
  39536. this._context = this._canvas.getContext("2d");
  39537. this._context.textBaseline = "top";
  39538. this._context.font = font;
  39539. this._context.fillStyle = "white";
  39540. this._context.imageSmoothingEnabled = false;
  39541. this._context.clearRect(0, 0, textureSize.width, textureSize.height);
  39542. // Create a canvas for the signed distance field mode, we only have to store one char, the purpose is to render a char scaled _sdfScale times
  39543. // into this 2D context, then get the bitmap data, create the sdf char and push the result in the _context (which hold the whole Font Texture content)
  39544. // So you can see this context as an intermediate one, because it is.
  39545. if (this._signedDistanceField) {
  39546. var sdfC = document.createElement("canvas");
  39547. var s = this._sdfScale;
  39548. sdfC.width = maxCharWidth * s;
  39549. sdfC.height = this._lineHeightSuper * s;
  39550. var sdfCtx = sdfC.getContext("2d");
  39551. sdfCtx.scale(s, s);
  39552. sdfCtx.textBaseline = "top";
  39553. sdfCtx.font = font;
  39554. sdfCtx.fillStyle = "white";
  39555. sdfCtx.imageSmoothingEnabled = false;
  39556. this._sdfCanvas = sdfC;
  39557. this._sdfContext = sdfCtx;
  39558. }
  39559. this._currentFreePosition = BABYLON.Vector2.Zero();
  39560. // Add the basic ASCII based characters
  39561. for (var i = 0x20; i < 0x7F; i++) {
  39562. var c = String.fromCharCode(i);
  39563. this.getChar(c);
  39564. }
  39565. this.update();
  39566. }
  39567. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  39568. get: function () {
  39569. return this._superSample;
  39570. },
  39571. enumerable: true,
  39572. configurable: true
  39573. });
  39574. Object.defineProperty(FontTexture.prototype, "isSignedDistanceField", {
  39575. get: function () {
  39576. return this._signedDistanceField;
  39577. },
  39578. enumerable: true,
  39579. configurable: true
  39580. });
  39581. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  39582. get: function () {
  39583. return this._spaceWidth;
  39584. },
  39585. enumerable: true,
  39586. configurable: true
  39587. });
  39588. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  39589. get: function () {
  39590. return this._lineHeight;
  39591. },
  39592. enumerable: true,
  39593. configurable: true
  39594. });
  39595. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  39596. if (supersample === void 0) { supersample = false; }
  39597. if (signedDistanceField === void 0) { signedDistanceField = false; }
  39598. var s = scene;
  39599. if (!s.__fontTextureCache__) {
  39600. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  39601. }
  39602. var dic = s.__fontTextureCache__;
  39603. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  39604. var ft = dic.get(lfn);
  39605. if (ft) {
  39606. ++ft._usedCounter;
  39607. return ft;
  39608. }
  39609. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample, signedDistanceField);
  39610. ft._cachedFontId = lfn;
  39611. dic.add(lfn, ft);
  39612. return ft;
  39613. };
  39614. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  39615. if (supersample === void 0) { supersample = false; }
  39616. if (signedDistanceField === void 0) { signedDistanceField = false; }
  39617. var s = scene;
  39618. var dic = s.__fontTextureCache__;
  39619. if (!dic) {
  39620. return;
  39621. }
  39622. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  39623. var font = dic.get(lfn);
  39624. if (--font._usedCounter === 0) {
  39625. dic.remove(lfn);
  39626. font.dispose();
  39627. }
  39628. };
  39629. /**
  39630. * Make sure the given char is present in the font map.
  39631. * @param char the character to get or add
  39632. * @return the CharInfo instance corresponding to the given character
  39633. */
  39634. FontTexture.prototype.getChar = function (char) {
  39635. if (char.length !== 1) {
  39636. return null;
  39637. }
  39638. var info = this._charInfos[char];
  39639. if (info) {
  39640. return info;
  39641. }
  39642. info = new CharInfo();
  39643. var measure = this._context.measureText(char);
  39644. var textureSize = this.getSize();
  39645. // we reached the end of the current line?
  39646. var width = Math.round(measure.width);
  39647. if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
  39648. this._currentFreePosition.x = 0;
  39649. this._currentFreePosition.y += this._lineHeightSuper + this._yMargin;
  39650. // No more room?
  39651. if (this._currentFreePosition.y > textureSize.height) {
  39652. return this.getChar("!");
  39653. }
  39654. }
  39655. // In sdf mode we render the character in an intermediate 2D context which scale the character this._sdfScale times (which is required to compute the sdf map accurately)
  39656. if (this._signedDistanceField) {
  39657. this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
  39658. this._sdfContext.fillText(char, 0, -this._offset);
  39659. var data = this._sdfContext.getImageData(0, 0, width * this._sdfScale, this._sdfCanvas.height);
  39660. var res = this._computeSDFChar(data);
  39661. this._context.putImageData(res, this._currentFreePosition.x, this._currentFreePosition.y);
  39662. }
  39663. else {
  39664. // Draw the character in the HTML canvas
  39665. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  39666. }
  39667. // Fill the CharInfo object
  39668. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  39669. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  39670. if (this._signedDistanceField) {
  39671. var off = 1 / textureSize.width;
  39672. info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
  39673. info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
  39674. }
  39675. info.charWidth = this._superSample ? (width / 2) : width;
  39676. // Add the info structure
  39677. this._charInfos[char] = info;
  39678. this._curCharCount++;
  39679. // Set the next position
  39680. this._currentFreePosition.x += width + this._xMargin;
  39681. return info;
  39682. };
  39683. FontTexture.prototype._computeSDFChar = function (source) {
  39684. var scl = this._sdfScale;
  39685. var sw = source.width;
  39686. var sh = source.height;
  39687. var dw = sw / scl;
  39688. var dh = sh / scl;
  39689. var roffx = 0;
  39690. var roffy = 0;
  39691. // We shouldn't look beyond half of the biggest between width and height
  39692. var radius = scl;
  39693. var br = radius - 1;
  39694. var lookupSrc = function (dx, dy, offX, offY, lookVis) {
  39695. var sx = dx * scl;
  39696. var sy = dy * scl;
  39697. // Looking out of the area? return true to make the test going on
  39698. if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
  39699. return true;
  39700. }
  39701. // Get the pixel we want
  39702. var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
  39703. var res = (val > 0) === lookVis;
  39704. if (!res) {
  39705. roffx = offX;
  39706. roffy = offY;
  39707. }
  39708. return res;
  39709. };
  39710. var lookupArea = function (dx, dy, lookVis) {
  39711. // Fast rejection test, if we have the same result in N, S, W, E at a distance which is the radius-1 then it means the data will be consistent in this area. That's because we've scale the rendering of the letter "radius" times, so a letter's pixel will be at least radius wide
  39712. if (lookupSrc(dx, dy, 0, br, lookVis) &&
  39713. lookupSrc(dx, dy, 0, -br, lookVis) &&
  39714. lookupSrc(dx, dy, -br, 0, lookVis) &&
  39715. lookupSrc(dx, dy, br, 0, lookVis)) {
  39716. return 0;
  39717. }
  39718. for (var i = 1; i <= radius; i++) {
  39719. // Quick test N, S, W, E
  39720. if (!lookupSrc(dx, dy, 0, i, lookVis) || !lookupSrc(dx, dy, 0, -i, lookVis) || !lookupSrc(dx, dy, -i, 0, lookVis) || !lookupSrc(dx, dy, i, 0, lookVis)) {
  39721. return i * i; // Squared Distance is simple to compute in this case
  39722. }
  39723. // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
  39724. for (var j = 1; j <= i; j++) {
  39725. if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
  39726. !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
  39727. !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
  39728. !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
  39729. // We found the nearest texel having and opposite state, store the squared length
  39730. var res_1 = (i * i) + (j * j);
  39731. var count = 1;
  39732. // To improve quality we will sample the texels around this one, so it's 8 samples, we consider only the one having an opposite state, add them to the current res and will will compute the average at the end
  39733. if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
  39734. res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
  39735. ++count;
  39736. }
  39737. if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
  39738. res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
  39739. ++count;
  39740. }
  39741. if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
  39742. res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
  39743. ++count;
  39744. }
  39745. if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
  39746. res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
  39747. ++count;
  39748. }
  39749. if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
  39750. res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
  39751. ++count;
  39752. }
  39753. if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
  39754. res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
  39755. ++count;
  39756. }
  39757. if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
  39758. res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
  39759. ++count;
  39760. }
  39761. if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
  39762. res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
  39763. ++count;
  39764. }
  39765. // Compute the average based on the accumulated distance
  39766. return res_1 / count;
  39767. }
  39768. }
  39769. }
  39770. return 0;
  39771. };
  39772. var tmp = new Array(dw * dh);
  39773. for (var y = 0; y < dh; y++) {
  39774. for (var x = 0; x < dw; x++) {
  39775. var curState = lookupSrc(x, y, 0, 0, true);
  39776. var d = lookupArea(x, y, curState);
  39777. if (d === 0) {
  39778. d = radius * radius * 2;
  39779. }
  39780. tmp[(y * dw) + x] = curState ? d : -d;
  39781. }
  39782. }
  39783. var res = this._context.createImageData(dw, dh);
  39784. var size = dw * dh;
  39785. for (var j = 0; j < size; j++) {
  39786. var d = tmp[j];
  39787. var sign = (d < 0) ? -1 : 1;
  39788. d = Math.sqrt(Math.abs(d)) * sign;
  39789. d *= 127.5 / radius;
  39790. d += 127.5;
  39791. if (d < 0) {
  39792. d = 0;
  39793. }
  39794. else if (d > 255) {
  39795. d = 255;
  39796. }
  39797. d += 0.5;
  39798. res.data[j * 4 + 0] = d;
  39799. res.data[j * 4 + 1] = d;
  39800. res.data[j * 4 + 2] = d;
  39801. res.data[j * 4 + 3] = 255;
  39802. }
  39803. return res;
  39804. };
  39805. FontTexture.prototype.measureText = function (text, tabulationSize) {
  39806. if (tabulationSize === void 0) { tabulationSize = 4; }
  39807. var maxWidth = 0;
  39808. var curWidth = 0;
  39809. var lineCount = 1;
  39810. var charxpos = 0;
  39811. // Parse each char of the string
  39812. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  39813. var char = text_1[_i];
  39814. // Next line feed?
  39815. if (char === "\n") {
  39816. maxWidth = Math.max(maxWidth, curWidth);
  39817. charxpos = 0;
  39818. curWidth = 0;
  39819. ++lineCount;
  39820. continue;
  39821. }
  39822. // Tabulation ?
  39823. if (char === "\t") {
  39824. var nextPos = charxpos + tabulationSize;
  39825. nextPos = nextPos - (nextPos % tabulationSize);
  39826. curWidth += (nextPos - charxpos) * this.spaceWidth;
  39827. charxpos = nextPos;
  39828. continue;
  39829. }
  39830. if (char < " ") {
  39831. continue;
  39832. }
  39833. curWidth += this.getChar(char).charWidth;
  39834. ++charxpos;
  39835. }
  39836. maxWidth = Math.max(maxWidth, curWidth);
  39837. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  39838. };
  39839. FontTexture.prototype.getSuperSampleFont = function (font) {
  39840. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  39841. var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z]+?)\s*$/;
  39842. var res = font.toLocaleLowerCase().match(regex);
  39843. if (res == null) {
  39844. return null;
  39845. }
  39846. var size = parseInt(res[4]);
  39847. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  39848. var newFont = "";
  39849. for (var j = 1; j < res.length; j++) {
  39850. if (res[j] != null) {
  39851. newFont += res[j] + " ";
  39852. }
  39853. }
  39854. return newFont;
  39855. };
  39856. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  39857. FontTexture.prototype.getFontHeight = function (font) {
  39858. var fontDraw = document.createElement("canvas");
  39859. var ctx = fontDraw.getContext('2d');
  39860. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  39861. ctx.textBaseline = 'top';
  39862. ctx.fillStyle = 'white';
  39863. ctx.font = font;
  39864. ctx.fillText('jH|', 0, 0);
  39865. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  39866. var start = -1;
  39867. var end = -1;
  39868. for (var row = 0; row < fontDraw.height; row++) {
  39869. for (var column = 0; column < fontDraw.width; column++) {
  39870. var index = (row * fontDraw.width + column) * 4;
  39871. if (pixels[index] === 0) {
  39872. if (column === fontDraw.width - 1 && start !== -1) {
  39873. end = row;
  39874. row = fontDraw.height;
  39875. break;
  39876. }
  39877. continue;
  39878. }
  39879. else {
  39880. if (start === -1) {
  39881. start = row;
  39882. }
  39883. break;
  39884. }
  39885. }
  39886. }
  39887. return { height: (end - start) + 1, offset: start - 1 };
  39888. };
  39889. Object.defineProperty(FontTexture.prototype, "canRescale", {
  39890. get: function () {
  39891. return false;
  39892. },
  39893. enumerable: true,
  39894. configurable: true
  39895. });
  39896. FontTexture.prototype.getContext = function () {
  39897. return this._context;
  39898. };
  39899. /**
  39900. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  39901. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  39902. */
  39903. FontTexture.prototype.update = function () {
  39904. // Update only if there's new char added since the previous update
  39905. if (this._lastUpdateCharCount < this._curCharCount) {
  39906. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  39907. this._lastUpdateCharCount = this._curCharCount;
  39908. }
  39909. };
  39910. // cloning should be prohibited, there's no point to duplicate this texture at all
  39911. FontTexture.prototype.clone = function () {
  39912. return null;
  39913. };
  39914. /**
  39915. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  39916. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  39917. */
  39918. FontTexture.prototype.incCachedFontTextureCounter = function () {
  39919. ++this._usedCounter;
  39920. };
  39921. /**
  39922. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  39923. */
  39924. FontTexture.prototype.decCachedFontTextureCounter = function () {
  39925. var s = this.getScene();
  39926. var dic = s.__fontTextureCache__;
  39927. if (!dic) {
  39928. return;
  39929. }
  39930. if (--this._usedCounter === 0) {
  39931. dic.remove(this._cachedFontId);
  39932. this.dispose();
  39933. }
  39934. };
  39935. return FontTexture;
  39936. }(BABYLON.Texture));
  39937. BABYLON.FontTexture = FontTexture;
  39938. })(BABYLON || (BABYLON = {}));
  39939. //# sourceMappingURL=../../Materials/Textures/babylon.fontTexture.js.map
  39940. var BABYLON;
  39941. (function (BABYLON) {
  39942. var MapTexture = (function (_super) {
  39943. __extends(MapTexture, _super);
  39944. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  39945. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39946. if (useMipMap === void 0) { useMipMap = false; }
  39947. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  39948. this.name = name;
  39949. this._size = size;
  39950. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39951. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39952. // Create the rectPackMap that will allocate portion of the texture
  39953. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  39954. // Create the texture that will store the content
  39955. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  39956. }
  39957. /**
  39958. * Allocate a rectangle of a given size in the texture map
  39959. * @param size the size of the rectangle to allocation
  39960. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  39961. */
  39962. MapTexture.prototype.allocateRect = function (size) {
  39963. return this._rectPackingMap.addRect(size);
  39964. };
  39965. /**
  39966. * Free a given rectangle from the texture map
  39967. * @param rectInfo the instance corresponding to the rect to free.
  39968. */
  39969. MapTexture.prototype.freeRect = function (rectInfo) {
  39970. if (rectInfo) {
  39971. rectInfo.freeContent();
  39972. }
  39973. };
  39974. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  39975. /**
  39976. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  39977. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  39978. * @returns {}
  39979. */
  39980. get: function () {
  39981. return this._rectPackingMap.freeSpace;
  39982. },
  39983. enumerable: true,
  39984. configurable: true
  39985. });
  39986. /**
  39987. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  39988. * 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.
  39989. * Don't forget to call unbindTexture when you're done rendering
  39990. * @param rect the zone to render to
  39991. * @param clear true to clear the portion's color/depth data
  39992. */
  39993. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  39994. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  39995. };
  39996. /**
  39997. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  39998. * 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.
  39999. * Don't forget to call unbindTexture when you're done rendering
  40000. * @param pos the position into the texture
  40001. * @param size the portion to fit the clip space to
  40002. * @param clear true to clear the portion's color/depth data
  40003. */
  40004. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  40005. var engine = this.getScene().getEngine();
  40006. engine.bindFramebuffer(this._texture);
  40007. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  40008. if (clear) {
  40009. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  40010. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  40011. }
  40012. };
  40013. /**
  40014. * Unbind the texture map from the rendering engine.
  40015. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  40016. * @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.
  40017. */
  40018. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  40019. // Dump ?
  40020. if (dumpForDebug) {
  40021. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  40022. }
  40023. var engine = this.getScene().getEngine();
  40024. if (this._replacedViewport) {
  40025. engine.setViewport(this._replacedViewport);
  40026. this._replacedViewport = null;
  40027. }
  40028. engine.unBindFramebuffer(this._texture);
  40029. };
  40030. Object.defineProperty(MapTexture.prototype, "canRescale", {
  40031. get: function () {
  40032. return false;
  40033. },
  40034. enumerable: true,
  40035. configurable: true
  40036. });
  40037. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  40038. // Anyway, there's not much point to use this method for this kind of texture I guess
  40039. MapTexture.prototype.clone = function () {
  40040. return null;
  40041. };
  40042. return MapTexture;
  40043. }(BABYLON.Texture));
  40044. BABYLON.MapTexture = MapTexture;
  40045. })(BABYLON || (BABYLON = {}));
  40046. //# sourceMappingURL=../../Materials/Textures/babylon.mapTexture.js.map
  40047. var BABYLON;
  40048. (function (BABYLON) {
  40049. var ShaderMaterial = (function (_super) {
  40050. __extends(ShaderMaterial, _super);
  40051. function ShaderMaterial(name, scene, shaderPath, options) {
  40052. _super.call(this, name, scene);
  40053. this._textures = {};
  40054. this._textureArrays = {};
  40055. this._floats = {};
  40056. this._floatsArrays = {};
  40057. this._colors3 = {};
  40058. this._colors4 = {};
  40059. this._vectors2 = {};
  40060. this._vectors3 = {};
  40061. this._vectors4 = {};
  40062. this._matrices = {};
  40063. this._matrices3x3 = {};
  40064. this._matrices2x2 = {};
  40065. this._vectors3Arrays = {};
  40066. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  40067. this._shaderPath = shaderPath;
  40068. options.needAlphaBlending = options.needAlphaBlending || false;
  40069. options.needAlphaTesting = options.needAlphaTesting || false;
  40070. options.attributes = options.attributes || ["position", "normal", "uv"];
  40071. options.uniforms = options.uniforms || ["worldViewProjection"];
  40072. options.samplers = options.samplers || [];
  40073. options.defines = options.defines || [];
  40074. this._options = options;
  40075. }
  40076. ShaderMaterial.prototype.needAlphaBlending = function () {
  40077. return this._options.needAlphaBlending;
  40078. };
  40079. ShaderMaterial.prototype.needAlphaTesting = function () {
  40080. return this._options.needAlphaTesting;
  40081. };
  40082. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  40083. if (this._options.uniforms.indexOf(uniformName) === -1) {
  40084. this._options.uniforms.push(uniformName);
  40085. }
  40086. };
  40087. ShaderMaterial.prototype.setTexture = function (name, texture) {
  40088. if (this._options.samplers.indexOf(name) === -1) {
  40089. this._options.samplers.push(name);
  40090. }
  40091. this._textures[name] = texture;
  40092. return this;
  40093. };
  40094. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  40095. if (this._options.samplers.indexOf(name) === -1) {
  40096. this._options.samplers.push(name);
  40097. }
  40098. this._checkUniform(name);
  40099. this._textureArrays[name] = textures;
  40100. return this;
  40101. };
  40102. ShaderMaterial.prototype.setFloat = function (name, value) {
  40103. this._checkUniform(name);
  40104. this._floats[name] = value;
  40105. return this;
  40106. };
  40107. ShaderMaterial.prototype.setFloats = function (name, value) {
  40108. this._checkUniform(name);
  40109. this._floatsArrays[name] = value;
  40110. return this;
  40111. };
  40112. ShaderMaterial.prototype.setColor3 = function (name, value) {
  40113. this._checkUniform(name);
  40114. this._colors3[name] = value;
  40115. return this;
  40116. };
  40117. ShaderMaterial.prototype.setColor4 = function (name, value) {
  40118. this._checkUniform(name);
  40119. this._colors4[name] = value;
  40120. return this;
  40121. };
  40122. ShaderMaterial.prototype.setVector2 = function (name, value) {
  40123. this._checkUniform(name);
  40124. this._vectors2[name] = value;
  40125. return this;
  40126. };
  40127. ShaderMaterial.prototype.setVector3 = function (name, value) {
  40128. this._checkUniform(name);
  40129. this._vectors3[name] = value;
  40130. return this;
  40131. };
  40132. ShaderMaterial.prototype.setVector4 = function (name, value) {
  40133. this._checkUniform(name);
  40134. this._vectors4[name] = value;
  40135. return this;
  40136. };
  40137. ShaderMaterial.prototype.setMatrix = function (name, value) {
  40138. this._checkUniform(name);
  40139. this._matrices[name] = value;
  40140. return this;
  40141. };
  40142. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  40143. this._checkUniform(name);
  40144. this._matrices3x3[name] = value;
  40145. return this;
  40146. };
  40147. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  40148. this._checkUniform(name);
  40149. this._matrices2x2[name] = value;
  40150. return this;
  40151. };
  40152. ShaderMaterial.prototype.setArray3 = function (name, value) {
  40153. this._checkUniform(name);
  40154. this._vectors3Arrays[name] = value;
  40155. return this;
  40156. };
  40157. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  40158. if (!mesh) {
  40159. return true;
  40160. }
  40161. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  40162. return false;
  40163. }
  40164. return false;
  40165. };
  40166. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  40167. var scene = this.getScene();
  40168. var engine = scene.getEngine();
  40169. if (!this.checkReadyOnEveryCall) {
  40170. if (this._renderId === scene.getRenderId()) {
  40171. if (this._checkCache(scene, mesh, useInstances)) {
  40172. return true;
  40173. }
  40174. }
  40175. }
  40176. // Instances
  40177. var defines = [];
  40178. var fallbacks = new BABYLON.EffectFallbacks();
  40179. if (useInstances) {
  40180. defines.push("#define INSTANCES");
  40181. }
  40182. for (var index = 0; index < this._options.defines.length; index++) {
  40183. defines.push(this._options.defines[index]);
  40184. }
  40185. // Bones
  40186. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  40187. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40188. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40189. fallbacks.addCPUSkinningFallback(0, mesh);
  40190. }
  40191. // Alpha test
  40192. if (engine.getAlphaTesting()) {
  40193. defines.push("#define ALPHATEST");
  40194. }
  40195. var previousEffect = this._effect;
  40196. var join = defines.join("\n");
  40197. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  40198. if (!this._effect.isReady()) {
  40199. return false;
  40200. }
  40201. if (previousEffect !== this._effect) {
  40202. scene.resetCachedMaterial();
  40203. }
  40204. this._renderId = scene.getRenderId();
  40205. return true;
  40206. };
  40207. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40208. var scene = this.getScene();
  40209. if (this._options.uniforms.indexOf("world") !== -1) {
  40210. this._effect.setMatrix("world", world);
  40211. }
  40212. if (this._options.uniforms.indexOf("worldView") !== -1) {
  40213. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  40214. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  40215. }
  40216. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  40217. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  40218. }
  40219. };
  40220. ShaderMaterial.prototype.bind = function (world, mesh) {
  40221. // Std values
  40222. this.bindOnlyWorldMatrix(world);
  40223. if (this.getScene().getCachedMaterial() !== this) {
  40224. if (this._options.uniforms.indexOf("view") !== -1) {
  40225. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  40226. }
  40227. if (this._options.uniforms.indexOf("projection") !== -1) {
  40228. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  40229. }
  40230. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  40231. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  40232. }
  40233. // Bones
  40234. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  40235. var name;
  40236. // Texture
  40237. for (name in this._textures) {
  40238. this._effect.setTexture(name, this._textures[name]);
  40239. }
  40240. // Texture arrays
  40241. for (name in this._textureArrays) {
  40242. this._effect.setTextureArray(name, this._textureArrays[name]);
  40243. }
  40244. // Float
  40245. for (name in this._floats) {
  40246. this._effect.setFloat(name, this._floats[name]);
  40247. }
  40248. // Float s
  40249. for (name in this._floatsArrays) {
  40250. this._effect.setArray(name, this._floatsArrays[name]);
  40251. }
  40252. // Color3
  40253. for (name in this._colors3) {
  40254. this._effect.setColor3(name, this._colors3[name]);
  40255. }
  40256. // Color4
  40257. for (name in this._colors4) {
  40258. var color = this._colors4[name];
  40259. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  40260. }
  40261. // Vector2
  40262. for (name in this._vectors2) {
  40263. this._effect.setVector2(name, this._vectors2[name]);
  40264. }
  40265. // Vector3
  40266. for (name in this._vectors3) {
  40267. this._effect.setVector3(name, this._vectors3[name]);
  40268. }
  40269. // Vector4
  40270. for (name in this._vectors4) {
  40271. this._effect.setVector4(name, this._vectors4[name]);
  40272. }
  40273. // Matrix
  40274. for (name in this._matrices) {
  40275. this._effect.setMatrix(name, this._matrices[name]);
  40276. }
  40277. // Matrix 3x3
  40278. for (name in this._matrices3x3) {
  40279. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  40280. }
  40281. // Matrix 2x2
  40282. for (name in this._matrices2x2) {
  40283. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  40284. }
  40285. // Vector3Array
  40286. for (name in this._vectors3Arrays) {
  40287. this._effect.setArray3(name, this._vectors3Arrays[name]);
  40288. }
  40289. }
  40290. _super.prototype.bind.call(this, world, mesh);
  40291. };
  40292. ShaderMaterial.prototype.clone = function (name) {
  40293. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  40294. return newShaderMaterial;
  40295. };
  40296. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40297. if (forceDisposeTextures) {
  40298. var name;
  40299. for (name in this._textures) {
  40300. this._textures[name].dispose();
  40301. }
  40302. for (name in this._textureArrays) {
  40303. var array = this._textureArrays[name];
  40304. for (var index = 0; index < array.length; index++) {
  40305. array[index].dispose();
  40306. }
  40307. }
  40308. }
  40309. this._textures = {};
  40310. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40311. };
  40312. ShaderMaterial.prototype.serialize = function () {
  40313. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40314. serializationObject.customType = "BABYLON.ShaderMaterial";
  40315. serializationObject.options = this._options;
  40316. serializationObject.shaderPath = this._shaderPath;
  40317. var name;
  40318. // Texture
  40319. serializationObject.textures = {};
  40320. for (name in this._textures) {
  40321. serializationObject.textures[name] = this._textures[name].serialize();
  40322. }
  40323. // Texture arrays
  40324. serializationObject.textureArrays = {};
  40325. for (name in this._textureArrays) {
  40326. serializationObject.textureArrays[name] = [];
  40327. var array = this._textureArrays[name];
  40328. for (var index = 0; index < array.length; index++) {
  40329. serializationObject.textureArrays[name].push(array[index].serialize());
  40330. }
  40331. }
  40332. // Float
  40333. serializationObject.floats = {};
  40334. for (name in this._floats) {
  40335. serializationObject.floats[name] = this._floats[name];
  40336. }
  40337. // Float s
  40338. serializationObject.floatArrays = {};
  40339. for (name in this._floatsArrays) {
  40340. serializationObject.floatArrays[name] = this._floatsArrays[name];
  40341. }
  40342. // Color3
  40343. serializationObject.colors3 = {};
  40344. for (name in this._colors3) {
  40345. serializationObject.colors3[name] = this._colors3[name].asArray();
  40346. }
  40347. // Color4
  40348. serializationObject.colors4 = {};
  40349. for (name in this._colors4) {
  40350. serializationObject.colors4[name] = this._colors4[name].asArray();
  40351. }
  40352. // Vector2
  40353. serializationObject.vectors2 = {};
  40354. for (name in this._vectors2) {
  40355. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  40356. }
  40357. // Vector3
  40358. serializationObject.vectors3 = {};
  40359. for (name in this._vectors3) {
  40360. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  40361. }
  40362. // Vector4
  40363. serializationObject.vectors4 = {};
  40364. for (name in this._vectors4) {
  40365. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  40366. }
  40367. // Matrix
  40368. serializationObject.matrices = {};
  40369. for (name in this._matrices) {
  40370. serializationObject.matrices[name] = this._matrices[name].asArray();
  40371. }
  40372. // Matrix 3x3
  40373. serializationObject.matrices3x3 = {};
  40374. for (name in this._matrices3x3) {
  40375. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  40376. }
  40377. // Matrix 2x2
  40378. serializationObject.matrices2x2 = {};
  40379. for (name in this._matrices2x2) {
  40380. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  40381. }
  40382. // Vector3Array
  40383. serializationObject.vectors3Arrays = {};
  40384. for (name in this._vectors3Arrays) {
  40385. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  40386. }
  40387. return serializationObject;
  40388. };
  40389. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  40390. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  40391. var name;
  40392. // Texture
  40393. for (name in source.textures) {
  40394. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  40395. }
  40396. // Texture arrays
  40397. for (name in source.textureArrays) {
  40398. var array = source.textureArrays[name];
  40399. var textureArray = new Array();
  40400. for (var index = 0; index < array.length; index++) {
  40401. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  40402. }
  40403. material.setTextureArray(name, textureArray);
  40404. }
  40405. // Float
  40406. for (name in source.floats) {
  40407. material.setFloat(name, source.floats[name]);
  40408. }
  40409. // Float s
  40410. for (name in source.floatsArrays) {
  40411. material.setFloats(name, source.floatsArrays[name]);
  40412. }
  40413. // Color3
  40414. for (name in source.colors3) {
  40415. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  40416. }
  40417. // Color4
  40418. for (name in source.colors4) {
  40419. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  40420. }
  40421. // Vector2
  40422. for (name in source.vectors2) {
  40423. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  40424. }
  40425. // Vector3
  40426. for (name in source.vectors3) {
  40427. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  40428. }
  40429. // Vector4
  40430. for (name in source.vectors4) {
  40431. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  40432. }
  40433. // Matrix
  40434. for (name in source.matrices) {
  40435. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  40436. }
  40437. // Matrix 3x3
  40438. for (name in source.matrices3x3) {
  40439. material.setMatrix3x3(name, source.matrices3x3[name]);
  40440. }
  40441. // Matrix 2x2
  40442. for (name in source.matrices2x2) {
  40443. material.setMatrix2x2(name, source.matrices2x2[name]);
  40444. }
  40445. // Vector3Array
  40446. for (name in source.vectors3Arrays) {
  40447. material.setArray3(name, source.vectors3Arrays[name]);
  40448. }
  40449. return material;
  40450. };
  40451. return ShaderMaterial;
  40452. }(BABYLON.Material));
  40453. BABYLON.ShaderMaterial = ShaderMaterial;
  40454. })(BABYLON || (BABYLON = {}));
  40455. //# sourceMappingURL=../Materials/babylon.shaderMaterial.js.map
  40456. var BABYLON;
  40457. (function (BABYLON) {
  40458. var Internals;
  40459. (function (Internals) {
  40460. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  40461. // All values and structures referenced from:
  40462. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  40463. var DDS_MAGIC = 0x20534444;
  40464. 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;
  40465. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  40466. 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;
  40467. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  40468. function FourCCToInt32(value) {
  40469. return value.charCodeAt(0) +
  40470. (value.charCodeAt(1) << 8) +
  40471. (value.charCodeAt(2) << 16) +
  40472. (value.charCodeAt(3) << 24);
  40473. }
  40474. function Int32ToFourCC(value) {
  40475. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  40476. }
  40477. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  40478. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  40479. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  40480. var headerLengthInt = 31; // The header length in 32 bit ints
  40481. // Offsets into the header array
  40482. var off_magic = 0;
  40483. var off_size = 1;
  40484. var off_flags = 2;
  40485. var off_height = 3;
  40486. var off_width = 4;
  40487. var off_mipmapCount = 7;
  40488. var off_pfFlags = 20;
  40489. var off_pfFourCC = 21;
  40490. var off_RGBbpp = 22;
  40491. var off_RMask = 23;
  40492. var off_GMask = 24;
  40493. var off_BMask = 25;
  40494. var off_AMask = 26;
  40495. var off_caps1 = 27;
  40496. var off_caps2 = 28;
  40497. ;
  40498. var DDSTools = (function () {
  40499. function DDSTools() {
  40500. }
  40501. DDSTools.GetDDSInfo = function (arrayBuffer) {
  40502. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  40503. var mipmapCount = 1;
  40504. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  40505. mipmapCount = Math.max(1, header[off_mipmapCount]);
  40506. }
  40507. return {
  40508. width: header[off_width],
  40509. height: header[off_height],
  40510. mipmapCount: mipmapCount,
  40511. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  40512. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  40513. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  40514. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  40515. };
  40516. };
  40517. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40518. var byteArray = new Uint8Array(dataLength);
  40519. var srcData = new Uint8Array(arrayBuffer);
  40520. var index = 0;
  40521. for (var y = height - 1; y >= 0; y--) {
  40522. for (var x = 0; x < width; x++) {
  40523. var srcPos = dataOffset + (x + y * width) * 4;
  40524. byteArray[index + 2] = srcData[srcPos];
  40525. byteArray[index + 1] = srcData[srcPos + 1];
  40526. byteArray[index] = srcData[srcPos + 2];
  40527. byteArray[index + 3] = srcData[srcPos + 3];
  40528. index += 4;
  40529. }
  40530. }
  40531. return byteArray;
  40532. };
  40533. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40534. var byteArray = new Uint8Array(dataLength);
  40535. var srcData = new Uint8Array(arrayBuffer);
  40536. var index = 0;
  40537. for (var y = height - 1; y >= 0; y--) {
  40538. for (var x = 0; x < width; x++) {
  40539. var srcPos = dataOffset + (x + y * width) * 3;
  40540. byteArray[index + 2] = srcData[srcPos];
  40541. byteArray[index + 1] = srcData[srcPos + 1];
  40542. byteArray[index] = srcData[srcPos + 2];
  40543. index += 3;
  40544. }
  40545. }
  40546. return byteArray;
  40547. };
  40548. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  40549. var byteArray = new Uint8Array(dataLength);
  40550. var srcData = new Uint8Array(arrayBuffer);
  40551. var index = 0;
  40552. for (var y = height - 1; y >= 0; y--) {
  40553. for (var x = 0; x < width; x++) {
  40554. var srcPos = dataOffset + (x + y * width);
  40555. byteArray[index] = srcData[srcPos];
  40556. index++;
  40557. }
  40558. }
  40559. return byteArray;
  40560. };
  40561. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  40562. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  40563. if (header[off_magic] != DDS_MAGIC) {
  40564. BABYLON.Tools.Error("Invalid magic number in DDS header");
  40565. return;
  40566. }
  40567. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  40568. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  40569. return;
  40570. }
  40571. if (info.isFourCC) {
  40572. fourCC = header[off_pfFourCC];
  40573. switch (fourCC) {
  40574. case FOURCC_DXT1:
  40575. blockBytes = 8;
  40576. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  40577. break;
  40578. case FOURCC_DXT3:
  40579. blockBytes = 16;
  40580. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  40581. break;
  40582. case FOURCC_DXT5:
  40583. blockBytes = 16;
  40584. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  40585. break;
  40586. default:
  40587. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  40588. return;
  40589. }
  40590. }
  40591. mipmapCount = 1;
  40592. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  40593. mipmapCount = Math.max(1, header[off_mipmapCount]);
  40594. }
  40595. var bpp = header[off_RGBbpp];
  40596. for (var face = 0; face < faces; face++) {
  40597. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  40598. width = header[off_width];
  40599. height = header[off_height];
  40600. dataOffset = header[off_size] + 4;
  40601. for (i = 0; i < mipmapCount; ++i) {
  40602. if (info.isRGB) {
  40603. if (bpp === 24) {
  40604. dataLength = width * height * 3;
  40605. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  40606. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  40607. }
  40608. else {
  40609. dataLength = width * height * 4;
  40610. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  40611. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  40612. }
  40613. }
  40614. else if (info.isLuminance) {
  40615. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  40616. var unpaddedRowSize = width;
  40617. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  40618. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  40619. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  40620. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  40621. }
  40622. else {
  40623. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  40624. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  40625. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  40626. }
  40627. dataOffset += dataLength;
  40628. width *= 0.5;
  40629. height *= 0.5;
  40630. width = Math.max(1.0, width);
  40631. height = Math.max(1.0, height);
  40632. }
  40633. }
  40634. };
  40635. return DDSTools;
  40636. }());
  40637. Internals.DDSTools = DDSTools;
  40638. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40639. })(BABYLON || (BABYLON = {}));
  40640. //# sourceMappingURL=../Tools/babylon.tools.dds.js.map
  40641. var BABYLON;
  40642. (function (BABYLON) {
  40643. var CannonJSPlugin = (function () {
  40644. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  40645. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  40646. if (iterations === void 0) { iterations = 10; }
  40647. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  40648. this.name = "CannonJSPlugin";
  40649. this._physicsMaterials = [];
  40650. this._fixedTimeStep = 1 / 60;
  40651. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  40652. this._currentCollisionGroup = 2;
  40653. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  40654. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  40655. this._tmpPosition = BABYLON.Vector3.Zero();
  40656. this._tmpQuaternion = new BABYLON.Quaternion();
  40657. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  40658. this._tmpDeltaRotation = new BABYLON.Quaternion();
  40659. this._tmpUnityRotation = new BABYLON.Quaternion();
  40660. if (!this.isSupported()) {
  40661. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  40662. return;
  40663. }
  40664. this.world = new CANNON.World();
  40665. this.world.broadphase = new CANNON.NaiveBroadphase();
  40666. this.world.solver.iterations = iterations;
  40667. }
  40668. CannonJSPlugin.prototype.setGravity = function (gravity) {
  40669. this.world.gravity.copy(gravity);
  40670. };
  40671. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  40672. this._fixedTimeStep = timeStep;
  40673. };
  40674. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  40675. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  40676. };
  40677. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  40678. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  40679. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  40680. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  40681. };
  40682. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  40683. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  40684. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  40685. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  40686. };
  40687. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  40688. //parent-child relationship. Does this impostor has a parent impostor?
  40689. if (impostor.parent) {
  40690. if (impostor.physicsBody) {
  40691. this.removePhysicsBody(impostor);
  40692. //TODO is that needed?
  40693. impostor.forceUpdate();
  40694. }
  40695. return;
  40696. }
  40697. //should a new body be created for this impostor?
  40698. if (impostor.isBodyInitRequired()) {
  40699. var shape = this._createShape(impostor);
  40700. //unregister events, if body is being changed
  40701. var oldBody = impostor.physicsBody;
  40702. if (oldBody) {
  40703. this.removePhysicsBody(impostor);
  40704. }
  40705. //create the body and material
  40706. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  40707. var bodyCreationObject = {
  40708. mass: impostor.getParam("mass"),
  40709. material: material
  40710. };
  40711. // A simple extend, in case native options were used.
  40712. var nativeOptions = impostor.getParam("nativeOptions");
  40713. for (var key in nativeOptions) {
  40714. if (nativeOptions.hasOwnProperty(key)) {
  40715. bodyCreationObject[key] = nativeOptions[key];
  40716. }
  40717. }
  40718. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  40719. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  40720. this.world.addEventListener("preStep", impostor.beforeStep);
  40721. this.world.addEventListener("postStep", impostor.afterStep);
  40722. impostor.physicsBody.addShape(shape);
  40723. this.world.add(impostor.physicsBody);
  40724. //try to keep the body moving in the right direction by taking old properties.
  40725. //Should be tested!
  40726. if (oldBody) {
  40727. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  40728. impostor.physicsBody[param].copy(oldBody[param]);
  40729. });
  40730. }
  40731. this._processChildMeshes(impostor);
  40732. }
  40733. //now update the body's transformation
  40734. this._updatePhysicsBodyTransformation(impostor);
  40735. };
  40736. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  40737. var _this = this;
  40738. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  40739. if (meshChildren.length) {
  40740. var processMesh = function (localPosition, mesh) {
  40741. var childImpostor = mesh.getPhysicsImpostor();
  40742. if (childImpostor) {
  40743. var parent = childImpostor.parent;
  40744. if (parent !== mainImpostor) {
  40745. var localPosition = mesh.position;
  40746. if (childImpostor.physicsBody) {
  40747. _this.removePhysicsBody(childImpostor);
  40748. childImpostor.physicsBody = null;
  40749. }
  40750. childImpostor.parent = mainImpostor;
  40751. childImpostor.resetUpdateFlags();
  40752. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  40753. //Add the mass of the children.
  40754. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  40755. }
  40756. }
  40757. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  40758. };
  40759. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  40760. }
  40761. };
  40762. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  40763. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  40764. this.world.removeEventListener("preStep", impostor.beforeStep);
  40765. this.world.removeEventListener("postStep", impostor.afterStep);
  40766. this.world.remove(impostor.physicsBody);
  40767. };
  40768. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  40769. var mainBody = impostorJoint.mainImpostor.physicsBody;
  40770. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  40771. if (!mainBody || !connectedBody) {
  40772. return;
  40773. }
  40774. var constraint;
  40775. var jointData = impostorJoint.joint.jointData;
  40776. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  40777. var constraintData = {
  40778. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  40779. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  40780. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  40781. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  40782. maxForce: jointData.nativeParams.maxForce,
  40783. collideConnected: !!jointData.collision
  40784. };
  40785. //Not needed, Cannon has a collideConnected flag
  40786. /*if (!jointData.collision) {
  40787. //add 1st body to a collision group of its own, if it is not in 1
  40788. if (mainBody.collisionFilterGroup === 1) {
  40789. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  40790. this._currentCollisionGroup <<= 1;
  40791. }
  40792. if (connectedBody.collisionFilterGroup === 1) {
  40793. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  40794. this._currentCollisionGroup <<= 1;
  40795. }
  40796. //add their mask to the collisionFilterMask of each other:
  40797. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  40798. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  40799. }*/
  40800. switch (impostorJoint.joint.type) {
  40801. case BABYLON.PhysicsJoint.HingeJoint:
  40802. case BABYLON.PhysicsJoint.Hinge2Joint:
  40803. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  40804. break;
  40805. case BABYLON.PhysicsJoint.DistanceJoint:
  40806. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  40807. break;
  40808. case BABYLON.PhysicsJoint.SpringJoint:
  40809. var springData = jointData;
  40810. constraint = new CANNON.Spring(mainBody, connectedBody, {
  40811. restLength: springData.length,
  40812. stiffness: springData.stiffness,
  40813. damping: springData.damping,
  40814. localAnchorA: constraintData.pivotA,
  40815. localAnchorB: constraintData.pivotB
  40816. });
  40817. break;
  40818. case BABYLON.PhysicsJoint.LockJoint:
  40819. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  40820. break;
  40821. case BABYLON.PhysicsJoint.PointToPointJoint:
  40822. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  40823. default:
  40824. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  40825. break;
  40826. }
  40827. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  40828. constraint.collideConnected = !!jointData.collision;
  40829. impostorJoint.joint.physicsJoint = constraint;
  40830. //don't add spring as constraint, as it is not one.
  40831. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  40832. this.world.addConstraint(constraint);
  40833. }
  40834. else {
  40835. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  40836. constraint.applyForce();
  40837. });
  40838. }
  40839. };
  40840. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  40841. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  40842. };
  40843. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  40844. var index;
  40845. var mat;
  40846. for (index = 0; index < this._physicsMaterials.length; index++) {
  40847. mat = this._physicsMaterials[index];
  40848. if (mat.friction === friction && mat.restitution === restitution) {
  40849. return mat;
  40850. }
  40851. }
  40852. var currentMat = new CANNON.Material(name);
  40853. currentMat.friction = friction;
  40854. currentMat.restitution = restitution;
  40855. this._physicsMaterials.push(currentMat);
  40856. return currentMat;
  40857. };
  40858. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  40859. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  40860. };
  40861. CannonJSPlugin.prototype._createShape = function (impostor) {
  40862. var object = impostor.object;
  40863. var returnValue;
  40864. var extendSize = impostor.getObjectExtendSize();
  40865. switch (impostor.type) {
  40866. case BABYLON.PhysicsEngine.SphereImpostor:
  40867. var radiusX = extendSize.x;
  40868. var radiusY = extendSize.y;
  40869. var radiusZ = extendSize.z;
  40870. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  40871. break;
  40872. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  40873. case BABYLON.PhysicsImpostor.CylinderImpostor:
  40874. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  40875. break;
  40876. case BABYLON.PhysicsImpostor.BoxImpostor:
  40877. var box = extendSize.scale(0.5);
  40878. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  40879. break;
  40880. case BABYLON.PhysicsImpostor.PlaneImpostor:
  40881. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  40882. returnValue = new CANNON.Plane();
  40883. break;
  40884. case BABYLON.PhysicsImpostor.MeshImpostor:
  40885. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  40886. var rawFaces = object.getIndices ? object.getIndices() : [];
  40887. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  40888. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  40889. break;
  40890. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  40891. returnValue = this._createHeightmap(object);
  40892. break;
  40893. case BABYLON.PhysicsImpostor.ParticleImpostor:
  40894. returnValue = new CANNON.Particle();
  40895. break;
  40896. }
  40897. return returnValue;
  40898. };
  40899. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  40900. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40901. var matrix = [];
  40902. //For now pointDepth will not be used and will be automatically calculated.
  40903. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  40904. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  40905. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  40906. var elementSize = dim * 2 / arraySize;
  40907. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  40908. for (var i = 0; i < pos.length; i = i + 3) {
  40909. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  40910. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  40911. var y = pos[i + 1] + minY;
  40912. if (!matrix[x]) {
  40913. matrix[x] = [];
  40914. }
  40915. if (!matrix[x][z]) {
  40916. matrix[x][z] = y;
  40917. }
  40918. matrix[x][z] = Math.max(y, matrix[x][z]);
  40919. }
  40920. for (var x = 0; x <= arraySize; ++x) {
  40921. if (!matrix[x]) {
  40922. var loc = 1;
  40923. while (!matrix[(x + loc) % arraySize]) {
  40924. loc++;
  40925. }
  40926. matrix[x] = matrix[(x + loc) % arraySize].slice();
  40927. }
  40928. for (var z = 0; z <= arraySize; ++z) {
  40929. if (!matrix[x][z]) {
  40930. var loc = 1;
  40931. var newValue;
  40932. while (newValue === undefined) {
  40933. newValue = matrix[x][(z + loc++) % arraySize];
  40934. }
  40935. matrix[x][z] = newValue;
  40936. }
  40937. }
  40938. }
  40939. var shape = new CANNON.Heightfield(matrix, {
  40940. elementSize: elementSize
  40941. });
  40942. //For future reference, needed for body transformation
  40943. shape.minY = minY;
  40944. return shape;
  40945. };
  40946. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  40947. var object = impostor.object;
  40948. //make sure it is updated...
  40949. object.computeWorldMatrix && object.computeWorldMatrix(true);
  40950. // The delta between the mesh position and the mesh bounding box center
  40951. var center = impostor.getObjectCenter();
  40952. var extendSize = impostor.getObjectExtendSize();
  40953. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  40954. this._tmpPosition.copyFrom(center);
  40955. var quaternion = object.rotationQuaternion;
  40956. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  40957. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  40958. //-90 DEG in X, precalculated
  40959. quaternion = quaternion.multiply(this._minus90X);
  40960. //Invert! (Precalculated, 90 deg in X)
  40961. //No need to clone. this will never change.
  40962. impostor.setDeltaRotation(this._plus90X);
  40963. }
  40964. //If it is a heightfield, if should be centered.
  40965. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  40966. var mesh = object;
  40967. //calculate the correct body position:
  40968. var rotationQuaternion = mesh.rotationQuaternion;
  40969. mesh.rotationQuaternion = this._tmpUnityRotation;
  40970. mesh.computeWorldMatrix(true);
  40971. //get original center with no rotation
  40972. var c = center.clone();
  40973. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  40974. //rotation is back
  40975. mesh.rotationQuaternion = rotationQuaternion;
  40976. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  40977. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  40978. mesh.setPivotMatrix(p);
  40979. mesh.computeWorldMatrix(true);
  40980. //calculate the translation
  40981. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  40982. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  40983. //add it inverted to the delta
  40984. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  40985. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  40986. mesh.setPivotMatrix(oldPivot);
  40987. mesh.computeWorldMatrix(true);
  40988. }
  40989. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  40990. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  40991. this._tmpPosition.copyFrom(object.position);
  40992. }
  40993. impostor.setDeltaPosition(this._tmpDeltaPosition);
  40994. //Now update the impostor object
  40995. impostor.physicsBody.position.copy(this._tmpPosition);
  40996. impostor.physicsBody.quaternion.copy(quaternion);
  40997. };
  40998. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  40999. impostor.object.position.copyFrom(impostor.physicsBody.position);
  41000. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  41001. };
  41002. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  41003. impostor.physicsBody.position.copy(newPosition);
  41004. impostor.physicsBody.quaternion.copy(newRotation);
  41005. };
  41006. CannonJSPlugin.prototype.isSupported = function () {
  41007. return window.CANNON !== undefined;
  41008. };
  41009. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  41010. impostor.physicsBody.velocity.copy(velocity);
  41011. };
  41012. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  41013. impostor.physicsBody.angularVelocity.copy(velocity);
  41014. };
  41015. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  41016. var v = impostor.physicsBody.velocity;
  41017. if (!v)
  41018. return null;
  41019. return new BABYLON.Vector3(v.x, v.y, v.z);
  41020. };
  41021. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  41022. var v = impostor.physicsBody.angularVelocity;
  41023. if (!v)
  41024. return null;
  41025. return new BABYLON.Vector3(v.x, v.y, v.z);
  41026. };
  41027. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  41028. impostor.physicsBody.mass = mass;
  41029. impostor.physicsBody.updateMassProperties();
  41030. };
  41031. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  41032. impostor.physicsBody.sleep();
  41033. };
  41034. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  41035. impostor.physicsBody.wakeUp();
  41036. };
  41037. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  41038. joint.physicsJoint.distance = maxDistance;
  41039. };
  41040. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  41041. if (!motorIndex) {
  41042. joint.physicsJoint.enableMotor();
  41043. }
  41044. };
  41045. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  41046. if (!motorIndex) {
  41047. joint.physicsJoint.disableMotor();
  41048. }
  41049. };
  41050. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  41051. if (!motorIndex) {
  41052. joint.physicsJoint.enableMotor();
  41053. joint.physicsJoint.setMotorSpeed(speed);
  41054. if (maxForce) {
  41055. this.setLimit(joint, maxForce);
  41056. }
  41057. }
  41058. };
  41059. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  41060. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  41061. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  41062. };
  41063. CannonJSPlugin.prototype.dispose = function () {
  41064. //nothing to do, actually.
  41065. };
  41066. return CannonJSPlugin;
  41067. }());
  41068. BABYLON.CannonJSPlugin = CannonJSPlugin;
  41069. })(BABYLON || (BABYLON = {}));
  41070. //# sourceMappingURL=../../Physics/Plugins/babylon.cannonJSPlugin.js.map
  41071. var BABYLON;
  41072. (function (BABYLON) {
  41073. var OimoJSPlugin = (function () {
  41074. function OimoJSPlugin(iterations) {
  41075. this.name = "OimoJSPlugin";
  41076. this._tmpImpostorsArray = [];
  41077. this._tmpPositionVector = BABYLON.Vector3.Zero();
  41078. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  41079. this.world.worldscale(1);
  41080. this.world.clear();
  41081. //making sure no stats are calculated
  41082. this.world.isNoStat = true;
  41083. }
  41084. OimoJSPlugin.prototype.setGravity = function (gravity) {
  41085. this.world.gravity.copy(gravity);
  41086. };
  41087. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  41088. this.world.timeStep = timeStep;
  41089. };
  41090. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  41091. var _this = this;
  41092. impostors.forEach(function (impostor) {
  41093. impostor.beforeStep();
  41094. });
  41095. this.world.step();
  41096. impostors.forEach(function (impostor) {
  41097. impostor.afterStep();
  41098. //update the ordered impostors array
  41099. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  41100. });
  41101. //check for collisions
  41102. var contact = this.world.contacts;
  41103. while (contact !== null) {
  41104. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  41105. contact = contact.next;
  41106. continue;
  41107. }
  41108. //is this body colliding with any other? get the impostor
  41109. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  41110. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  41111. if (!mainImpostor || !collidingImpostor) {
  41112. contact = contact.next;
  41113. continue;
  41114. }
  41115. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  41116. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  41117. contact = contact.next;
  41118. }
  41119. };
  41120. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41121. var mass = impostor.physicsBody.massInfo.mass;
  41122. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  41123. };
  41124. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41125. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  41126. this.applyImpulse(impostor, force, contactPoint);
  41127. };
  41128. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41129. var _this = this;
  41130. //parent-child relationship. Does this impostor has a parent impostor?
  41131. if (impostor.parent) {
  41132. if (impostor.physicsBody) {
  41133. this.removePhysicsBody(impostor);
  41134. //TODO is that needed?
  41135. impostor.forceUpdate();
  41136. }
  41137. return;
  41138. }
  41139. if (impostor.isBodyInitRequired()) {
  41140. var bodyConfig = {
  41141. name: impostor.uniqueId,
  41142. //Oimo must have mass, also for static objects.
  41143. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  41144. size: [],
  41145. type: [],
  41146. pos: [],
  41147. rot: [],
  41148. move: impostor.getParam("mass") !== 0,
  41149. //Supporting older versions of Oimo
  41150. world: this.world
  41151. };
  41152. var impostors = [impostor];
  41153. var addToArray = function (parent) {
  41154. if (!parent.getChildMeshes)
  41155. return;
  41156. parent.getChildMeshes().forEach(function (m) {
  41157. if (m.physicsImpostor) {
  41158. impostors.push(m.physicsImpostor);
  41159. m.physicsImpostor._init();
  41160. }
  41161. });
  41162. };
  41163. addToArray(impostor.object);
  41164. var checkWithEpsilon_1 = function (value) {
  41165. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  41166. };
  41167. impostors.forEach(function (i) {
  41168. //get the correct bounding box
  41169. var oldQuaternion = i.object.rotationQuaternion;
  41170. var rot = new OIMO.Euler().setFromQuaternion({
  41171. x: impostor.object.rotationQuaternion.x,
  41172. y: impostor.object.rotationQuaternion.y,
  41173. z: impostor.object.rotationQuaternion.z,
  41174. s: impostor.object.rotationQuaternion.w
  41175. });
  41176. var extendSize = i.getObjectExtendSize();
  41177. if (i === impostor) {
  41178. var center = impostor.getObjectCenter();
  41179. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  41180. //Can also use Array.prototype.push.apply
  41181. bodyConfig.pos.push(center.x);
  41182. bodyConfig.pos.push(center.y);
  41183. bodyConfig.pos.push(center.z);
  41184. //tmp solution
  41185. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  41186. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  41187. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  41188. }
  41189. else {
  41190. bodyConfig.pos.push(i.object.position.x);
  41191. bodyConfig.pos.push(i.object.position.y);
  41192. bodyConfig.pos.push(i.object.position.z);
  41193. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  41194. bodyConfig.rot.push(0);
  41195. bodyConfig.rot.push(0);
  41196. bodyConfig.rot.push(0);
  41197. }
  41198. // register mesh
  41199. switch (i.type) {
  41200. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41201. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  41202. case BABYLON.PhysicsImpostor.SphereImpostor:
  41203. var radiusX = extendSize.x;
  41204. var radiusY = extendSize.y;
  41205. var radiusZ = extendSize.z;
  41206. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  41207. bodyConfig.type.push('sphere');
  41208. //due to the way oimo works with compounds, add 3 times
  41209. bodyConfig.size.push(size);
  41210. bodyConfig.size.push(size);
  41211. bodyConfig.size.push(size);
  41212. break;
  41213. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41214. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  41215. var sizeY = checkWithEpsilon_1(extendSize.y);
  41216. bodyConfig.type.push('cylinder');
  41217. bodyConfig.size.push(sizeX);
  41218. bodyConfig.size.push(sizeY);
  41219. //due to the way oimo works with compounds, add one more value.
  41220. bodyConfig.size.push(sizeY);
  41221. break;
  41222. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41223. case BABYLON.PhysicsImpostor.BoxImpostor:
  41224. default:
  41225. var sizeX = checkWithEpsilon_1(extendSize.x);
  41226. var sizeY = checkWithEpsilon_1(extendSize.y);
  41227. var sizeZ = checkWithEpsilon_1(extendSize.z);
  41228. bodyConfig.type.push('box');
  41229. bodyConfig.size.push(sizeX);
  41230. bodyConfig.size.push(sizeY);
  41231. bodyConfig.size.push(sizeZ);
  41232. break;
  41233. }
  41234. //actually not needed, but hey...
  41235. i.object.rotationQuaternion = oldQuaternion;
  41236. });
  41237. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  41238. }
  41239. else {
  41240. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  41241. }
  41242. impostor.setDeltaPosition(this._tmpPositionVector);
  41243. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  41244. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  41245. };
  41246. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41247. //impostor.physicsBody.dispose();
  41248. //Same as : (older oimo versions)
  41249. this.world.removeRigidBody(impostor.physicsBody);
  41250. };
  41251. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41252. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41253. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41254. if (!mainBody || !connectedBody) {
  41255. return;
  41256. }
  41257. var jointData = impostorJoint.joint.jointData;
  41258. var options = jointData.nativeParams || {};
  41259. var type;
  41260. var nativeJointData = {
  41261. body1: mainBody,
  41262. body2: connectedBody,
  41263. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  41264. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  41265. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  41266. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  41267. min: options.min,
  41268. max: options.max,
  41269. collision: options.collision || jointData.collision,
  41270. spring: options.spring,
  41271. //supporting older version of Oimo
  41272. world: this.world
  41273. };
  41274. switch (impostorJoint.joint.type) {
  41275. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41276. type = "jointBall";
  41277. break;
  41278. case BABYLON.PhysicsJoint.SpringJoint:
  41279. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  41280. var springData = jointData;
  41281. nativeJointData.min = springData.length || nativeJointData.min;
  41282. //Max should also be set, just make sure it is at least min
  41283. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  41284. case BABYLON.PhysicsJoint.DistanceJoint:
  41285. type = "jointDistance";
  41286. nativeJointData.max = jointData.maxDistance;
  41287. break;
  41288. case BABYLON.PhysicsJoint.PrismaticJoint:
  41289. type = "jointPrisme";
  41290. break;
  41291. case BABYLON.PhysicsJoint.SliderJoint:
  41292. type = "jointSlide";
  41293. break;
  41294. case BABYLON.PhysicsJoint.WheelJoint:
  41295. type = "jointWheel";
  41296. break;
  41297. case BABYLON.PhysicsJoint.HingeJoint:
  41298. default:
  41299. type = "jointHinge";
  41300. break;
  41301. }
  41302. nativeJointData.type = type;
  41303. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  41304. };
  41305. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41306. //Bug in Oimo prevents us from disposing a joint in the playground
  41307. //joint.joint.physicsJoint.dispose();
  41308. //So we will bruteforce it!
  41309. try {
  41310. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  41311. }
  41312. catch (e) {
  41313. BABYLON.Tools.Warn(e);
  41314. }
  41315. };
  41316. OimoJSPlugin.prototype.isSupported = function () {
  41317. return OIMO !== undefined;
  41318. };
  41319. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  41320. if (!impostor.physicsBody.sleeping) {
  41321. //TODO check that
  41322. if (impostor.physicsBody.shapes.next) {
  41323. var parentShape = this._getLastShape(impostor.physicsBody);
  41324. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  41325. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  41326. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  41327. }
  41328. else {
  41329. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  41330. }
  41331. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  41332. impostor.object.rotationQuaternion.normalize();
  41333. }
  41334. };
  41335. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  41336. var body = impostor.physicsBody;
  41337. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  41338. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  41339. body.syncShapes();
  41340. body.awake();
  41341. };
  41342. OimoJSPlugin.prototype._getLastShape = function (body) {
  41343. var lastShape = body.shapes;
  41344. while (lastShape.next) {
  41345. lastShape = lastShape.next;
  41346. }
  41347. return lastShape;
  41348. };
  41349. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  41350. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  41351. };
  41352. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  41353. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  41354. };
  41355. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  41356. var v = impostor.physicsBody.linearVelocity;
  41357. if (!v)
  41358. return null;
  41359. return new BABYLON.Vector3(v.x, v.y, v.z);
  41360. };
  41361. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  41362. var v = impostor.physicsBody.angularVelocity;
  41363. if (!v)
  41364. return null;
  41365. return new BABYLON.Vector3(v.x, v.y, v.z);
  41366. };
  41367. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  41368. var staticBody = mass === 0;
  41369. //this will actually set the body's density and not its mass.
  41370. //But this is how oimo treats the mass variable.
  41371. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  41372. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  41373. };
  41374. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  41375. impostor.physicsBody.sleep();
  41376. };
  41377. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  41378. impostor.physicsBody.awake();
  41379. };
  41380. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  41381. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  41382. if (minDistance !== void 0) {
  41383. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  41384. }
  41385. };
  41386. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  41387. //TODO separate rotational and transational motors.
  41388. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  41389. if (motor) {
  41390. motor.setMotor(speed, maxForce);
  41391. }
  41392. };
  41393. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  41394. //TODO separate rotational and transational motors.
  41395. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  41396. if (motor) {
  41397. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  41398. }
  41399. };
  41400. OimoJSPlugin.prototype.dispose = function () {
  41401. this.world.clear();
  41402. };
  41403. return OimoJSPlugin;
  41404. }());
  41405. BABYLON.OimoJSPlugin = OimoJSPlugin;
  41406. })(BABYLON || (BABYLON = {}));
  41407. //# sourceMappingURL=../../Physics/Plugins/babylon.oimoJSPlugin.js.map
  41408. var BABYLON;
  41409. (function (BABYLON) {
  41410. var DisplayPassPostProcess = (function (_super) {
  41411. __extends(DisplayPassPostProcess, _super);
  41412. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  41413. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  41414. }
  41415. return DisplayPassPostProcess;
  41416. }(BABYLON.PostProcess));
  41417. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  41418. })(BABYLON || (BABYLON = {}));
  41419. //# sourceMappingURL=../PostProcess/babylon.displayPassPostProcess.js.map
  41420. var BABYLON;
  41421. (function (BABYLON) {
  41422. var SimplificationSettings = (function () {
  41423. function SimplificationSettings(quality, distance, optimizeMesh) {
  41424. this.quality = quality;
  41425. this.distance = distance;
  41426. this.optimizeMesh = optimizeMesh;
  41427. }
  41428. return SimplificationSettings;
  41429. }());
  41430. BABYLON.SimplificationSettings = SimplificationSettings;
  41431. var SimplificationQueue = (function () {
  41432. function SimplificationQueue() {
  41433. this.running = false;
  41434. this._simplificationArray = [];
  41435. }
  41436. SimplificationQueue.prototype.addTask = function (task) {
  41437. this._simplificationArray.push(task);
  41438. };
  41439. SimplificationQueue.prototype.executeNext = function () {
  41440. var task = this._simplificationArray.pop();
  41441. if (task) {
  41442. this.running = true;
  41443. this.runSimplification(task);
  41444. }
  41445. else {
  41446. this.running = false;
  41447. }
  41448. };
  41449. SimplificationQueue.prototype.runSimplification = function (task) {
  41450. var _this = this;
  41451. if (task.parallelProcessing) {
  41452. //parallel simplifier
  41453. task.settings.forEach(function (setting) {
  41454. var simplifier = _this.getSimplifier(task);
  41455. simplifier.simplify(setting, function (newMesh) {
  41456. task.mesh.addLODLevel(setting.distance, newMesh);
  41457. newMesh.isVisible = true;
  41458. //check if it is the last
  41459. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  41460. //all done, run the success callback.
  41461. task.successCallback();
  41462. }
  41463. _this.executeNext();
  41464. });
  41465. });
  41466. }
  41467. else {
  41468. //single simplifier.
  41469. var simplifier = this.getSimplifier(task);
  41470. var runDecimation = function (setting, callback) {
  41471. simplifier.simplify(setting, function (newMesh) {
  41472. task.mesh.addLODLevel(setting.distance, newMesh);
  41473. newMesh.isVisible = true;
  41474. //run the next quality level
  41475. callback();
  41476. });
  41477. };
  41478. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  41479. runDecimation(task.settings[loop.index], function () {
  41480. loop.executeNext();
  41481. });
  41482. }, function () {
  41483. //execution ended, run the success callback.
  41484. if (task.successCallback) {
  41485. task.successCallback();
  41486. }
  41487. _this.executeNext();
  41488. });
  41489. }
  41490. };
  41491. SimplificationQueue.prototype.getSimplifier = function (task) {
  41492. switch (task.simplificationType) {
  41493. case SimplificationType.QUADRATIC:
  41494. default:
  41495. return new QuadraticErrorSimplification(task.mesh);
  41496. }
  41497. };
  41498. return SimplificationQueue;
  41499. }());
  41500. BABYLON.SimplificationQueue = SimplificationQueue;
  41501. /**
  41502. * The implemented types of simplification.
  41503. * At the moment only Quadratic Error Decimation is implemented.
  41504. */
  41505. (function (SimplificationType) {
  41506. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  41507. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  41508. var SimplificationType = BABYLON.SimplificationType;
  41509. var DecimationTriangle = (function () {
  41510. function DecimationTriangle(vertices) {
  41511. this.vertices = vertices;
  41512. this.error = new Array(4);
  41513. this.deleted = false;
  41514. this.isDirty = false;
  41515. this.deletePending = false;
  41516. this.borderFactor = 0;
  41517. }
  41518. return DecimationTriangle;
  41519. }());
  41520. BABYLON.DecimationTriangle = DecimationTriangle;
  41521. var DecimationVertex = (function () {
  41522. function DecimationVertex(position, id) {
  41523. this.position = position;
  41524. this.id = id;
  41525. this.isBorder = true;
  41526. this.q = new QuadraticMatrix();
  41527. this.triangleCount = 0;
  41528. this.triangleStart = 0;
  41529. this.originalOffsets = [];
  41530. }
  41531. DecimationVertex.prototype.updatePosition = function (newPosition) {
  41532. this.position.copyFrom(newPosition);
  41533. };
  41534. return DecimationVertex;
  41535. }());
  41536. BABYLON.DecimationVertex = DecimationVertex;
  41537. var QuadraticMatrix = (function () {
  41538. function QuadraticMatrix(data) {
  41539. this.data = new Array(10);
  41540. for (var i = 0; i < 10; ++i) {
  41541. if (data && data[i]) {
  41542. this.data[i] = data[i];
  41543. }
  41544. else {
  41545. this.data[i] = 0;
  41546. }
  41547. }
  41548. }
  41549. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  41550. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  41551. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  41552. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  41553. return det;
  41554. };
  41555. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  41556. for (var i = 0; i < 10; ++i) {
  41557. this.data[i] += matrix.data[i];
  41558. }
  41559. };
  41560. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  41561. for (var i = 0; i < 10; ++i) {
  41562. this.data[i] += data[i];
  41563. }
  41564. };
  41565. QuadraticMatrix.prototype.add = function (matrix) {
  41566. var m = new QuadraticMatrix();
  41567. for (var i = 0; i < 10; ++i) {
  41568. m.data[i] = this.data[i] + matrix.data[i];
  41569. }
  41570. return m;
  41571. };
  41572. QuadraticMatrix.FromData = function (a, b, c, d) {
  41573. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  41574. };
  41575. //returning an array to avoid garbage collection
  41576. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  41577. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  41578. };
  41579. return QuadraticMatrix;
  41580. }());
  41581. BABYLON.QuadraticMatrix = QuadraticMatrix;
  41582. var Reference = (function () {
  41583. function Reference(vertexId, triangleId) {
  41584. this.vertexId = vertexId;
  41585. this.triangleId = triangleId;
  41586. }
  41587. return Reference;
  41588. }());
  41589. BABYLON.Reference = Reference;
  41590. /**
  41591. * An implementation of the Quadratic Error simplification algorithm.
  41592. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  41593. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  41594. * @author RaananW
  41595. */
  41596. var QuadraticErrorSimplification = (function () {
  41597. function QuadraticErrorSimplification(_mesh) {
  41598. this._mesh = _mesh;
  41599. this.initialized = false;
  41600. this.syncIterations = 5000;
  41601. this.aggressiveness = 7;
  41602. this.decimationIterations = 100;
  41603. this.boundingBoxEpsilon = BABYLON.Epsilon;
  41604. }
  41605. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  41606. var _this = this;
  41607. this.initDecimatedMesh();
  41608. //iterating through the submeshes array, one after the other.
  41609. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  41610. _this.initWithMesh(loop.index, function () {
  41611. _this.runDecimation(settings, loop.index, function () {
  41612. loop.executeNext();
  41613. });
  41614. }, settings.optimizeMesh);
  41615. }, function () {
  41616. setTimeout(function () {
  41617. successCallback(_this._reconstructedMesh);
  41618. }, 0);
  41619. });
  41620. };
  41621. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  41622. var _this = this;
  41623. var gCount = 0;
  41624. triangle.vertices.forEach(function (vertex) {
  41625. var count = 0;
  41626. var vPos = vertex.position;
  41627. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  41628. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  41629. ++count;
  41630. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  41631. ++count;
  41632. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  41633. ++count;
  41634. if (count > 1) {
  41635. ++gCount;
  41636. }
  41637. ;
  41638. });
  41639. if (gCount > 1) {
  41640. console.log(triangle, gCount);
  41641. }
  41642. return gCount > 1;
  41643. };
  41644. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  41645. var _this = this;
  41646. var targetCount = ~~(this.triangles.length * settings.quality);
  41647. var deletedTriangles = 0;
  41648. var triangleCount = this.triangles.length;
  41649. var iterationFunction = function (iteration, callback) {
  41650. setTimeout(function () {
  41651. if (iteration % 5 === 0) {
  41652. _this.updateMesh(iteration === 0);
  41653. }
  41654. for (var i = 0; i < _this.triangles.length; ++i) {
  41655. _this.triangles[i].isDirty = false;
  41656. }
  41657. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  41658. var trianglesIterator = function (i) {
  41659. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  41660. var t = _this.triangles[tIdx];
  41661. if (!t)
  41662. return;
  41663. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  41664. return;
  41665. }
  41666. for (var j = 0; j < 3; ++j) {
  41667. if (t.error[j] < threshold) {
  41668. var deleted0 = [];
  41669. var deleted1 = [];
  41670. var v0 = t.vertices[j];
  41671. var v1 = t.vertices[(j + 1) % 3];
  41672. if (v0.isBorder || v1.isBorder)
  41673. continue;
  41674. var p = BABYLON.Vector3.Zero();
  41675. var n = BABYLON.Vector3.Zero();
  41676. var uv = BABYLON.Vector2.Zero();
  41677. var color = new BABYLON.Color4(0, 0, 0, 1);
  41678. _this.calculateError(v0, v1, p, n, uv, color);
  41679. var delTr = [];
  41680. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  41681. continue;
  41682. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  41683. continue;
  41684. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  41685. continue;
  41686. var uniqueArray = [];
  41687. delTr.forEach(function (deletedT) {
  41688. if (uniqueArray.indexOf(deletedT) === -1) {
  41689. deletedT.deletePending = true;
  41690. uniqueArray.push(deletedT);
  41691. }
  41692. });
  41693. if (uniqueArray.length % 2 !== 0) {
  41694. continue;
  41695. }
  41696. v0.q = v1.q.add(v0.q);
  41697. v0.updatePosition(p);
  41698. var tStart = _this.references.length;
  41699. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  41700. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  41701. var tCount = _this.references.length - tStart;
  41702. if (tCount <= v0.triangleCount) {
  41703. if (tCount) {
  41704. for (var c = 0; c < tCount; c++) {
  41705. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  41706. }
  41707. }
  41708. }
  41709. else {
  41710. v0.triangleStart = tStart;
  41711. }
  41712. v0.triangleCount = tCount;
  41713. break;
  41714. }
  41715. }
  41716. };
  41717. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  41718. }, 0);
  41719. };
  41720. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  41721. if (triangleCount - deletedTriangles <= targetCount)
  41722. loop.breakLoop();
  41723. else {
  41724. iterationFunction(loop.index, function () {
  41725. loop.executeNext();
  41726. });
  41727. }
  41728. }, function () {
  41729. setTimeout(function () {
  41730. //reconstruct this part of the mesh
  41731. _this.reconstructMesh(submeshIndex);
  41732. successCallback();
  41733. }, 0);
  41734. });
  41735. };
  41736. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  41737. var _this = this;
  41738. this.vertices = [];
  41739. this.triangles = [];
  41740. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41741. var indices = this._mesh.getIndices();
  41742. var submesh = this._mesh.subMeshes[submeshIndex];
  41743. var findInVertices = function (positionToSearch) {
  41744. if (optimizeMesh) {
  41745. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  41746. if (_this.vertices[ii].position.equals(positionToSearch)) {
  41747. return _this.vertices[ii];
  41748. }
  41749. }
  41750. }
  41751. return null;
  41752. };
  41753. var vertexReferences = [];
  41754. var vertexInit = function (i) {
  41755. var offset = i + submesh.verticesStart;
  41756. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  41757. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  41758. vertex.originalOffsets.push(offset);
  41759. if (vertex.id === _this.vertices.length) {
  41760. _this.vertices.push(vertex);
  41761. }
  41762. vertexReferences.push(vertex.id);
  41763. };
  41764. //var totalVertices = mesh.getTotalVertices();
  41765. var totalVertices = submesh.verticesCount;
  41766. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  41767. var indicesInit = function (i) {
  41768. var offset = (submesh.indexStart / 3) + i;
  41769. var pos = (offset * 3);
  41770. var i0 = indices[pos + 0];
  41771. var i1 = indices[pos + 1];
  41772. var i2 = indices[pos + 2];
  41773. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  41774. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  41775. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  41776. var triangle = new DecimationTriangle([v0, v1, v2]);
  41777. triangle.originalOffset = pos;
  41778. _this.triangles.push(triangle);
  41779. };
  41780. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  41781. _this.init(callback);
  41782. });
  41783. });
  41784. };
  41785. QuadraticErrorSimplification.prototype.init = function (callback) {
  41786. var _this = this;
  41787. var triangleInit1 = function (i) {
  41788. var t = _this.triangles[i];
  41789. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  41790. for (var j = 0; j < 3; j++) {
  41791. 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))));
  41792. }
  41793. };
  41794. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  41795. var triangleInit2 = function (i) {
  41796. var t = _this.triangles[i];
  41797. for (var j = 0; j < 3; ++j) {
  41798. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  41799. }
  41800. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  41801. };
  41802. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  41803. _this.initialized = true;
  41804. callback();
  41805. });
  41806. });
  41807. };
  41808. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  41809. var newTriangles = [];
  41810. var i;
  41811. for (i = 0; i < this.vertices.length; ++i) {
  41812. this.vertices[i].triangleCount = 0;
  41813. }
  41814. var t;
  41815. var j;
  41816. for (i = 0; i < this.triangles.length; ++i) {
  41817. if (!this.triangles[i].deleted) {
  41818. t = this.triangles[i];
  41819. for (j = 0; j < 3; ++j) {
  41820. t.vertices[j].triangleCount = 1;
  41821. }
  41822. newTriangles.push(t);
  41823. }
  41824. }
  41825. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  41826. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  41827. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  41828. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  41829. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41830. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41831. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41832. var vertexCount = 0;
  41833. for (i = 0; i < this.vertices.length; ++i) {
  41834. var vertex = this.vertices[i];
  41835. vertex.id = vertexCount;
  41836. if (vertex.triangleCount) {
  41837. vertex.originalOffsets.forEach(function (originalOffset) {
  41838. newPositionData.push(vertex.position.x);
  41839. newPositionData.push(vertex.position.y);
  41840. newPositionData.push(vertex.position.z);
  41841. newNormalData.push(normalData[originalOffset * 3]);
  41842. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  41843. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  41844. if (uvs && uvs.length) {
  41845. newUVsData.push(uvs[(originalOffset * 2)]);
  41846. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  41847. }
  41848. else if (colorsData && colorsData.length) {
  41849. newColorsData.push(colorsData[(originalOffset * 4)]);
  41850. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  41851. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  41852. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  41853. }
  41854. ++vertexCount;
  41855. });
  41856. }
  41857. }
  41858. var startingIndex = this._reconstructedMesh.getTotalIndices();
  41859. var startingVertex = this._reconstructedMesh.getTotalVertices();
  41860. var submeshesArray = this._reconstructedMesh.subMeshes;
  41861. this._reconstructedMesh.subMeshes = [];
  41862. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  41863. var originalIndices = this._mesh.getIndices();
  41864. for (i = 0; i < newTriangles.length; ++i) {
  41865. t = newTriangles[i]; //now get the new referencing point for each vertex
  41866. [0, 1, 2].forEach(function (idx) {
  41867. var id = originalIndices[t.originalOffset + idx];
  41868. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  41869. if (offset < 0)
  41870. offset = 0;
  41871. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  41872. });
  41873. }
  41874. //overwriting the old vertex buffers and indices.
  41875. this._reconstructedMesh.setIndices(newIndicesArray);
  41876. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  41877. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  41878. if (newUVsData.length > 0)
  41879. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  41880. if (newColorsData.length > 0)
  41881. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  41882. //create submesh
  41883. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  41884. if (submeshIndex > 0) {
  41885. this._reconstructedMesh.subMeshes = [];
  41886. submeshesArray.forEach(function (submesh) {
  41887. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  41888. });
  41889. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  41890. }
  41891. };
  41892. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  41893. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  41894. this._reconstructedMesh.material = this._mesh.material;
  41895. this._reconstructedMesh.parent = this._mesh.parent;
  41896. this._reconstructedMesh.isVisible = false;
  41897. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  41898. };
  41899. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  41900. for (var i = 0; i < vertex1.triangleCount; ++i) {
  41901. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  41902. if (t.deleted)
  41903. continue;
  41904. var s = this.references[vertex1.triangleStart + i].vertexId;
  41905. var v1 = t.vertices[(s + 1) % 3];
  41906. var v2 = t.vertices[(s + 2) % 3];
  41907. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  41908. deletedArray[i] = true;
  41909. delTr.push(t);
  41910. continue;
  41911. }
  41912. var d1 = v1.position.subtract(point);
  41913. d1 = d1.normalize();
  41914. var d2 = v2.position.subtract(point);
  41915. d2 = d2.normalize();
  41916. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  41917. return true;
  41918. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  41919. deletedArray[i] = false;
  41920. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  41921. return true;
  41922. }
  41923. return false;
  41924. };
  41925. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  41926. var newDeleted = deletedTriangles;
  41927. for (var i = 0; i < vertex.triangleCount; ++i) {
  41928. var ref = this.references[vertex.triangleStart + i];
  41929. var t = this.triangles[ref.triangleId];
  41930. if (t.deleted)
  41931. continue;
  41932. if (deletedArray[i] && t.deletePending) {
  41933. t.deleted = true;
  41934. newDeleted++;
  41935. continue;
  41936. }
  41937. t.vertices[ref.vertexId] = origVertex;
  41938. t.isDirty = true;
  41939. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  41940. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  41941. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  41942. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  41943. this.references.push(ref);
  41944. }
  41945. return newDeleted;
  41946. };
  41947. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  41948. for (var i = 0; i < this.vertices.length; ++i) {
  41949. var vCount = [];
  41950. var vId = [];
  41951. var v = this.vertices[i];
  41952. var j;
  41953. for (j = 0; j < v.triangleCount; ++j) {
  41954. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  41955. for (var ii = 0; ii < 3; ii++) {
  41956. var ofs = 0;
  41957. var vv = triangle.vertices[ii];
  41958. while (ofs < vCount.length) {
  41959. if (vId[ofs] === vv.id)
  41960. break;
  41961. ++ofs;
  41962. }
  41963. if (ofs === vCount.length) {
  41964. vCount.push(1);
  41965. vId.push(vv.id);
  41966. }
  41967. else {
  41968. vCount[ofs]++;
  41969. }
  41970. }
  41971. }
  41972. for (j = 0; j < vCount.length; ++j) {
  41973. if (vCount[j] === 1) {
  41974. this.vertices[vId[j]].isBorder = true;
  41975. }
  41976. else {
  41977. this.vertices[vId[j]].isBorder = false;
  41978. }
  41979. }
  41980. }
  41981. };
  41982. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  41983. if (identifyBorders === void 0) { identifyBorders = false; }
  41984. var i;
  41985. if (!identifyBorders) {
  41986. var newTrianglesVector = [];
  41987. for (i = 0; i < this.triangles.length; ++i) {
  41988. if (!this.triangles[i].deleted) {
  41989. newTrianglesVector.push(this.triangles[i]);
  41990. }
  41991. }
  41992. this.triangles = newTrianglesVector;
  41993. }
  41994. for (i = 0; i < this.vertices.length; ++i) {
  41995. this.vertices[i].triangleCount = 0;
  41996. this.vertices[i].triangleStart = 0;
  41997. }
  41998. var t;
  41999. var j;
  42000. var v;
  42001. for (i = 0; i < this.triangles.length; ++i) {
  42002. t = this.triangles[i];
  42003. for (j = 0; j < 3; ++j) {
  42004. v = t.vertices[j];
  42005. v.triangleCount++;
  42006. }
  42007. }
  42008. var tStart = 0;
  42009. for (i = 0; i < this.vertices.length; ++i) {
  42010. this.vertices[i].triangleStart = tStart;
  42011. tStart += this.vertices[i].triangleCount;
  42012. this.vertices[i].triangleCount = 0;
  42013. }
  42014. var newReferences = new Array(this.triangles.length * 3);
  42015. for (i = 0; i < this.triangles.length; ++i) {
  42016. t = this.triangles[i];
  42017. for (j = 0; j < 3; ++j) {
  42018. v = t.vertices[j];
  42019. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  42020. v.triangleCount++;
  42021. }
  42022. }
  42023. this.references = newReferences;
  42024. if (identifyBorders) {
  42025. this.identifyBorder();
  42026. }
  42027. };
  42028. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  42029. var x = point.x;
  42030. var y = point.y;
  42031. var z = point.z;
  42032. 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
  42033. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  42034. };
  42035. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  42036. var q = vertex1.q.add(vertex2.q);
  42037. var border = vertex1.isBorder && vertex2.isBorder;
  42038. var error = 0;
  42039. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  42040. if (qDet !== 0 && !border) {
  42041. if (!pointResult) {
  42042. pointResult = BABYLON.Vector3.Zero();
  42043. }
  42044. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  42045. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  42046. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  42047. error = this.vertexError(q, pointResult);
  42048. }
  42049. else {
  42050. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  42051. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  42052. var error1 = this.vertexError(q, vertex1.position);
  42053. var error2 = this.vertexError(q, vertex2.position);
  42054. var error3 = this.vertexError(q, p3);
  42055. error = Math.min(error1, error2, error3);
  42056. if (error === error1) {
  42057. if (pointResult) {
  42058. pointResult.copyFrom(vertex1.position);
  42059. }
  42060. }
  42061. else if (error === error2) {
  42062. if (pointResult) {
  42063. pointResult.copyFrom(vertex2.position);
  42064. }
  42065. }
  42066. else {
  42067. if (pointResult) {
  42068. pointResult.copyFrom(p3);
  42069. }
  42070. }
  42071. }
  42072. return error;
  42073. };
  42074. return QuadraticErrorSimplification;
  42075. }());
  42076. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  42077. })(BABYLON || (BABYLON = {}));
  42078. //# sourceMappingURL=../Mesh/babylon.meshSimplification.js.map
  42079. var BABYLON;
  42080. (function (BABYLON) {
  42081. var serializedGeometries = [];
  42082. var serializeGeometry = function (geometry, serializationGeometries) {
  42083. if (serializedGeometries[geometry.id]) {
  42084. return;
  42085. }
  42086. if (geometry.doNotSerialize) {
  42087. return;
  42088. }
  42089. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  42090. serializationGeometries.boxes.push(geometry.serialize());
  42091. }
  42092. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  42093. serializationGeometries.spheres.push(geometry.serialize());
  42094. }
  42095. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  42096. serializationGeometries.cylinders.push(geometry.serialize());
  42097. }
  42098. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  42099. serializationGeometries.toruses.push(geometry.serialize());
  42100. }
  42101. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  42102. serializationGeometries.grounds.push(geometry.serialize());
  42103. }
  42104. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  42105. serializationGeometries.planes.push(geometry.serialize());
  42106. }
  42107. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  42108. serializationGeometries.torusKnots.push(geometry.serialize());
  42109. }
  42110. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  42111. throw new Error("Unknown primitive type");
  42112. }
  42113. else {
  42114. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  42115. }
  42116. serializedGeometries[geometry.id] = true;
  42117. };
  42118. var serializeMesh = function (mesh, serializationScene) {
  42119. var serializationObject = {};
  42120. serializationObject.name = mesh.name;
  42121. serializationObject.id = mesh.id;
  42122. if (BABYLON.Tags.HasTags(mesh)) {
  42123. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  42124. }
  42125. serializationObject.position = mesh.position.asArray();
  42126. if (mesh.rotationQuaternion) {
  42127. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  42128. }
  42129. else if (mesh.rotation) {
  42130. serializationObject.rotation = mesh.rotation.asArray();
  42131. }
  42132. serializationObject.scaling = mesh.scaling.asArray();
  42133. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  42134. serializationObject.isEnabled = mesh.isEnabled();
  42135. serializationObject.isVisible = mesh.isVisible;
  42136. serializationObject.infiniteDistance = mesh.infiniteDistance;
  42137. serializationObject.pickable = mesh.isPickable;
  42138. serializationObject.receiveShadows = mesh.receiveShadows;
  42139. serializationObject.billboardMode = mesh.billboardMode;
  42140. serializationObject.visibility = mesh.visibility;
  42141. serializationObject.checkCollisions = mesh.checkCollisions;
  42142. serializationObject.isBlocker = mesh.isBlocker;
  42143. // Parent
  42144. if (mesh.parent) {
  42145. serializationObject.parentId = mesh.parent.id;
  42146. }
  42147. // Geometry
  42148. var geometry = mesh._geometry;
  42149. if (geometry) {
  42150. var geometryId = geometry.id;
  42151. serializationObject.geometryId = geometryId;
  42152. if (!mesh.getScene().getGeometryByID(geometryId)) {
  42153. // 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
  42154. serializeGeometry(geometry, serializationScene.geometries);
  42155. }
  42156. // SubMeshes
  42157. serializationObject.subMeshes = [];
  42158. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  42159. var subMesh = mesh.subMeshes[subIndex];
  42160. serializationObject.subMeshes.push({
  42161. materialIndex: subMesh.materialIndex,
  42162. verticesStart: subMesh.verticesStart,
  42163. verticesCount: subMesh.verticesCount,
  42164. indexStart: subMesh.indexStart,
  42165. indexCount: subMesh.indexCount
  42166. });
  42167. }
  42168. }
  42169. // Material
  42170. if (mesh.material) {
  42171. serializationObject.materialId = mesh.material.id;
  42172. }
  42173. else {
  42174. mesh.material = null;
  42175. }
  42176. // Skeleton
  42177. if (mesh.skeleton) {
  42178. serializationObject.skeletonId = mesh.skeleton.id;
  42179. }
  42180. // Physics
  42181. //TODO implement correct serialization for physics impostors.
  42182. if (mesh.getPhysicsImpostor()) {
  42183. serializationObject.physicsMass = mesh.getPhysicsMass();
  42184. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  42185. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  42186. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  42187. }
  42188. // Metadata
  42189. if (mesh.metadata) {
  42190. serializationObject.metadata = mesh.metadata;
  42191. }
  42192. // Instances
  42193. serializationObject.instances = [];
  42194. for (var index = 0; index < mesh.instances.length; index++) {
  42195. var instance = mesh.instances[index];
  42196. var serializationInstance = {
  42197. name: instance.name,
  42198. position: instance.position.asArray(),
  42199. scaling: instance.scaling.asArray()
  42200. };
  42201. if (instance.rotationQuaternion) {
  42202. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  42203. }
  42204. else if (instance.rotation) {
  42205. serializationInstance.rotation = instance.rotation.asArray();
  42206. }
  42207. serializationObject.instances.push(serializationInstance);
  42208. // Animations
  42209. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  42210. serializationInstance.ranges = instance.serializeAnimationRanges();
  42211. }
  42212. // Animations
  42213. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  42214. serializationObject.ranges = mesh.serializeAnimationRanges();
  42215. // Layer mask
  42216. serializationObject.layerMask = mesh.layerMask;
  42217. // Action Manager
  42218. if (mesh.actionManager) {
  42219. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  42220. }
  42221. return serializationObject;
  42222. };
  42223. var finalizeSingleMesh = function (mesh, serializationObject) {
  42224. //only works if the mesh is already loaded
  42225. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42226. //serialize material
  42227. if (mesh.material) {
  42228. if (mesh.material instanceof BABYLON.StandardMaterial) {
  42229. serializationObject.materials = serializationObject.materials || [];
  42230. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42231. serializationObject.materials.push(mesh.material.serialize());
  42232. }
  42233. }
  42234. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  42235. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  42236. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42237. serializationObject.multiMaterials.push(mesh.material.serialize());
  42238. }
  42239. }
  42240. }
  42241. //serialize geometry
  42242. var geometry = mesh._geometry;
  42243. if (geometry) {
  42244. if (!serializationObject.geometries) {
  42245. serializationObject.geometries = {};
  42246. serializationObject.geometries.boxes = [];
  42247. serializationObject.geometries.spheres = [];
  42248. serializationObject.geometries.cylinders = [];
  42249. serializationObject.geometries.toruses = [];
  42250. serializationObject.geometries.grounds = [];
  42251. serializationObject.geometries.planes = [];
  42252. serializationObject.geometries.torusKnots = [];
  42253. serializationObject.geometries.vertexData = [];
  42254. }
  42255. serializeGeometry(geometry, serializationObject.geometries);
  42256. }
  42257. // Skeletons
  42258. if (mesh.skeleton) {
  42259. serializationObject.skeletons = serializationObject.skeletons || [];
  42260. serializationObject.skeletons.push(mesh.skeleton.serialize());
  42261. }
  42262. //serialize the actual mesh
  42263. serializationObject.meshes = serializationObject.meshes || [];
  42264. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  42265. }
  42266. };
  42267. var SceneSerializer = (function () {
  42268. function SceneSerializer() {
  42269. }
  42270. SceneSerializer.ClearCache = function () {
  42271. serializedGeometries = [];
  42272. };
  42273. SceneSerializer.Serialize = function (scene) {
  42274. var serializationObject = {};
  42275. // Scene
  42276. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  42277. serializationObject.autoClear = scene.autoClear;
  42278. serializationObject.clearColor = scene.clearColor.asArray();
  42279. serializationObject.ambientColor = scene.ambientColor.asArray();
  42280. serializationObject.gravity = scene.gravity.asArray();
  42281. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  42282. serializationObject.workerCollisions = scene.workerCollisions;
  42283. // Fog
  42284. if (scene.fogMode && scene.fogMode !== 0) {
  42285. serializationObject.fogMode = scene.fogMode;
  42286. serializationObject.fogColor = scene.fogColor.asArray();
  42287. serializationObject.fogStart = scene.fogStart;
  42288. serializationObject.fogEnd = scene.fogEnd;
  42289. serializationObject.fogDensity = scene.fogDensity;
  42290. }
  42291. //Physics
  42292. if (scene.isPhysicsEnabled()) {
  42293. serializationObject.physicsEnabled = true;
  42294. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  42295. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  42296. }
  42297. // Metadata
  42298. if (scene.metadata) {
  42299. serializationObject.metadata = scene.metadata;
  42300. }
  42301. // Lights
  42302. serializationObject.lights = [];
  42303. var index;
  42304. var light;
  42305. for (index = 0; index < scene.lights.length; index++) {
  42306. light = scene.lights[index];
  42307. if (!light.doNotSerialize) {
  42308. serializationObject.lights.push(light.serialize());
  42309. }
  42310. }
  42311. // Cameras
  42312. serializationObject.cameras = [];
  42313. for (index = 0; index < scene.cameras.length; index++) {
  42314. var camera = scene.cameras[index];
  42315. if (!camera.doNotSerialize) {
  42316. serializationObject.cameras.push(camera.serialize());
  42317. }
  42318. }
  42319. if (scene.activeCamera) {
  42320. serializationObject.activeCameraID = scene.activeCamera.id;
  42321. }
  42322. // Animations
  42323. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  42324. // Materials
  42325. serializationObject.materials = [];
  42326. serializationObject.multiMaterials = [];
  42327. var material;
  42328. for (index = 0; index < scene.materials.length; index++) {
  42329. material = scene.materials[index];
  42330. if (!material.doNotSerialize) {
  42331. serializationObject.materials.push(material.serialize());
  42332. }
  42333. }
  42334. // MultiMaterials
  42335. serializationObject.multiMaterials = [];
  42336. for (index = 0; index < scene.multiMaterials.length; index++) {
  42337. var multiMaterial = scene.multiMaterials[index];
  42338. serializationObject.multiMaterials.push(multiMaterial.serialize());
  42339. }
  42340. // Skeletons
  42341. serializationObject.skeletons = [];
  42342. for (index = 0; index < scene.skeletons.length; index++) {
  42343. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  42344. }
  42345. // Geometries
  42346. serializationObject.geometries = {};
  42347. serializationObject.geometries.boxes = [];
  42348. serializationObject.geometries.spheres = [];
  42349. serializationObject.geometries.cylinders = [];
  42350. serializationObject.geometries.toruses = [];
  42351. serializationObject.geometries.grounds = [];
  42352. serializationObject.geometries.planes = [];
  42353. serializationObject.geometries.torusKnots = [];
  42354. serializationObject.geometries.vertexData = [];
  42355. serializedGeometries = [];
  42356. var geometries = scene.getGeometries();
  42357. for (index = 0; index < geometries.length; index++) {
  42358. var geometry = geometries[index];
  42359. if (geometry.isReady()) {
  42360. serializeGeometry(geometry, serializationObject.geometries);
  42361. }
  42362. }
  42363. // Meshes
  42364. serializationObject.meshes = [];
  42365. for (index = 0; index < scene.meshes.length; index++) {
  42366. var abstractMesh = scene.meshes[index];
  42367. if (abstractMesh instanceof BABYLON.Mesh) {
  42368. var mesh = abstractMesh;
  42369. if (!mesh.doNotSerialize) {
  42370. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42371. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  42372. }
  42373. }
  42374. }
  42375. }
  42376. // Particles Systems
  42377. serializationObject.particleSystems = [];
  42378. for (index = 0; index < scene.particleSystems.length; index++) {
  42379. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  42380. }
  42381. // Lens flares
  42382. serializationObject.lensFlareSystems = [];
  42383. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  42384. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  42385. }
  42386. // Shadows
  42387. serializationObject.shadowGenerators = [];
  42388. for (index = 0; index < scene.lights.length; index++) {
  42389. light = scene.lights[index];
  42390. var shadowGenerator = light.getShadowGenerator();
  42391. // Only support serialization for official generator so far.
  42392. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  42393. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  42394. }
  42395. }
  42396. // Action Manager
  42397. if (scene.actionManager) {
  42398. serializationObject.actions = scene.actionManager.serialize("scene");
  42399. }
  42400. // Audio
  42401. serializationObject.sounds = [];
  42402. for (index = 0; index < scene.soundTracks.length; index++) {
  42403. var soundtrack = scene.soundTracks[index];
  42404. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  42405. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  42406. }
  42407. }
  42408. return serializationObject;
  42409. };
  42410. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  42411. if (withParents === void 0) { withParents = false; }
  42412. if (withChildren === void 0) { withChildren = false; }
  42413. var serializationObject = {};
  42414. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  42415. if (withParents || withChildren) {
  42416. //deliberate for loop! not for each, appended should be processed as well.
  42417. for (var i = 0; i < toSerialize.length; ++i) {
  42418. if (withChildren) {
  42419. toSerialize[i].getDescendants().forEach(function (node) {
  42420. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  42421. toSerialize.push(node);
  42422. }
  42423. });
  42424. }
  42425. //make sure the array doesn't contain the object already
  42426. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  42427. toSerialize.push(toSerialize[i].parent);
  42428. }
  42429. }
  42430. }
  42431. toSerialize.forEach(function (mesh) {
  42432. finalizeSingleMesh(mesh, serializationObject);
  42433. });
  42434. return serializationObject;
  42435. };
  42436. return SceneSerializer;
  42437. }());
  42438. BABYLON.SceneSerializer = SceneSerializer;
  42439. })(BABYLON || (BABYLON = {}));
  42440. //# sourceMappingURL=../Tools/babylon.sceneSerializer.js.map
  42441. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  42442. // Huge respect for a such great lib.
  42443. // Earcut license:
  42444. // Copyright (c) 2016, Mapbox
  42445. //
  42446. // Permission to use, copy, modify, and/or distribute this software for any purpose
  42447. // with or without fee is hereby granted, provided that the above copyright notice
  42448. // and this permission notice appear in all copies.
  42449. //
  42450. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  42451. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  42452. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  42453. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  42454. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  42455. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  42456. // THIS SOFTWARE.
  42457. var Earcut;
  42458. (function (Earcut) {
  42459. /**
  42460. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  42461. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  42462. * @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).
  42463. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  42464. */
  42465. function earcut(data, holeIndices, dim) {
  42466. dim = dim || 2;
  42467. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  42468. if (!outerNode)
  42469. return triangles;
  42470. var minX, minY, maxX, maxY, x, y, size;
  42471. if (hasHoles)
  42472. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  42473. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  42474. if (data.length > 80 * dim) {
  42475. minX = maxX = data[0];
  42476. minY = maxY = data[1];
  42477. for (var i = dim; i < outerLen; i += dim) {
  42478. x = data[i];
  42479. y = data[i + 1];
  42480. if (x < minX)
  42481. minX = x;
  42482. if (y < minY)
  42483. minY = y;
  42484. if (x > maxX)
  42485. maxX = x;
  42486. if (y > maxY)
  42487. maxY = y;
  42488. }
  42489. // minX, minY and size are later used to transform coords into integers for z-order calculation
  42490. size = Math.max(maxX - minX, maxY - minY);
  42491. }
  42492. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  42493. return triangles;
  42494. }
  42495. Earcut.earcut = earcut;
  42496. // create a circular doubly linked list from polygon points in the specified winding order
  42497. function linkedList(data, start, end, dim, clockwise) {
  42498. var i, last;
  42499. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  42500. for (i = start; i < end; i += dim)
  42501. last = insertNode(i, data[i], data[i + 1], last);
  42502. }
  42503. else {
  42504. for (i = end - dim; i >= start; i -= dim)
  42505. last = insertNode(i, data[i], data[i + 1], last);
  42506. }
  42507. if (last && equals(last, last.next)) {
  42508. removeNode(last);
  42509. last = last.next;
  42510. }
  42511. return last;
  42512. }
  42513. // eliminate colinear or duplicate points
  42514. function filterPoints(start, end) {
  42515. if (!start)
  42516. return start;
  42517. if (!end)
  42518. end = start;
  42519. var p = start, again;
  42520. do {
  42521. again = false;
  42522. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  42523. removeNode(p);
  42524. p = end = p.prev;
  42525. if (p === p.next)
  42526. return null;
  42527. again = true;
  42528. }
  42529. else {
  42530. p = p.next;
  42531. }
  42532. } while (again || p !== end);
  42533. return end;
  42534. }
  42535. // main ear slicing loop which triangulates a polygon (given as a linked list)
  42536. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  42537. if (!ear)
  42538. return;
  42539. // interlink polygon nodes in z-order
  42540. if (!pass && size)
  42541. indexCurve(ear, minX, minY, size);
  42542. var stop = ear, prev, next;
  42543. // iterate through ears, slicing them one by one
  42544. while (ear.prev !== ear.next) {
  42545. prev = ear.prev;
  42546. next = ear.next;
  42547. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  42548. // cut off the triangle
  42549. triangles.push(prev.i / dim);
  42550. triangles.push(ear.i / dim);
  42551. triangles.push(next.i / dim);
  42552. removeNode(ear);
  42553. // skipping the next vertice leads to less sliver triangles
  42554. ear = next.next;
  42555. stop = next.next;
  42556. continue;
  42557. }
  42558. ear = next;
  42559. // if we looped through the whole remaining polygon and can't find any more ears
  42560. if (ear === stop) {
  42561. // try filtering points and slicing again
  42562. if (!pass) {
  42563. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  42564. }
  42565. else if (pass === 1) {
  42566. ear = cureLocalIntersections(ear, triangles, dim);
  42567. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  42568. }
  42569. else if (pass === 2) {
  42570. splitEarcut(ear, triangles, dim, minX, minY, size);
  42571. }
  42572. break;
  42573. }
  42574. }
  42575. }
  42576. // check whether a polygon node forms a valid ear with adjacent nodes
  42577. function isEar(ear) {
  42578. var a = ear.prev, b = ear, c = ear.next;
  42579. if (area(a, b, c) >= 0)
  42580. return false; // reflex, can't be an ear
  42581. // now make sure we don't have other points inside the potential ear
  42582. var p = ear.next.next;
  42583. while (p !== ear.prev) {
  42584. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  42585. area(p.prev, p, p.next) >= 0)
  42586. return false;
  42587. p = p.next;
  42588. }
  42589. return true;
  42590. }
  42591. function isEarHashed(ear, minX, minY, size) {
  42592. var a = ear.prev, b = ear, c = ear.next;
  42593. if (area(a, b, c) >= 0)
  42594. return false; // reflex, can't be an ear
  42595. // triangle bbox; min & max are calculated like this for speed
  42596. 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);
  42597. // z-order range for the current triangle bbox;
  42598. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  42599. // first look for points inside the triangle in increasing z-order
  42600. var p = ear.nextZ;
  42601. while (p && p.z <= maxZ) {
  42602. if (p !== ear.prev &&
  42603. p !== ear.next &&
  42604. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  42605. area(p.prev, p, p.next) >= 0)
  42606. return false;
  42607. p = p.nextZ;
  42608. }
  42609. // then look for points in decreasing z-order
  42610. p = ear.prevZ;
  42611. while (p && p.z >= minZ) {
  42612. if (p !== ear.prev &&
  42613. p !== ear.next &&
  42614. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  42615. area(p.prev, p, p.next) >= 0)
  42616. return false;
  42617. p = p.prevZ;
  42618. }
  42619. return true;
  42620. }
  42621. // go through all polygon nodes and cure small local self-intersections
  42622. function cureLocalIntersections(start, triangles, dim) {
  42623. var p = start;
  42624. do {
  42625. var a = p.prev, b = p.next.next;
  42626. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  42627. triangles.push(a.i / dim);
  42628. triangles.push(p.i / dim);
  42629. triangles.push(b.i / dim);
  42630. // remove two nodes involved
  42631. removeNode(p);
  42632. removeNode(p.next);
  42633. p = start = b;
  42634. }
  42635. p = p.next;
  42636. } while (p !== start);
  42637. return p;
  42638. }
  42639. // try splitting polygon into two and triangulate them independently
  42640. function splitEarcut(start, triangles, dim, minX, minY, size) {
  42641. // look for a valid diagonal that divides the polygon into two
  42642. var a = start;
  42643. do {
  42644. var b = a.next.next;
  42645. while (b !== a.prev) {
  42646. if (a.i !== b.i && isValidDiagonal(a, b)) {
  42647. // split the polygon in two by the diagonal
  42648. var c = splitPolygon(a, b);
  42649. // filter colinear points around the cuts
  42650. a = filterPoints(a, a.next);
  42651. c = filterPoints(c, c.next);
  42652. // run earcut on each half
  42653. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  42654. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  42655. return;
  42656. }
  42657. b = b.next;
  42658. }
  42659. a = a.next;
  42660. } while (a !== start);
  42661. }
  42662. // link every hole into the outer loop, producing a single-ring polygon without holes
  42663. function eliminateHoles(data, holeIndices, outerNode, dim) {
  42664. var queue = [], i, len, start, end, list;
  42665. for (i = 0, len = holeIndices.length; i < len; i++) {
  42666. start = holeIndices[i] * dim;
  42667. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  42668. list = linkedList(data, start, end, dim, false);
  42669. if (list === list.next)
  42670. list.steiner = true;
  42671. queue.push(getLeftmost(list));
  42672. }
  42673. queue.sort(compareX);
  42674. // process holes from left to right
  42675. for (i = 0; i < queue.length; i++) {
  42676. eliminateHole(queue[i], outerNode);
  42677. outerNode = filterPoints(outerNode, outerNode.next);
  42678. }
  42679. return outerNode;
  42680. }
  42681. function compareX(a, b) {
  42682. return a.x - b.x;
  42683. }
  42684. // find a bridge between vertices that connects hole with an outer ring and and link it
  42685. function eliminateHole(hole, outerNode) {
  42686. outerNode = findHoleBridge(hole, outerNode);
  42687. if (outerNode) {
  42688. var b = splitPolygon(outerNode, hole);
  42689. filterPoints(b, b.next);
  42690. }
  42691. }
  42692. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  42693. function findHoleBridge(hole, outerNode) {
  42694. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  42695. // find a segment intersected by a ray from the hole's leftmost point to the left;
  42696. // segment's endpoint with lesser x will be potential connection point
  42697. do {
  42698. if (hy <= p.y && hy >= p.next.y) {
  42699. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  42700. if (x <= hx && x > qx) {
  42701. qx = x;
  42702. if (x === hx) {
  42703. if (hy === p.y)
  42704. return p;
  42705. if (hy === p.next.y)
  42706. return p.next;
  42707. }
  42708. m = p.x < p.next.x ? p : p.next;
  42709. }
  42710. }
  42711. p = p.next;
  42712. } while (p !== outerNode);
  42713. if (!m)
  42714. return null;
  42715. if (hx === qx)
  42716. return m.prev; // hole touches outer segment; pick lower endpoint
  42717. // look for points inside the triangle of hole point, segment intersection and endpoint;
  42718. // if there are no points found, we have a valid connection;
  42719. // otherwise choose the point of the minimum angle with the ray as connection point
  42720. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  42721. p = m.next;
  42722. while (p !== stop) {
  42723. if (hx >= p.x &&
  42724. p.x >= mx &&
  42725. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  42726. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  42727. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  42728. m = p;
  42729. tanMin = tan;
  42730. }
  42731. }
  42732. p = p.next;
  42733. }
  42734. return m;
  42735. }
  42736. // interlink polygon nodes in z-order
  42737. function indexCurve(start, minX, minY, size) {
  42738. var p = start;
  42739. do {
  42740. if (p.z === null)
  42741. p.z = zOrder(p.x, p.y, minX, minY, size);
  42742. p.prevZ = p.prev;
  42743. p.nextZ = p.next;
  42744. p = p.next;
  42745. } while (p !== start);
  42746. p.prevZ.nextZ = null;
  42747. p.prevZ = null;
  42748. sortLinked(p);
  42749. }
  42750. // Simon Tatham's linked list merge sort algorithm
  42751. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  42752. function sortLinked(list) {
  42753. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  42754. do {
  42755. p = list;
  42756. list = null;
  42757. tail = null;
  42758. numMerges = 0;
  42759. while (p) {
  42760. numMerges++;
  42761. q = p;
  42762. pSize = 0;
  42763. for (i = 0; i < inSize; i++) {
  42764. pSize++;
  42765. q = q.nextZ;
  42766. if (!q)
  42767. break;
  42768. }
  42769. qSize = inSize;
  42770. while (pSize > 0 || (qSize > 0 && q)) {
  42771. if (pSize === 0) {
  42772. e = q;
  42773. q = q.nextZ;
  42774. qSize--;
  42775. }
  42776. else if (qSize === 0 || !q) {
  42777. e = p;
  42778. p = p.nextZ;
  42779. pSize--;
  42780. }
  42781. else if (p.z <= q.z) {
  42782. e = p;
  42783. p = p.nextZ;
  42784. pSize--;
  42785. }
  42786. else {
  42787. e = q;
  42788. q = q.nextZ;
  42789. qSize--;
  42790. }
  42791. if (tail)
  42792. tail.nextZ = e;
  42793. else
  42794. list = e;
  42795. e.prevZ = tail;
  42796. tail = e;
  42797. }
  42798. p = q;
  42799. }
  42800. tail.nextZ = null;
  42801. inSize *= 2;
  42802. } while (numMerges > 1);
  42803. return list;
  42804. }
  42805. // z-order of a point given coords and size of the data bounding box
  42806. function zOrder(x, y, minX, minY, size) {
  42807. // coords are transformed into non-negative 15-bit integer range
  42808. x = 32767 * (x - minX) / size;
  42809. y = 32767 * (y - minY) / size;
  42810. x = (x | (x << 8)) & 0x00FF00FF;
  42811. x = (x | (x << 4)) & 0x0F0F0F0F;
  42812. x = (x | (x << 2)) & 0x33333333;
  42813. x = (x | (x << 1)) & 0x55555555;
  42814. y = (y | (y << 8)) & 0x00FF00FF;
  42815. y = (y | (y << 4)) & 0x0F0F0F0F;
  42816. y = (y | (y << 2)) & 0x33333333;
  42817. y = (y | (y << 1)) & 0x55555555;
  42818. return x | (y << 1);
  42819. }
  42820. // find the leftmost node of a polygon ring
  42821. function getLeftmost(start) {
  42822. var p = start, leftmost = start;
  42823. do {
  42824. if (p.x < leftmost.x)
  42825. leftmost = p;
  42826. p = p.next;
  42827. } while (p !== start);
  42828. return leftmost;
  42829. }
  42830. // check if a point lies within a convex triangle
  42831. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  42832. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  42833. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  42834. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  42835. }
  42836. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  42837. function isValidDiagonal(a, b) {
  42838. return a.next.i !== b.i &&
  42839. a.prev.i !== b.i &&
  42840. !intersectsPolygon(a, b) &&
  42841. locallyInside(a, b) &&
  42842. locallyInside(b, a) &&
  42843. middleInside(a, b);
  42844. }
  42845. // signed area of a triangle
  42846. function area(p, q, r) {
  42847. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  42848. }
  42849. // check if two points are equal
  42850. function equals(p1, p2) {
  42851. return p1.x === p2.x && p1.y === p2.y;
  42852. }
  42853. // check if two segments intersect
  42854. function intersects(p1, q1, p2, q2) {
  42855. if ((equals(p1, q1) && equals(p2, q2)) ||
  42856. (equals(p1, q2) && equals(p2, q1)))
  42857. return true;
  42858. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  42859. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  42860. }
  42861. // check if a polygon diagonal intersects any polygon segments
  42862. function intersectsPolygon(a, b) {
  42863. var p = a;
  42864. do {
  42865. if (p.i !== a.i &&
  42866. p.next.i !== a.i &&
  42867. p.i !== b.i &&
  42868. p.next.i !== b.i &&
  42869. intersects(p, p.next, a, b))
  42870. return true;
  42871. p = p.next;
  42872. } while (p !== a);
  42873. return false;
  42874. }
  42875. // check if a polygon diagonal is locally inside the polygon
  42876. function locallyInside(a, b) {
  42877. return area(a.prev, a, a.next) < 0
  42878. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  42879. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  42880. }
  42881. // check if the middle point of a polygon diagonal is inside the polygon
  42882. function middleInside(a, b) {
  42883. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  42884. do {
  42885. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  42886. inside = !inside;
  42887. p = p.next;
  42888. } while (p !== a);
  42889. return inside;
  42890. }
  42891. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  42892. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  42893. function splitPolygon(a, b) {
  42894. 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;
  42895. a.next = b;
  42896. b.prev = a;
  42897. a2.next = an;
  42898. an.prev = a2;
  42899. b2.next = a2;
  42900. a2.prev = b2;
  42901. bp.next = b2;
  42902. b2.prev = bp;
  42903. return b2;
  42904. }
  42905. // create a node and optionally link it with previous one (in a circular doubly linked list)
  42906. function insertNode(i, x, y, last) {
  42907. var p = new Node(i, x, y);
  42908. if (!last) {
  42909. p.prev = p;
  42910. p.next = p;
  42911. }
  42912. else {
  42913. p.next = last.next;
  42914. p.prev = last;
  42915. last.next.prev = p;
  42916. last.next = p;
  42917. }
  42918. return p;
  42919. }
  42920. function removeNode(p) {
  42921. p.next.prev = p.prev;
  42922. p.prev.next = p.next;
  42923. if (p.prevZ)
  42924. p.prevZ.nextZ = p.nextZ;
  42925. if (p.nextZ)
  42926. p.nextZ.prevZ = p.prevZ;
  42927. }
  42928. function Node(i, x, y) {
  42929. // vertice index in coordinates array
  42930. this.i = i;
  42931. // vertex coordinates
  42932. this.x = x;
  42933. this.y = y;
  42934. // previous and next vertice nodes in a polygon ring
  42935. this.prev = null;
  42936. this.next = null;
  42937. // z-order curve value
  42938. this.z = null;
  42939. // previous and next nodes in z-order
  42940. this.prevZ = null;
  42941. this.nextZ = null;
  42942. // indicates whether this is a steiner point
  42943. this.steiner = false;
  42944. }
  42945. /**
  42946. * return a percentage difference between the polygon area and its triangulation area;
  42947. * used to verify correctness of triangulation
  42948. */
  42949. function deviation(data, holeIndices, dim, triangles) {
  42950. var hasHoles = holeIndices && holeIndices.length;
  42951. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  42952. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  42953. if (hasHoles) {
  42954. for (var i = 0, len = holeIndices.length; i < len; i++) {
  42955. var start = holeIndices[i] * dim;
  42956. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  42957. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  42958. }
  42959. }
  42960. var trianglesArea = 0;
  42961. for (i = 0; i < triangles.length; i += 3) {
  42962. var a = triangles[i] * dim;
  42963. var b = triangles[i + 1] * dim;
  42964. var c = triangles[i + 2] * dim;
  42965. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  42966. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  42967. }
  42968. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  42969. }
  42970. Earcut.deviation = deviation;
  42971. ;
  42972. function signedArea(data, start, end, dim) {
  42973. var sum = 0;
  42974. for (var i = start, j = end - dim; i < end; i += dim) {
  42975. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  42976. j = i;
  42977. }
  42978. return sum;
  42979. }
  42980. /**
  42981. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  42982. */
  42983. function flatten(data) {
  42984. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  42985. for (var i = 0; i < data.length; i++) {
  42986. for (var j = 0; j < data[i].length; j++) {
  42987. for (var d = 0; d < dim; d++)
  42988. result.vertices.push(data[i][j][d]);
  42989. }
  42990. if (i > 0) {
  42991. holeIndex += data[i - 1].length;
  42992. result.holes.push(holeIndex);
  42993. }
  42994. }
  42995. return result;
  42996. }
  42997. Earcut.flatten = flatten;
  42998. ;
  42999. })(Earcut || (Earcut = {}));
  43000. //# sourceMappingURL=../Tools/babylon.earcut.js.map
  43001. var BABYLON;
  43002. (function (BABYLON) {
  43003. // Unique ID when we import meshes from Babylon to CSG
  43004. var currentCSGMeshId = 0;
  43005. // # class Vertex
  43006. // Represents a vertex of a polygon. Use your own vertex class instead of this
  43007. // one to provide additional features like texture coordinates and vertex
  43008. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  43009. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  43010. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  43011. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  43012. // is not used anywhere else.
  43013. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  43014. var Vertex = (function () {
  43015. function Vertex(pos, normal, uv) {
  43016. this.pos = pos;
  43017. this.normal = normal;
  43018. this.uv = uv;
  43019. }
  43020. Vertex.prototype.clone = function () {
  43021. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  43022. };
  43023. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  43024. // orientation of a polygon is flipped.
  43025. Vertex.prototype.flip = function () {
  43026. this.normal = this.normal.scale(-1);
  43027. };
  43028. // Create a new vertex between this vertex and `other` by linearly
  43029. // interpolating all properties using a parameter of `t`. Subclasses should
  43030. // override this to interpolate additional properties.
  43031. Vertex.prototype.interpolate = function (other, t) {
  43032. 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));
  43033. };
  43034. return Vertex;
  43035. }());
  43036. // # class Plane
  43037. // Represents a plane in 3D space.
  43038. var Plane = (function () {
  43039. function Plane(normal, w) {
  43040. this.normal = normal;
  43041. this.w = w;
  43042. }
  43043. Plane.FromPoints = function (a, b, c) {
  43044. var v0 = c.subtract(a);
  43045. var v1 = b.subtract(a);
  43046. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  43047. return null;
  43048. }
  43049. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  43050. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  43051. };
  43052. Plane.prototype.clone = function () {
  43053. return new Plane(this.normal.clone(), this.w);
  43054. };
  43055. Plane.prototype.flip = function () {
  43056. this.normal.scaleInPlace(-1);
  43057. this.w = -this.w;
  43058. };
  43059. // Split `polygon` by this plane if needed, then put the polygon or polygon
  43060. // fragments in the appropriate lists. Coplanar polygons go into either
  43061. // `coplanarFront` or `coplanarBack` depending on their orientation with
  43062. // respect to this plane. Polygons in front or in back of this plane go into
  43063. // either `front` or `back`.
  43064. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  43065. var COPLANAR = 0;
  43066. var FRONT = 1;
  43067. var BACK = 2;
  43068. var SPANNING = 3;
  43069. // Classify each point as well as the entire polygon into one of the above
  43070. // four classes.
  43071. var polygonType = 0;
  43072. var types = [];
  43073. var i;
  43074. var t;
  43075. for (i = 0; i < polygon.vertices.length; i++) {
  43076. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  43077. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  43078. polygonType |= type;
  43079. types.push(type);
  43080. }
  43081. // Put the polygon in the correct list, splitting it when necessary.
  43082. switch (polygonType) {
  43083. case COPLANAR:
  43084. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  43085. break;
  43086. case FRONT:
  43087. front.push(polygon);
  43088. break;
  43089. case BACK:
  43090. back.push(polygon);
  43091. break;
  43092. case SPANNING:
  43093. var f = [], b = [];
  43094. for (i = 0; i < polygon.vertices.length; i++) {
  43095. var j = (i + 1) % polygon.vertices.length;
  43096. var ti = types[i], tj = types[j];
  43097. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  43098. if (ti !== BACK)
  43099. f.push(vi);
  43100. if (ti !== FRONT)
  43101. b.push(ti !== BACK ? vi.clone() : vi);
  43102. if ((ti | tj) === SPANNING) {
  43103. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  43104. var v = vi.interpolate(vj, t);
  43105. f.push(v);
  43106. b.push(v.clone());
  43107. }
  43108. }
  43109. var poly;
  43110. if (f.length >= 3) {
  43111. poly = new Polygon(f, polygon.shared);
  43112. if (poly.plane)
  43113. front.push(poly);
  43114. }
  43115. if (b.length >= 3) {
  43116. poly = new Polygon(b, polygon.shared);
  43117. if (poly.plane)
  43118. back.push(poly);
  43119. }
  43120. break;
  43121. }
  43122. };
  43123. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  43124. // point is on the plane.
  43125. Plane.EPSILON = 1e-5;
  43126. return Plane;
  43127. }());
  43128. // # class Polygon
  43129. // Represents a convex polygon. The vertices used to initialize a polygon must
  43130. // be coplanar and form a convex loop.
  43131. //
  43132. // Each convex polygon has a `shared` property, which is shared between all
  43133. // polygons that are clones of each other or were split from the same polygon.
  43134. // This can be used to define per-polygon properties (such as surface color).
  43135. var Polygon = (function () {
  43136. function Polygon(vertices, shared) {
  43137. this.vertices = vertices;
  43138. this.shared = shared;
  43139. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  43140. }
  43141. Polygon.prototype.clone = function () {
  43142. var vertices = this.vertices.map(function (v) { return v.clone(); });
  43143. return new Polygon(vertices, this.shared);
  43144. };
  43145. Polygon.prototype.flip = function () {
  43146. this.vertices.reverse().map(function (v) { v.flip(); });
  43147. this.plane.flip();
  43148. };
  43149. return Polygon;
  43150. }());
  43151. // # class Node
  43152. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  43153. // by picking a polygon to split along. That polygon (and all other coplanar
  43154. // polygons) are added directly to that node and the other polygons are added to
  43155. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  43156. // no distinction between internal and leaf nodes.
  43157. var Node = (function () {
  43158. function Node(polygons) {
  43159. this.plane = null;
  43160. this.front = null;
  43161. this.back = null;
  43162. this.polygons = [];
  43163. if (polygons) {
  43164. this.build(polygons);
  43165. }
  43166. }
  43167. Node.prototype.clone = function () {
  43168. var node = new Node();
  43169. node.plane = this.plane && this.plane.clone();
  43170. node.front = this.front && this.front.clone();
  43171. node.back = this.back && this.back.clone();
  43172. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  43173. return node;
  43174. };
  43175. // Convert solid space to empty space and empty space to solid space.
  43176. Node.prototype.invert = function () {
  43177. for (var i = 0; i < this.polygons.length; i++) {
  43178. this.polygons[i].flip();
  43179. }
  43180. if (this.plane) {
  43181. this.plane.flip();
  43182. }
  43183. if (this.front) {
  43184. this.front.invert();
  43185. }
  43186. if (this.back) {
  43187. this.back.invert();
  43188. }
  43189. var temp = this.front;
  43190. this.front = this.back;
  43191. this.back = temp;
  43192. };
  43193. // Recursively remove all polygons in `polygons` that are inside this BSP
  43194. // tree.
  43195. Node.prototype.clipPolygons = function (polygons) {
  43196. if (!this.plane)
  43197. return polygons.slice();
  43198. var front = [], back = [];
  43199. for (var i = 0; i < polygons.length; i++) {
  43200. this.plane.splitPolygon(polygons[i], front, back, front, back);
  43201. }
  43202. if (this.front) {
  43203. front = this.front.clipPolygons(front);
  43204. }
  43205. if (this.back) {
  43206. back = this.back.clipPolygons(back);
  43207. }
  43208. else {
  43209. back = [];
  43210. }
  43211. return front.concat(back);
  43212. };
  43213. // Remove all polygons in this BSP tree that are inside the other BSP tree
  43214. // `bsp`.
  43215. Node.prototype.clipTo = function (bsp) {
  43216. this.polygons = bsp.clipPolygons(this.polygons);
  43217. if (this.front)
  43218. this.front.clipTo(bsp);
  43219. if (this.back)
  43220. this.back.clipTo(bsp);
  43221. };
  43222. // Return a list of all polygons in this BSP tree.
  43223. Node.prototype.allPolygons = function () {
  43224. var polygons = this.polygons.slice();
  43225. if (this.front)
  43226. polygons = polygons.concat(this.front.allPolygons());
  43227. if (this.back)
  43228. polygons = polygons.concat(this.back.allPolygons());
  43229. return polygons;
  43230. };
  43231. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  43232. // new polygons are filtered down to the bottom of the tree and become new
  43233. // nodes there. Each set of polygons is partitioned using the first polygon
  43234. // (no heuristic is used to pick a good split).
  43235. Node.prototype.build = function (polygons) {
  43236. if (!polygons.length)
  43237. return;
  43238. if (!this.plane)
  43239. this.plane = polygons[0].plane.clone();
  43240. var front = [], back = [];
  43241. for (var i = 0; i < polygons.length; i++) {
  43242. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  43243. }
  43244. if (front.length) {
  43245. if (!this.front)
  43246. this.front = new Node();
  43247. this.front.build(front);
  43248. }
  43249. if (back.length) {
  43250. if (!this.back)
  43251. this.back = new Node();
  43252. this.back.build(back);
  43253. }
  43254. };
  43255. return Node;
  43256. }());
  43257. var CSG = (function () {
  43258. function CSG() {
  43259. this.polygons = new Array();
  43260. }
  43261. // Convert BABYLON.Mesh to BABYLON.CSG
  43262. CSG.FromMesh = function (mesh) {
  43263. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  43264. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  43265. if (mesh instanceof BABYLON.Mesh) {
  43266. mesh.computeWorldMatrix(true);
  43267. matrix = mesh.getWorldMatrix();
  43268. meshPosition = mesh.position.clone();
  43269. meshRotation = mesh.rotation.clone();
  43270. if (mesh.rotationQuaternion) {
  43271. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  43272. }
  43273. meshScaling = mesh.scaling.clone();
  43274. }
  43275. else {
  43276. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  43277. }
  43278. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43279. var subMeshes = mesh.subMeshes;
  43280. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  43281. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  43282. vertices = [];
  43283. for (var j = 0; j < 3; j++) {
  43284. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  43285. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  43286. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  43287. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  43288. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  43289. vertex = new Vertex(position, normal, uv);
  43290. vertices.push(vertex);
  43291. }
  43292. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  43293. // To handle the case of degenerated triangle
  43294. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  43295. if (polygon.plane)
  43296. polygons.push(polygon);
  43297. }
  43298. }
  43299. var csg = CSG.FromPolygons(polygons);
  43300. csg.matrix = matrix;
  43301. csg.position = meshPosition;
  43302. csg.rotation = meshRotation;
  43303. csg.scaling = meshScaling;
  43304. csg.rotationQuaternion = meshRotationQuaternion;
  43305. currentCSGMeshId++;
  43306. return csg;
  43307. };
  43308. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  43309. CSG.FromPolygons = function (polygons) {
  43310. var csg = new CSG();
  43311. csg.polygons = polygons;
  43312. return csg;
  43313. };
  43314. CSG.prototype.clone = function () {
  43315. var csg = new CSG();
  43316. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  43317. csg.copyTransformAttributes(this);
  43318. return csg;
  43319. };
  43320. CSG.prototype.toPolygons = function () {
  43321. return this.polygons;
  43322. };
  43323. CSG.prototype.union = function (csg) {
  43324. var a = new Node(this.clone().polygons);
  43325. var b = new Node(csg.clone().polygons);
  43326. a.clipTo(b);
  43327. b.clipTo(a);
  43328. b.invert();
  43329. b.clipTo(a);
  43330. b.invert();
  43331. a.build(b.allPolygons());
  43332. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43333. };
  43334. CSG.prototype.unionInPlace = function (csg) {
  43335. var a = new Node(this.polygons);
  43336. var b = new Node(csg.polygons);
  43337. a.clipTo(b);
  43338. b.clipTo(a);
  43339. b.invert();
  43340. b.clipTo(a);
  43341. b.invert();
  43342. a.build(b.allPolygons());
  43343. this.polygons = a.allPolygons();
  43344. };
  43345. CSG.prototype.subtract = function (csg) {
  43346. var a = new Node(this.clone().polygons);
  43347. var b = new Node(csg.clone().polygons);
  43348. a.invert();
  43349. a.clipTo(b);
  43350. b.clipTo(a);
  43351. b.invert();
  43352. b.clipTo(a);
  43353. b.invert();
  43354. a.build(b.allPolygons());
  43355. a.invert();
  43356. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43357. };
  43358. CSG.prototype.subtractInPlace = function (csg) {
  43359. var a = new Node(this.polygons);
  43360. var b = new Node(csg.polygons);
  43361. a.invert();
  43362. a.clipTo(b);
  43363. b.clipTo(a);
  43364. b.invert();
  43365. b.clipTo(a);
  43366. b.invert();
  43367. a.build(b.allPolygons());
  43368. a.invert();
  43369. this.polygons = a.allPolygons();
  43370. };
  43371. CSG.prototype.intersect = function (csg) {
  43372. var a = new Node(this.clone().polygons);
  43373. var b = new Node(csg.clone().polygons);
  43374. a.invert();
  43375. b.clipTo(a);
  43376. b.invert();
  43377. a.clipTo(b);
  43378. b.clipTo(a);
  43379. a.build(b.allPolygons());
  43380. a.invert();
  43381. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43382. };
  43383. CSG.prototype.intersectInPlace = function (csg) {
  43384. var a = new Node(this.polygons);
  43385. var b = new Node(csg.polygons);
  43386. a.invert();
  43387. b.clipTo(a);
  43388. b.invert();
  43389. a.clipTo(b);
  43390. b.clipTo(a);
  43391. a.build(b.allPolygons());
  43392. a.invert();
  43393. this.polygons = a.allPolygons();
  43394. };
  43395. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  43396. // not modified.
  43397. CSG.prototype.inverse = function () {
  43398. var csg = this.clone();
  43399. csg.inverseInPlace();
  43400. return csg;
  43401. };
  43402. CSG.prototype.inverseInPlace = function () {
  43403. this.polygons.map(function (p) { p.flip(); });
  43404. };
  43405. // This is used to keep meshes transformations so they can be restored
  43406. // when we build back a Babylon Mesh
  43407. // NB : All CSG operations are performed in world coordinates
  43408. CSG.prototype.copyTransformAttributes = function (csg) {
  43409. this.matrix = csg.matrix;
  43410. this.position = csg.position;
  43411. this.rotation = csg.rotation;
  43412. this.scaling = csg.scaling;
  43413. this.rotationQuaternion = csg.rotationQuaternion;
  43414. return this;
  43415. };
  43416. // Build Raw mesh from CSG
  43417. // Coordinates here are in world space
  43418. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  43419. var matrix = this.matrix.clone();
  43420. matrix.invert();
  43421. 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;
  43422. if (keepSubMeshes) {
  43423. // Sort Polygons, since subMeshes are indices range
  43424. polygons.sort(function (a, b) {
  43425. if (a.shared.meshId === b.shared.meshId) {
  43426. return a.shared.subMeshId - b.shared.subMeshId;
  43427. }
  43428. else {
  43429. return a.shared.meshId - b.shared.meshId;
  43430. }
  43431. });
  43432. }
  43433. for (var i = 0, il = polygons.length; i < il; i++) {
  43434. polygon = polygons[i];
  43435. // Building SubMeshes
  43436. if (!subMesh_dict[polygon.shared.meshId]) {
  43437. subMesh_dict[polygon.shared.meshId] = {};
  43438. }
  43439. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  43440. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  43441. indexStart: +Infinity,
  43442. indexEnd: -Infinity,
  43443. materialIndex: polygon.shared.materialIndex
  43444. };
  43445. }
  43446. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  43447. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  43448. polygonIndices[0] = 0;
  43449. polygonIndices[1] = j - 1;
  43450. polygonIndices[2] = j;
  43451. for (var k = 0; k < 3; k++) {
  43452. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  43453. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  43454. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  43455. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  43456. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  43457. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  43458. // Check if 2 points can be merged
  43459. if (!(typeof vertex_idx !== 'undefined' &&
  43460. normals[vertex_idx * 3] === localNormal.x &&
  43461. normals[vertex_idx * 3 + 1] === localNormal.y &&
  43462. normals[vertex_idx * 3 + 2] === localNormal.z &&
  43463. uvs[vertex_idx * 2] === uv.x &&
  43464. uvs[vertex_idx * 2 + 1] === uv.y)) {
  43465. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  43466. uvs.push(uv.x, uv.y);
  43467. normals.push(normal.x, normal.y, normal.z);
  43468. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  43469. }
  43470. indices.push(vertex_idx);
  43471. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  43472. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  43473. currentIndex++;
  43474. }
  43475. }
  43476. }
  43477. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  43478. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  43479. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  43480. mesh.setIndices(indices);
  43481. if (keepSubMeshes) {
  43482. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  43483. var materialIndexOffset = 0, materialMaxIndex;
  43484. mesh.subMeshes = new Array();
  43485. for (var m in subMesh_dict) {
  43486. materialMaxIndex = -1;
  43487. for (var sm in subMesh_dict[m]) {
  43488. subMesh_obj = subMesh_dict[m][sm];
  43489. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  43490. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  43491. }
  43492. materialIndexOffset += ++materialMaxIndex;
  43493. }
  43494. }
  43495. return mesh;
  43496. };
  43497. // Build Mesh from CSG taking material and transforms into account
  43498. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  43499. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  43500. mesh.material = material;
  43501. mesh.position.copyFrom(this.position);
  43502. mesh.rotation.copyFrom(this.rotation);
  43503. if (this.rotationQuaternion) {
  43504. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  43505. }
  43506. mesh.scaling.copyFrom(this.scaling);
  43507. mesh.computeWorldMatrix(true);
  43508. return mesh;
  43509. };
  43510. return CSG;
  43511. }());
  43512. BABYLON.CSG = CSG;
  43513. })(BABYLON || (BABYLON = {}));
  43514. //# sourceMappingURL=../Mesh/babylon.csg.js.map
  43515. var BABYLON;
  43516. (function (BABYLON) {
  43517. var VRDistortionCorrectionPostProcess = (function (_super) {
  43518. __extends(VRDistortionCorrectionPostProcess, _super);
  43519. //ANY
  43520. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  43521. var _this = this;
  43522. _super.call(this, name, "vrDistortionCorrection", [
  43523. 'LensCenter',
  43524. 'Scale',
  43525. 'ScaleIn',
  43526. 'HmdWarpParam'
  43527. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  43528. this._isRightEye = isRightEye;
  43529. this._distortionFactors = vrMetrics.distortionK;
  43530. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  43531. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  43532. this.onSizeChangedObservable.add(function () {
  43533. _this.aspectRatio = _this.width * .5 / _this.height;
  43534. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  43535. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  43536. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  43537. });
  43538. this.onApplyObservable.add(function (effect) {
  43539. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  43540. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  43541. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  43542. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  43543. });
  43544. }
  43545. return VRDistortionCorrectionPostProcess;
  43546. }(BABYLON.PostProcess));
  43547. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  43548. })(BABYLON || (BABYLON = {}));
  43549. //# sourceMappingURL=../PostProcess/babylon.vrDistortionCorrectionPostProcess.js.map
  43550. // Mainly based on these 2 articles :
  43551. // 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
  43552. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  43553. var BABYLON;
  43554. (function (BABYLON) {
  43555. (function (JoystickAxis) {
  43556. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  43557. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  43558. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  43559. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  43560. var JoystickAxis = BABYLON.JoystickAxis;
  43561. var VirtualJoystick = (function () {
  43562. function VirtualJoystick(leftJoystick) {
  43563. var _this = this;
  43564. if (leftJoystick) {
  43565. this._leftJoystick = true;
  43566. }
  43567. else {
  43568. this._leftJoystick = false;
  43569. }
  43570. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  43571. VirtualJoystick._globalJoystickIndex++;
  43572. // By default left & right arrow keys are moving the X
  43573. // and up & down keys are moving the Y
  43574. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  43575. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  43576. this.reverseLeftRight = false;
  43577. this.reverseUpDown = false;
  43578. // collections of pointers
  43579. this._touches = new BABYLON.StringDictionary();
  43580. this.deltaPosition = BABYLON.Vector3.Zero();
  43581. this._joystickSensibility = 25;
  43582. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  43583. this._rotationSpeed = 25;
  43584. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  43585. this._rotateOnAxisRelativeToMesh = false;
  43586. this._onResize = function (evt) {
  43587. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  43588. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  43589. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  43590. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  43591. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  43592. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  43593. };
  43594. // injecting a canvas element on top of the canvas 3D game
  43595. if (!VirtualJoystick.vjCanvas) {
  43596. window.addEventListener("resize", this._onResize, false);
  43597. VirtualJoystick.vjCanvas = document.createElement("canvas");
  43598. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  43599. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  43600. VirtualJoystick.vjCanvas.width = window.innerWidth;
  43601. VirtualJoystick.vjCanvas.height = window.innerHeight;
  43602. VirtualJoystick.vjCanvas.style.width = "100%";
  43603. VirtualJoystick.vjCanvas.style.height = "100%";
  43604. VirtualJoystick.vjCanvas.style.position = "absolute";
  43605. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  43606. VirtualJoystick.vjCanvas.style.top = "0px";
  43607. VirtualJoystick.vjCanvas.style.left = "0px";
  43608. VirtualJoystick.vjCanvas.style.zIndex = "5";
  43609. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  43610. // Support for jQuery PEP polyfill
  43611. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  43612. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  43613. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  43614. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  43615. document.body.appendChild(VirtualJoystick.vjCanvas);
  43616. }
  43617. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  43618. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  43619. this.pressed = false;
  43620. // default joystick color
  43621. this._joystickColor = "cyan";
  43622. this._joystickPointerID = -1;
  43623. // current joystick position
  43624. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  43625. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  43626. // origin joystick position
  43627. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  43628. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  43629. this._onPointerDownHandlerRef = function (evt) {
  43630. _this._onPointerDown(evt);
  43631. };
  43632. this._onPointerMoveHandlerRef = function (evt) {
  43633. _this._onPointerMove(evt);
  43634. };
  43635. this._onPointerOutHandlerRef = function (evt) {
  43636. _this._onPointerUp(evt);
  43637. };
  43638. this._onPointerUpHandlerRef = function (evt) {
  43639. _this._onPointerUp(evt);
  43640. };
  43641. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  43642. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  43643. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  43644. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  43645. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  43646. evt.preventDefault(); // Disables system menu
  43647. }, false);
  43648. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  43649. }
  43650. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  43651. this._joystickSensibility = newJoystickSensibility;
  43652. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  43653. };
  43654. VirtualJoystick.prototype._onPointerDown = function (e) {
  43655. var positionOnScreenCondition;
  43656. e.preventDefault();
  43657. if (this._leftJoystick === true) {
  43658. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  43659. }
  43660. else {
  43661. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  43662. }
  43663. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  43664. // First contact will be dedicated to the virtual joystick
  43665. this._joystickPointerID = e.pointerId;
  43666. this._joystickPointerStartPos.x = e.clientX;
  43667. this._joystickPointerStartPos.y = e.clientY;
  43668. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  43669. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  43670. this._deltaJoystickVector.x = 0;
  43671. this._deltaJoystickVector.y = 0;
  43672. this.pressed = true;
  43673. this._touches.add(e.pointerId.toString(), e);
  43674. }
  43675. else {
  43676. // You can only trigger the action buttons with a joystick declared
  43677. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  43678. this._action();
  43679. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  43680. }
  43681. }
  43682. };
  43683. VirtualJoystick.prototype._onPointerMove = function (e) {
  43684. // If the current pointer is the one associated to the joystick (first touch contact)
  43685. if (this._joystickPointerID == e.pointerId) {
  43686. this._joystickPointerPos.x = e.clientX;
  43687. this._joystickPointerPos.y = e.clientY;
  43688. this._deltaJoystickVector = this._joystickPointerPos.clone();
  43689. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  43690. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  43691. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  43692. switch (this._axisTargetedByLeftAndRight) {
  43693. case JoystickAxis.X:
  43694. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  43695. break;
  43696. case JoystickAxis.Y:
  43697. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  43698. break;
  43699. case JoystickAxis.Z:
  43700. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  43701. break;
  43702. }
  43703. var directionUpDown = this.reverseUpDown ? 1 : -1;
  43704. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  43705. switch (this._axisTargetedByUpAndDown) {
  43706. case JoystickAxis.X:
  43707. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  43708. break;
  43709. case JoystickAxis.Y:
  43710. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  43711. break;
  43712. case JoystickAxis.Z:
  43713. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  43714. break;
  43715. }
  43716. }
  43717. else {
  43718. var data = this._touches.get(e.pointerId.toString());
  43719. if (data) {
  43720. data.x = e.clientX;
  43721. data.y = e.clientY;
  43722. }
  43723. }
  43724. };
  43725. VirtualJoystick.prototype._onPointerUp = function (e) {
  43726. if (this._joystickPointerID == e.pointerId) {
  43727. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  43728. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  43729. this._joystickPointerID = -1;
  43730. this.pressed = false;
  43731. }
  43732. else {
  43733. var touch = this._touches.get(e.pointerId.toString());
  43734. if (touch) {
  43735. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  43736. }
  43737. }
  43738. this._deltaJoystickVector.x = 0;
  43739. this._deltaJoystickVector.y = 0;
  43740. this._touches.remove(e.pointerId.toString());
  43741. };
  43742. /**
  43743. * Change the color of the virtual joystick
  43744. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  43745. */
  43746. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  43747. this._joystickColor = newColor;
  43748. };
  43749. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  43750. this._action = action;
  43751. };
  43752. // Define which axis you'd like to control for left & right
  43753. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  43754. switch (axis) {
  43755. case JoystickAxis.X:
  43756. case JoystickAxis.Y:
  43757. case JoystickAxis.Z:
  43758. this._axisTargetedByLeftAndRight = axis;
  43759. break;
  43760. default:
  43761. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  43762. break;
  43763. }
  43764. };
  43765. // Define which axis you'd like to control for up & down
  43766. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  43767. switch (axis) {
  43768. case JoystickAxis.X:
  43769. case JoystickAxis.Y:
  43770. case JoystickAxis.Z:
  43771. this._axisTargetedByUpAndDown = axis;
  43772. break;
  43773. default:
  43774. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  43775. break;
  43776. }
  43777. };
  43778. VirtualJoystick.prototype._clearCanvas = function () {
  43779. if (this._leftJoystick) {
  43780. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  43781. }
  43782. else {
  43783. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  43784. }
  43785. };
  43786. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  43787. var _this = this;
  43788. if (this.pressed) {
  43789. this._touches.forEach(function (touch) {
  43790. if (touch.pointerId === _this._joystickPointerID) {
  43791. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  43792. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  43793. VirtualJoystick.vjCanvasContext.beginPath();
  43794. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  43795. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  43796. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  43797. VirtualJoystick.vjCanvasContext.stroke();
  43798. VirtualJoystick.vjCanvasContext.closePath();
  43799. VirtualJoystick.vjCanvasContext.beginPath();
  43800. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  43801. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  43802. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  43803. VirtualJoystick.vjCanvasContext.stroke();
  43804. VirtualJoystick.vjCanvasContext.closePath();
  43805. VirtualJoystick.vjCanvasContext.beginPath();
  43806. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  43807. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  43808. VirtualJoystick.vjCanvasContext.stroke();
  43809. VirtualJoystick.vjCanvasContext.closePath();
  43810. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  43811. }
  43812. else {
  43813. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  43814. VirtualJoystick.vjCanvasContext.beginPath();
  43815. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  43816. VirtualJoystick.vjCanvasContext.beginPath();
  43817. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  43818. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  43819. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  43820. VirtualJoystick.vjCanvasContext.stroke();
  43821. VirtualJoystick.vjCanvasContext.closePath();
  43822. touch.prevX = touch.x;
  43823. touch.prevY = touch.y;
  43824. }
  43825. ;
  43826. });
  43827. }
  43828. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  43829. };
  43830. VirtualJoystick.prototype.releaseCanvas = function () {
  43831. if (VirtualJoystick.vjCanvas) {
  43832. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  43833. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  43834. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  43835. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  43836. window.removeEventListener("resize", this._onResize);
  43837. document.body.removeChild(VirtualJoystick.vjCanvas);
  43838. VirtualJoystick.vjCanvas = null;
  43839. }
  43840. };
  43841. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  43842. VirtualJoystick._globalJoystickIndex = 0;
  43843. return VirtualJoystick;
  43844. }());
  43845. BABYLON.VirtualJoystick = VirtualJoystick;
  43846. })(BABYLON || (BABYLON = {}));
  43847. //# sourceMappingURL=../Tools/babylon.virtualJoystick.js.map
  43848. var BABYLON;
  43849. (function (BABYLON) {
  43850. // We're mainly based on the logic defined into the FreeCamera code
  43851. var VirtualJoysticksCamera = (function (_super) {
  43852. __extends(VirtualJoysticksCamera, _super);
  43853. function VirtualJoysticksCamera(name, position, scene) {
  43854. _super.call(this, name, position, scene);
  43855. this.inputs.addVirtualJoystick();
  43856. }
  43857. return VirtualJoysticksCamera;
  43858. }(BABYLON.FreeCamera));
  43859. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  43860. })(BABYLON || (BABYLON = {}));
  43861. //# sourceMappingURL=../Cameras/babylon.virtualJoysticksCamera.js.map
  43862. var BABYLON;
  43863. (function (BABYLON) {
  43864. var FreeCameraVirtualJoystickInput = (function () {
  43865. function FreeCameraVirtualJoystickInput() {
  43866. }
  43867. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  43868. return this._leftjoystick;
  43869. };
  43870. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  43871. return this._rightjoystick;
  43872. };
  43873. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  43874. if (this._leftjoystick) {
  43875. var camera = this.camera;
  43876. var speed = camera._computeLocalCameraSpeed() * 50;
  43877. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  43878. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  43879. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  43880. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  43881. if (!this._leftjoystick.pressed) {
  43882. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  43883. }
  43884. if (!this._rightjoystick.pressed) {
  43885. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  43886. }
  43887. }
  43888. };
  43889. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  43890. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  43891. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  43892. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  43893. this._leftjoystick.setJoystickSensibility(0.15);
  43894. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  43895. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  43896. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  43897. this._rightjoystick.reverseUpDown = true;
  43898. this._rightjoystick.setJoystickSensibility(0.05);
  43899. this._rightjoystick.setJoystickColor("yellow");
  43900. };
  43901. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  43902. this._leftjoystick.releaseCanvas();
  43903. this._rightjoystick.releaseCanvas();
  43904. };
  43905. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  43906. return "FreeCameraVirtualJoystickInput";
  43907. };
  43908. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  43909. return "virtualJoystick";
  43910. };
  43911. return FreeCameraVirtualJoystickInput;
  43912. }());
  43913. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  43914. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  43915. })(BABYLON || (BABYLON = {}));
  43916. //# sourceMappingURL=../../Cameras/Inputs/babylon.freecamera.input.virtualjoystick.js.map
  43917. var BABYLON;
  43918. (function (BABYLON) {
  43919. var AnaglyphPostProcess = (function (_super) {
  43920. __extends(AnaglyphPostProcess, _super);
  43921. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  43922. var _this = this;
  43923. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  43924. this._passedProcess = rigCameras[0]._rigPostProcess;
  43925. this.onApplyObservable.add(function (effect) {
  43926. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  43927. });
  43928. }
  43929. return AnaglyphPostProcess;
  43930. }(BABYLON.PostProcess));
  43931. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  43932. })(BABYLON || (BABYLON = {}));
  43933. //# sourceMappingURL=../PostProcess/babylon.anaglyphPostProcess.js.map
  43934. var BABYLON;
  43935. (function (BABYLON) {
  43936. var OutlineRenderer = (function () {
  43937. function OutlineRenderer(scene) {
  43938. this._scene = scene;
  43939. }
  43940. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  43941. var _this = this;
  43942. if (useOverlay === void 0) { useOverlay = false; }
  43943. var scene = this._scene;
  43944. var engine = this._scene.getEngine();
  43945. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  43946. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  43947. return;
  43948. }
  43949. var mesh = subMesh.getRenderingMesh();
  43950. var material = subMesh.getMaterial();
  43951. engine.enableEffect(this._effect);
  43952. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  43953. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  43954. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  43955. // Bones
  43956. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43957. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  43958. }
  43959. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  43960. // Alpha test
  43961. if (material && material.needAlphaTesting()) {
  43962. var alphaTexture = material.getAlphaTestTexture();
  43963. this._effect.setTexture("diffuseSampler", alphaTexture);
  43964. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  43965. }
  43966. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  43967. };
  43968. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  43969. var defines = [];
  43970. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  43971. var mesh = subMesh.getMesh();
  43972. var material = subMesh.getMaterial();
  43973. // Alpha test
  43974. if (material && material.needAlphaTesting()) {
  43975. defines.push("#define ALPHATEST");
  43976. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43977. attribs.push(BABYLON.VertexBuffer.UVKind);
  43978. defines.push("#define UV1");
  43979. }
  43980. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  43981. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43982. defines.push("#define UV2");
  43983. }
  43984. }
  43985. // Bones
  43986. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43987. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43988. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43989. if (mesh.numBoneInfluencers > 4) {
  43990. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43991. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43992. }
  43993. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43994. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43995. }
  43996. else {
  43997. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43998. }
  43999. // Instances
  44000. if (useInstances) {
  44001. defines.push("#define INSTANCES");
  44002. attribs.push("world0");
  44003. attribs.push("world1");
  44004. attribs.push("world2");
  44005. attribs.push("world3");
  44006. }
  44007. // Get correct effect
  44008. var join = defines.join("\n");
  44009. if (this._cachedDefines !== join) {
  44010. this._cachedDefines = join;
  44011. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  44012. }
  44013. return this._effect.isReady();
  44014. };
  44015. return OutlineRenderer;
  44016. }());
  44017. BABYLON.OutlineRenderer = OutlineRenderer;
  44018. })(BABYLON || (BABYLON = {}));
  44019. //# sourceMappingURL=../Rendering/babylon.outlineRenderer.js.map
  44020. var BABYLON;
  44021. (function (BABYLON) {
  44022. var MeshAssetTask = (function () {
  44023. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  44024. this.name = name;
  44025. this.meshesNames = meshesNames;
  44026. this.rootUrl = rootUrl;
  44027. this.sceneFilename = sceneFilename;
  44028. this.isCompleted = false;
  44029. }
  44030. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44031. var _this = this;
  44032. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  44033. _this.loadedMeshes = meshes;
  44034. _this.loadedParticleSystems = particleSystems;
  44035. _this.loadedSkeletons = skeletons;
  44036. _this.isCompleted = true;
  44037. if (_this.onSuccess) {
  44038. _this.onSuccess(_this);
  44039. }
  44040. onSuccess();
  44041. }, null, function () {
  44042. if (_this.onError) {
  44043. _this.onError(_this);
  44044. }
  44045. onError();
  44046. });
  44047. };
  44048. return MeshAssetTask;
  44049. }());
  44050. BABYLON.MeshAssetTask = MeshAssetTask;
  44051. var TextFileAssetTask = (function () {
  44052. function TextFileAssetTask(name, url) {
  44053. this.name = name;
  44054. this.url = url;
  44055. this.isCompleted = false;
  44056. }
  44057. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44058. var _this = this;
  44059. BABYLON.Tools.LoadFile(this.url, function (data) {
  44060. _this.text = data;
  44061. _this.isCompleted = true;
  44062. if (_this.onSuccess) {
  44063. _this.onSuccess(_this);
  44064. }
  44065. onSuccess();
  44066. }, null, scene.database, false, function () {
  44067. if (_this.onError) {
  44068. _this.onError(_this);
  44069. }
  44070. onError();
  44071. });
  44072. };
  44073. return TextFileAssetTask;
  44074. }());
  44075. BABYLON.TextFileAssetTask = TextFileAssetTask;
  44076. var BinaryFileAssetTask = (function () {
  44077. function BinaryFileAssetTask(name, url) {
  44078. this.name = name;
  44079. this.url = url;
  44080. this.isCompleted = false;
  44081. }
  44082. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44083. var _this = this;
  44084. BABYLON.Tools.LoadFile(this.url, function (data) {
  44085. _this.data = data;
  44086. _this.isCompleted = true;
  44087. if (_this.onSuccess) {
  44088. _this.onSuccess(_this);
  44089. }
  44090. onSuccess();
  44091. }, null, scene.database, true, function () {
  44092. if (_this.onError) {
  44093. _this.onError(_this);
  44094. }
  44095. onError();
  44096. });
  44097. };
  44098. return BinaryFileAssetTask;
  44099. }());
  44100. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  44101. var ImageAssetTask = (function () {
  44102. function ImageAssetTask(name, url) {
  44103. this.name = name;
  44104. this.url = url;
  44105. this.isCompleted = false;
  44106. }
  44107. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44108. var _this = this;
  44109. var img = new Image();
  44110. BABYLON.Tools.SetCorsBehavior(this.url, img);
  44111. img.onload = function () {
  44112. _this.image = img;
  44113. _this.isCompleted = true;
  44114. if (_this.onSuccess) {
  44115. _this.onSuccess(_this);
  44116. }
  44117. onSuccess();
  44118. };
  44119. img.onerror = function () {
  44120. if (_this.onError) {
  44121. _this.onError(_this);
  44122. }
  44123. onError();
  44124. };
  44125. img.src = this.url;
  44126. };
  44127. return ImageAssetTask;
  44128. }());
  44129. BABYLON.ImageAssetTask = ImageAssetTask;
  44130. var TextureAssetTask = (function () {
  44131. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  44132. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44133. this.name = name;
  44134. this.url = url;
  44135. this.noMipmap = noMipmap;
  44136. this.invertY = invertY;
  44137. this.samplingMode = samplingMode;
  44138. this.isCompleted = false;
  44139. }
  44140. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44141. var _this = this;
  44142. var onload = function () {
  44143. _this.isCompleted = true;
  44144. if (_this.onSuccess) {
  44145. _this.onSuccess(_this);
  44146. }
  44147. onSuccess();
  44148. };
  44149. var onerror = function () {
  44150. if (_this.onError) {
  44151. _this.onError(_this);
  44152. }
  44153. onError();
  44154. };
  44155. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  44156. };
  44157. return TextureAssetTask;
  44158. }());
  44159. BABYLON.TextureAssetTask = TextureAssetTask;
  44160. var CubeTextureAssetTask = (function () {
  44161. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  44162. this.name = name;
  44163. this.url = url;
  44164. this.extensions = extensions;
  44165. this.noMipmap = noMipmap;
  44166. this.files = files;
  44167. this.isCompleted = false;
  44168. }
  44169. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44170. var _this = this;
  44171. var onload = function () {
  44172. _this.isCompleted = true;
  44173. if (_this.onSuccess) {
  44174. _this.onSuccess(_this);
  44175. }
  44176. onSuccess();
  44177. };
  44178. var onerror = function () {
  44179. if (_this.onError) {
  44180. _this.onError(_this);
  44181. }
  44182. onError();
  44183. };
  44184. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  44185. };
  44186. return CubeTextureAssetTask;
  44187. }());
  44188. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  44189. var AssetsManager = (function () {
  44190. function AssetsManager(scene) {
  44191. this.tasks = new Array();
  44192. this.waitingTasksCount = 0;
  44193. this.useDefaultLoadingScreen = true;
  44194. this._scene = scene;
  44195. }
  44196. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  44197. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  44198. this.tasks.push(task);
  44199. return task;
  44200. };
  44201. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  44202. var task = new TextFileAssetTask(taskName, url);
  44203. this.tasks.push(task);
  44204. return task;
  44205. };
  44206. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  44207. var task = new BinaryFileAssetTask(taskName, url);
  44208. this.tasks.push(task);
  44209. return task;
  44210. };
  44211. AssetsManager.prototype.addImageTask = function (taskName, url) {
  44212. var task = new ImageAssetTask(taskName, url);
  44213. this.tasks.push(task);
  44214. return task;
  44215. };
  44216. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  44217. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44218. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  44219. this.tasks.push(task);
  44220. return task;
  44221. };
  44222. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  44223. this.waitingTasksCount--;
  44224. if (this.waitingTasksCount === 0) {
  44225. if (this.onFinish) {
  44226. this.onFinish(this.tasks);
  44227. }
  44228. this._scene.getEngine().hideLoadingUI();
  44229. }
  44230. };
  44231. AssetsManager.prototype._runTask = function (task) {
  44232. var _this = this;
  44233. task.run(this._scene, function () {
  44234. if (_this.onTaskSuccess) {
  44235. _this.onTaskSuccess(task);
  44236. }
  44237. _this._decreaseWaitingTasksCount();
  44238. }, function () {
  44239. if (_this.onTaskError) {
  44240. _this.onTaskError(task);
  44241. }
  44242. _this._decreaseWaitingTasksCount();
  44243. });
  44244. };
  44245. AssetsManager.prototype.reset = function () {
  44246. this.tasks = new Array();
  44247. return this;
  44248. };
  44249. AssetsManager.prototype.load = function () {
  44250. this.waitingTasksCount = this.tasks.length;
  44251. if (this.waitingTasksCount === 0) {
  44252. if (this.onFinish) {
  44253. this.onFinish(this.tasks);
  44254. }
  44255. return this;
  44256. }
  44257. if (this.useDefaultLoadingScreen) {
  44258. this._scene.getEngine().displayLoadingUI();
  44259. }
  44260. for (var index = 0; index < this.tasks.length; index++) {
  44261. var task = this.tasks[index];
  44262. this._runTask(task);
  44263. }
  44264. return this;
  44265. };
  44266. return AssetsManager;
  44267. }());
  44268. BABYLON.AssetsManager = AssetsManager;
  44269. })(BABYLON || (BABYLON = {}));
  44270. //# sourceMappingURL=../Tools/babylon.assetsManager.js.map
  44271. var BABYLON;
  44272. (function (BABYLON) {
  44273. var VRCameraMetrics = (function () {
  44274. function VRCameraMetrics() {
  44275. this.compensateDistortion = true;
  44276. }
  44277. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  44278. get: function () {
  44279. return this.hResolution / (2 * this.vResolution);
  44280. },
  44281. enumerable: true,
  44282. configurable: true
  44283. });
  44284. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  44285. get: function () {
  44286. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  44287. },
  44288. enumerable: true,
  44289. configurable: true
  44290. });
  44291. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  44292. get: function () {
  44293. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  44294. var h = (4 * meters) / this.hScreenSize;
  44295. return BABYLON.Matrix.Translation(h, 0, 0);
  44296. },
  44297. enumerable: true,
  44298. configurable: true
  44299. });
  44300. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  44301. get: function () {
  44302. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  44303. var h = (4 * meters) / this.hScreenSize;
  44304. return BABYLON.Matrix.Translation(-h, 0, 0);
  44305. },
  44306. enumerable: true,
  44307. configurable: true
  44308. });
  44309. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  44310. get: function () {
  44311. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  44312. },
  44313. enumerable: true,
  44314. configurable: true
  44315. });
  44316. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  44317. get: function () {
  44318. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  44319. },
  44320. enumerable: true,
  44321. configurable: true
  44322. });
  44323. VRCameraMetrics.GetDefault = function () {
  44324. var result = new VRCameraMetrics();
  44325. result.hResolution = 1280;
  44326. result.vResolution = 800;
  44327. result.hScreenSize = 0.149759993;
  44328. result.vScreenSize = 0.0935999975;
  44329. result.vScreenCenter = 0.0467999987,
  44330. result.eyeToScreenDistance = 0.0410000011;
  44331. result.lensSeparationDistance = 0.0635000020;
  44332. result.interpupillaryDistance = 0.0640000030;
  44333. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  44334. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  44335. result.postProcessScaleFactor = 1.714605507808412;
  44336. result.lensCenterOffset = 0.151976421;
  44337. return result;
  44338. };
  44339. return VRCameraMetrics;
  44340. }());
  44341. BABYLON.VRCameraMetrics = VRCameraMetrics;
  44342. })(BABYLON || (BABYLON = {}));
  44343. //# sourceMappingURL=../../Cameras/VR/babylon.vrCameraMetrics.js.map
  44344. var BABYLON;
  44345. (function (BABYLON) {
  44346. var WebVRFreeCamera = (function (_super) {
  44347. __extends(WebVRFreeCamera, _super);
  44348. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  44349. var _this = this;
  44350. if (compensateDistortion === void 0) { compensateDistortion = false; }
  44351. if (webVROptions === void 0) { webVROptions = {}; }
  44352. _super.call(this, name, position, scene);
  44353. this.webVROptions = webVROptions;
  44354. this._vrDevice = null;
  44355. this._cacheState = null;
  44356. this._vrEnabled = false;
  44357. this._attached = false;
  44358. //using the position provided as the current position offset
  44359. this._positionOffset = position;
  44360. //enable VR
  44361. this.getEngine().initWebVR();
  44362. if (!this.getEngine().vrDisplaysPromise) {
  44363. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  44364. }
  44365. else {
  44366. //TODO get the metrics updated using the device's eye parameters!
  44367. //TODO also check that the device has the right capabilities!
  44368. this._frameData = new VRFrameData();
  44369. this.getEngine().vrDisplaysPromise.then(function (devices) {
  44370. if (devices.length > 0) {
  44371. _this._vrEnabled = true;
  44372. if (_this.webVROptions.displayName) {
  44373. var found = devices.some(function (device) {
  44374. if (device.displayName === _this.webVROptions.displayName) {
  44375. _this._vrDevice = device;
  44376. return true;
  44377. }
  44378. else {
  44379. return false;
  44380. }
  44381. });
  44382. if (!found) {
  44383. _this._vrDevice = devices[0];
  44384. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  44385. }
  44386. }
  44387. else {
  44388. //choose the first one
  44389. _this._vrDevice = devices[0];
  44390. }
  44391. //reset the rig parameters.
  44392. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  44393. if (_this._attached) {
  44394. _this.getEngine().enableVR(_this._vrDevice);
  44395. }
  44396. }
  44397. else {
  44398. BABYLON.Tools.Error("No WebVR devices found!");
  44399. }
  44400. });
  44401. }
  44402. this.rotationQuaternion = new BABYLON.Quaternion();
  44403. this._quaternionCache = new BABYLON.Quaternion();
  44404. }
  44405. WebVRFreeCamera.prototype._checkInputs = function () {
  44406. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  44407. var currentPost = this._frameData.pose;
  44408. //make sure we have data
  44409. if (currentPost && currentPost.orientation) {
  44410. this._cacheState = currentPost;
  44411. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  44412. if (this.webVROptions.trackPosition && this._cacheState.position) {
  44413. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  44414. //scale the position accordingly
  44415. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  44416. //add the position offset
  44417. this.position.addInPlace(this._positionOffset);
  44418. }
  44419. }
  44420. }
  44421. _super.prototype._checkInputs.call(this);
  44422. };
  44423. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44424. _super.prototype.attachControl.call(this, element, noPreventDefault);
  44425. this._attached = true;
  44426. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  44427. if (this._vrEnabled) {
  44428. this.getEngine().enableVR(this._vrDevice);
  44429. }
  44430. };
  44431. WebVRFreeCamera.prototype.detachControl = function (element) {
  44432. _super.prototype.detachControl.call(this, element);
  44433. this._vrEnabled = false;
  44434. this._attached = false;
  44435. this.getEngine().disableVR();
  44436. };
  44437. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  44438. //Backwards comp.
  44439. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  44440. //this.getEngine().switchFullscreen(requestPointerlock);
  44441. };
  44442. WebVRFreeCamera.prototype.getTypeName = function () {
  44443. return "WebVRFreeCamera";
  44444. };
  44445. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  44446. //uses the vrDisplay's "resetPose()".
  44447. //pitch and roll won't be affected.
  44448. this._vrDevice.resetPose();
  44449. };
  44450. /**
  44451. *
  44452. * Set the position offset of the VR camera
  44453. * The offset will be added to the WebVR pose, after scaling it (if set).
  44454. *
  44455. * @param {Vector3} [newPosition] an optional new position. if not provided, the current camera position will be used.
  44456. *
  44457. * @memberOf WebVRFreeCamera
  44458. */
  44459. WebVRFreeCamera.prototype.setPositionOffset = function (newPosition) {
  44460. if (newPosition) {
  44461. this._positionOffset = newPosition;
  44462. }
  44463. else {
  44464. this._positionOffset.copyFrom(this.position);
  44465. }
  44466. };
  44467. return WebVRFreeCamera;
  44468. }(BABYLON.FreeCamera));
  44469. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  44470. })(BABYLON || (BABYLON = {}));
  44471. //# sourceMappingURL=../../Cameras/VR/babylon.webVRCamera.js.map
  44472. var BABYLON;
  44473. (function (BABYLON) {
  44474. // Standard optimizations
  44475. var SceneOptimization = (function () {
  44476. function SceneOptimization(priority) {
  44477. if (priority === void 0) { priority = 0; }
  44478. this.priority = priority;
  44479. this.apply = function (scene) {
  44480. return true; // Return true if everything that can be done was applied
  44481. };
  44482. }
  44483. return SceneOptimization;
  44484. }());
  44485. BABYLON.SceneOptimization = SceneOptimization;
  44486. var TextureOptimization = (function (_super) {
  44487. __extends(TextureOptimization, _super);
  44488. function TextureOptimization(priority, maximumSize) {
  44489. var _this = this;
  44490. if (priority === void 0) { priority = 0; }
  44491. if (maximumSize === void 0) { maximumSize = 1024; }
  44492. _super.call(this, priority);
  44493. this.priority = priority;
  44494. this.maximumSize = maximumSize;
  44495. this.apply = function (scene) {
  44496. var allDone = true;
  44497. for (var index = 0; index < scene.textures.length; index++) {
  44498. var texture = scene.textures[index];
  44499. if (!texture.canRescale) {
  44500. continue;
  44501. }
  44502. var currentSize = texture.getSize();
  44503. var maxDimension = Math.max(currentSize.width, currentSize.height);
  44504. if (maxDimension > _this.maximumSize) {
  44505. texture.scale(0.5);
  44506. allDone = false;
  44507. }
  44508. }
  44509. return allDone;
  44510. };
  44511. }
  44512. return TextureOptimization;
  44513. }(SceneOptimization));
  44514. BABYLON.TextureOptimization = TextureOptimization;
  44515. var HardwareScalingOptimization = (function (_super) {
  44516. __extends(HardwareScalingOptimization, _super);
  44517. function HardwareScalingOptimization(priority, maximumScale) {
  44518. var _this = this;
  44519. if (priority === void 0) { priority = 0; }
  44520. if (maximumScale === void 0) { maximumScale = 2; }
  44521. _super.call(this, priority);
  44522. this.priority = priority;
  44523. this.maximumScale = maximumScale;
  44524. this._currentScale = 1;
  44525. this.apply = function (scene) {
  44526. _this._currentScale++;
  44527. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  44528. return _this._currentScale >= _this.maximumScale;
  44529. };
  44530. }
  44531. return HardwareScalingOptimization;
  44532. }(SceneOptimization));
  44533. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  44534. var ShadowsOptimization = (function (_super) {
  44535. __extends(ShadowsOptimization, _super);
  44536. function ShadowsOptimization() {
  44537. _super.apply(this, arguments);
  44538. this.apply = function (scene) {
  44539. scene.shadowsEnabled = false;
  44540. return true;
  44541. };
  44542. }
  44543. return ShadowsOptimization;
  44544. }(SceneOptimization));
  44545. BABYLON.ShadowsOptimization = ShadowsOptimization;
  44546. var PostProcessesOptimization = (function (_super) {
  44547. __extends(PostProcessesOptimization, _super);
  44548. function PostProcessesOptimization() {
  44549. _super.apply(this, arguments);
  44550. this.apply = function (scene) {
  44551. scene.postProcessesEnabled = false;
  44552. return true;
  44553. };
  44554. }
  44555. return PostProcessesOptimization;
  44556. }(SceneOptimization));
  44557. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  44558. var LensFlaresOptimization = (function (_super) {
  44559. __extends(LensFlaresOptimization, _super);
  44560. function LensFlaresOptimization() {
  44561. _super.apply(this, arguments);
  44562. this.apply = function (scene) {
  44563. scene.lensFlaresEnabled = false;
  44564. return true;
  44565. };
  44566. }
  44567. return LensFlaresOptimization;
  44568. }(SceneOptimization));
  44569. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  44570. var ParticlesOptimization = (function (_super) {
  44571. __extends(ParticlesOptimization, _super);
  44572. function ParticlesOptimization() {
  44573. _super.apply(this, arguments);
  44574. this.apply = function (scene) {
  44575. scene.particlesEnabled = false;
  44576. return true;
  44577. };
  44578. }
  44579. return ParticlesOptimization;
  44580. }(SceneOptimization));
  44581. BABYLON.ParticlesOptimization = ParticlesOptimization;
  44582. var RenderTargetsOptimization = (function (_super) {
  44583. __extends(RenderTargetsOptimization, _super);
  44584. function RenderTargetsOptimization() {
  44585. _super.apply(this, arguments);
  44586. this.apply = function (scene) {
  44587. scene.renderTargetsEnabled = false;
  44588. return true;
  44589. };
  44590. }
  44591. return RenderTargetsOptimization;
  44592. }(SceneOptimization));
  44593. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  44594. var MergeMeshesOptimization = (function (_super) {
  44595. __extends(MergeMeshesOptimization, _super);
  44596. function MergeMeshesOptimization() {
  44597. var _this = this;
  44598. _super.apply(this, arguments);
  44599. this._canBeMerged = function (abstractMesh) {
  44600. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  44601. return false;
  44602. }
  44603. var mesh = abstractMesh;
  44604. if (!mesh.isVisible || !mesh.isEnabled()) {
  44605. return false;
  44606. }
  44607. if (mesh.instances.length > 0) {
  44608. return false;
  44609. }
  44610. if (mesh.skeleton || mesh.hasLODLevels) {
  44611. return false;
  44612. }
  44613. if (mesh.parent) {
  44614. return false;
  44615. }
  44616. return true;
  44617. };
  44618. this.apply = function (scene, updateSelectionTree) {
  44619. var globalPool = scene.meshes.slice(0);
  44620. var globalLength = globalPool.length;
  44621. for (var index = 0; index < globalLength; index++) {
  44622. var currentPool = new Array();
  44623. var current = globalPool[index];
  44624. // Checks
  44625. if (!_this._canBeMerged(current)) {
  44626. continue;
  44627. }
  44628. currentPool.push(current);
  44629. // Find compatible meshes
  44630. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  44631. var otherMesh = globalPool[subIndex];
  44632. if (!_this._canBeMerged(otherMesh)) {
  44633. continue;
  44634. }
  44635. if (otherMesh.material !== current.material) {
  44636. continue;
  44637. }
  44638. if (otherMesh.checkCollisions !== current.checkCollisions) {
  44639. continue;
  44640. }
  44641. currentPool.push(otherMesh);
  44642. globalLength--;
  44643. globalPool.splice(subIndex, 1);
  44644. subIndex--;
  44645. }
  44646. if (currentPool.length < 2) {
  44647. continue;
  44648. }
  44649. // Merge meshes
  44650. BABYLON.Mesh.MergeMeshes(currentPool);
  44651. }
  44652. if (updateSelectionTree != undefined) {
  44653. if (updateSelectionTree) {
  44654. scene.createOrUpdateSelectionOctree();
  44655. }
  44656. }
  44657. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  44658. scene.createOrUpdateSelectionOctree();
  44659. }
  44660. return true;
  44661. };
  44662. }
  44663. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  44664. get: function () {
  44665. return MergeMeshesOptimization._UpdateSelectionTree;
  44666. },
  44667. set: function (value) {
  44668. MergeMeshesOptimization._UpdateSelectionTree = value;
  44669. },
  44670. enumerable: true,
  44671. configurable: true
  44672. });
  44673. MergeMeshesOptimization._UpdateSelectionTree = false;
  44674. return MergeMeshesOptimization;
  44675. }(SceneOptimization));
  44676. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  44677. // Options
  44678. var SceneOptimizerOptions = (function () {
  44679. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  44680. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  44681. if (trackerDuration === void 0) { trackerDuration = 2000; }
  44682. this.targetFrameRate = targetFrameRate;
  44683. this.trackerDuration = trackerDuration;
  44684. this.optimizations = new Array();
  44685. }
  44686. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  44687. var result = new SceneOptimizerOptions(targetFrameRate);
  44688. var priority = 0;
  44689. result.optimizations.push(new MergeMeshesOptimization(priority));
  44690. result.optimizations.push(new ShadowsOptimization(priority));
  44691. result.optimizations.push(new LensFlaresOptimization(priority));
  44692. // Next priority
  44693. priority++;
  44694. result.optimizations.push(new PostProcessesOptimization(priority));
  44695. result.optimizations.push(new ParticlesOptimization(priority));
  44696. // Next priority
  44697. priority++;
  44698. result.optimizations.push(new TextureOptimization(priority, 1024));
  44699. return result;
  44700. };
  44701. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  44702. var result = new SceneOptimizerOptions(targetFrameRate);
  44703. var priority = 0;
  44704. result.optimizations.push(new MergeMeshesOptimization(priority));
  44705. result.optimizations.push(new ShadowsOptimization(priority));
  44706. result.optimizations.push(new LensFlaresOptimization(priority));
  44707. // Next priority
  44708. priority++;
  44709. result.optimizations.push(new PostProcessesOptimization(priority));
  44710. result.optimizations.push(new ParticlesOptimization(priority));
  44711. // Next priority
  44712. priority++;
  44713. result.optimizations.push(new TextureOptimization(priority, 512));
  44714. // Next priority
  44715. priority++;
  44716. result.optimizations.push(new RenderTargetsOptimization(priority));
  44717. // Next priority
  44718. priority++;
  44719. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  44720. return result;
  44721. };
  44722. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  44723. var result = new SceneOptimizerOptions(targetFrameRate);
  44724. var priority = 0;
  44725. result.optimizations.push(new MergeMeshesOptimization(priority));
  44726. result.optimizations.push(new ShadowsOptimization(priority));
  44727. result.optimizations.push(new LensFlaresOptimization(priority));
  44728. // Next priority
  44729. priority++;
  44730. result.optimizations.push(new PostProcessesOptimization(priority));
  44731. result.optimizations.push(new ParticlesOptimization(priority));
  44732. // Next priority
  44733. priority++;
  44734. result.optimizations.push(new TextureOptimization(priority, 256));
  44735. // Next priority
  44736. priority++;
  44737. result.optimizations.push(new RenderTargetsOptimization(priority));
  44738. // Next priority
  44739. priority++;
  44740. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  44741. return result;
  44742. };
  44743. return SceneOptimizerOptions;
  44744. }());
  44745. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  44746. // Scene optimizer tool
  44747. var SceneOptimizer = (function () {
  44748. function SceneOptimizer() {
  44749. }
  44750. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  44751. // TODO: add an epsilon
  44752. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  44753. if (onSuccess) {
  44754. onSuccess();
  44755. }
  44756. return;
  44757. }
  44758. // Apply current level of optimizations
  44759. var allDone = true;
  44760. var noOptimizationApplied = true;
  44761. for (var index = 0; index < options.optimizations.length; index++) {
  44762. var optimization = options.optimizations[index];
  44763. if (optimization.priority === currentPriorityLevel) {
  44764. noOptimizationApplied = false;
  44765. allDone = allDone && optimization.apply(scene);
  44766. }
  44767. }
  44768. // If no optimization was applied, this is a failure :(
  44769. if (noOptimizationApplied) {
  44770. if (onFailure) {
  44771. onFailure();
  44772. }
  44773. return;
  44774. }
  44775. // If all optimizations were done, move to next level
  44776. if (allDone) {
  44777. currentPriorityLevel++;
  44778. }
  44779. // Let's the system running for a specific amount of time before checking FPS
  44780. scene.executeWhenReady(function () {
  44781. setTimeout(function () {
  44782. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  44783. }, options.trackerDuration);
  44784. });
  44785. };
  44786. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  44787. if (!options) {
  44788. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  44789. }
  44790. // Let's the system running for a specific amount of time before checking FPS
  44791. scene.executeWhenReady(function () {
  44792. setTimeout(function () {
  44793. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  44794. }, options.trackerDuration);
  44795. });
  44796. };
  44797. return SceneOptimizer;
  44798. }());
  44799. BABYLON.SceneOptimizer = SceneOptimizer;
  44800. })(BABYLON || (BABYLON = {}));
  44801. //# sourceMappingURL=../Tools/babylon.sceneOptimizer.js.map
  44802. var BABYLON;
  44803. (function (BABYLON) {
  44804. var Internals;
  44805. (function (Internals) {
  44806. var MeshLODLevel = (function () {
  44807. function MeshLODLevel(distance, mesh) {
  44808. this.distance = distance;
  44809. this.mesh = mesh;
  44810. }
  44811. return MeshLODLevel;
  44812. }());
  44813. Internals.MeshLODLevel = MeshLODLevel;
  44814. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  44815. })(BABYLON || (BABYLON = {}));
  44816. //# sourceMappingURL=../Mesh/babylon.meshLODLevel.js.map
  44817. var BABYLON;
  44818. (function (BABYLON) {
  44819. var RawTexture = (function (_super) {
  44820. __extends(RawTexture, _super);
  44821. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  44822. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44823. if (invertY === void 0) { invertY = false; }
  44824. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44825. _super.call(this, null, scene, !generateMipMaps, invertY);
  44826. this.format = format;
  44827. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  44828. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44829. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44830. }
  44831. RawTexture.prototype.update = function (data) {
  44832. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  44833. };
  44834. // Statics
  44835. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44836. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44837. if (invertY === void 0) { invertY = false; }
  44838. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44839. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  44840. };
  44841. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44842. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44843. if (invertY === void 0) { invertY = false; }
  44844. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44845. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  44846. };
  44847. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44848. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44849. if (invertY === void 0) { invertY = false; }
  44850. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44851. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  44852. };
  44853. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44854. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44855. if (invertY === void 0) { invertY = false; }
  44856. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44857. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  44858. };
  44859. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  44860. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44861. if (invertY === void 0) { invertY = false; }
  44862. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44863. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  44864. };
  44865. return RawTexture;
  44866. }(BABYLON.Texture));
  44867. BABYLON.RawTexture = RawTexture;
  44868. })(BABYLON || (BABYLON = {}));
  44869. //# sourceMappingURL=../../Materials/Textures/babylon.rawTexture.js.map
  44870. var BABYLON;
  44871. (function (BABYLON) {
  44872. var IndexedVector2 = (function (_super) {
  44873. __extends(IndexedVector2, _super);
  44874. function IndexedVector2(original, index) {
  44875. _super.call(this, original.x, original.y);
  44876. this.index = index;
  44877. }
  44878. return IndexedVector2;
  44879. }(BABYLON.Vector2));
  44880. var PolygonPoints = (function () {
  44881. function PolygonPoints() {
  44882. this.elements = new Array();
  44883. }
  44884. PolygonPoints.prototype.add = function (originalPoints) {
  44885. var _this = this;
  44886. var result = new Array();
  44887. originalPoints.forEach(function (point) {
  44888. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  44889. var newPoint = new IndexedVector2(point, _this.elements.length);
  44890. result.push(newPoint);
  44891. _this.elements.push(newPoint);
  44892. }
  44893. });
  44894. return result;
  44895. };
  44896. PolygonPoints.prototype.computeBounds = function () {
  44897. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  44898. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  44899. this.elements.forEach(function (point) {
  44900. // x
  44901. if (point.x < lmin.x) {
  44902. lmin.x = point.x;
  44903. }
  44904. else if (point.x > lmax.x) {
  44905. lmax.x = point.x;
  44906. }
  44907. // y
  44908. if (point.y < lmin.y) {
  44909. lmin.y = point.y;
  44910. }
  44911. else if (point.y > lmax.y) {
  44912. lmax.y = point.y;
  44913. }
  44914. });
  44915. return {
  44916. min: lmin,
  44917. max: lmax,
  44918. width: lmax.x - lmin.x,
  44919. height: lmax.y - lmin.y
  44920. };
  44921. };
  44922. return PolygonPoints;
  44923. }());
  44924. var Polygon = (function () {
  44925. function Polygon() {
  44926. }
  44927. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  44928. return [
  44929. new BABYLON.Vector2(xmin, ymin),
  44930. new BABYLON.Vector2(xmax, ymin),
  44931. new BABYLON.Vector2(xmax, ymax),
  44932. new BABYLON.Vector2(xmin, ymax)
  44933. ];
  44934. };
  44935. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  44936. if (cx === void 0) { cx = 0; }
  44937. if (cy === void 0) { cy = 0; }
  44938. if (numberOfSides === void 0) { numberOfSides = 32; }
  44939. var result = new Array();
  44940. var angle = 0;
  44941. var increment = (Math.PI * 2) / numberOfSides;
  44942. for (var i = 0; i < numberOfSides; i++) {
  44943. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  44944. angle -= increment;
  44945. }
  44946. return result;
  44947. };
  44948. Polygon.Parse = function (input) {
  44949. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  44950. var i, result = [];
  44951. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  44952. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  44953. }
  44954. return result;
  44955. };
  44956. Polygon.StartingAt = function (x, y) {
  44957. return BABYLON.Path2.StartingAt(x, y);
  44958. };
  44959. return Polygon;
  44960. }());
  44961. BABYLON.Polygon = Polygon;
  44962. var PolygonMeshBuilder = (function () {
  44963. function PolygonMeshBuilder(name, contours, scene) {
  44964. this._points = new PolygonPoints();
  44965. this._outlinepoints = new PolygonPoints();
  44966. this._holes = [];
  44967. this._epoints = new Array();
  44968. this._eholes = new Array();
  44969. this._name = name;
  44970. this._scene = scene;
  44971. var points;
  44972. if (contours instanceof BABYLON.Path2) {
  44973. points = contours.getPoints();
  44974. }
  44975. else {
  44976. points = contours;
  44977. }
  44978. this._addToepoint(points);
  44979. this._points.add(points);
  44980. this._outlinepoints.add(points);
  44981. }
  44982. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  44983. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  44984. var p = points_1[_i];
  44985. this._epoints.push(p.x, p.y);
  44986. }
  44987. };
  44988. PolygonMeshBuilder.prototype.addHole = function (hole) {
  44989. this._points.add(hole);
  44990. var holepoints = new PolygonPoints();
  44991. holepoints.add(hole);
  44992. this._holes.push(holepoints);
  44993. this._eholes.push(this._epoints.length / 2);
  44994. this._addToepoint(hole);
  44995. return this;
  44996. };
  44997. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  44998. var _this = this;
  44999. if (updatable === void 0) { updatable = false; }
  45000. var result = new BABYLON.Mesh(this._name, this._scene);
  45001. var normals = [];
  45002. var positions = [];
  45003. var uvs = [];
  45004. var bounds = this._points.computeBounds();
  45005. this._points.elements.forEach(function (p) {
  45006. normals.push(0, 1.0, 0);
  45007. positions.push(p.x, 0, p.y);
  45008. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  45009. });
  45010. var indices = [];
  45011. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  45012. for (var i = 0; i < res.length; i++) {
  45013. indices.push(res[i]);
  45014. }
  45015. if (depth > 0) {
  45016. var positionscount = (positions.length / 3); //get the current pointcount
  45017. this._points.elements.forEach(function (p) {
  45018. normals.push(0, -1.0, 0);
  45019. positions.push(p.x, -depth, p.y);
  45020. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  45021. });
  45022. var totalCount = indices.length;
  45023. for (var i = 0; i < totalCount; i += 3) {
  45024. var i0 = indices[i + 0];
  45025. var i1 = indices[i + 1];
  45026. var i2 = indices[i + 2];
  45027. indices.push(i2 + positionscount);
  45028. indices.push(i1 + positionscount);
  45029. indices.push(i0 + positionscount);
  45030. }
  45031. //Add the sides
  45032. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  45033. this._holes.forEach(function (hole) {
  45034. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  45035. });
  45036. }
  45037. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  45038. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  45039. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  45040. result.setIndices(indices);
  45041. return result;
  45042. };
  45043. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  45044. var StartIndex = positions.length / 3;
  45045. var ulength = 0;
  45046. for (var i = 0; i < points.elements.length; i++) {
  45047. var p = points.elements[i];
  45048. var p1;
  45049. if ((i + 1) > points.elements.length - 1) {
  45050. p1 = points.elements[0];
  45051. }
  45052. else {
  45053. p1 = points.elements[i + 1];
  45054. }
  45055. positions.push(p.x, 0, p.y);
  45056. positions.push(p.x, -depth, p.y);
  45057. positions.push(p1.x, 0, p1.y);
  45058. positions.push(p1.x, -depth, p1.y);
  45059. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  45060. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  45061. var v3 = v2.subtract(v1);
  45062. var v4 = new BABYLON.Vector3(0, 1, 0);
  45063. var vn = BABYLON.Vector3.Cross(v3, v4);
  45064. vn = vn.normalize();
  45065. uvs.push(ulength / bounds.width, 0);
  45066. uvs.push(ulength / bounds.width, 1);
  45067. ulength += v3.length();
  45068. uvs.push((ulength / bounds.width), 0);
  45069. uvs.push((ulength / bounds.width), 1);
  45070. if (!flip) {
  45071. normals.push(-vn.x, -vn.y, -vn.z);
  45072. normals.push(-vn.x, -vn.y, -vn.z);
  45073. normals.push(-vn.x, -vn.y, -vn.z);
  45074. normals.push(-vn.x, -vn.y, -vn.z);
  45075. indices.push(StartIndex);
  45076. indices.push(StartIndex + 1);
  45077. indices.push(StartIndex + 2);
  45078. indices.push(StartIndex + 1);
  45079. indices.push(StartIndex + 3);
  45080. indices.push(StartIndex + 2);
  45081. }
  45082. else {
  45083. normals.push(vn.x, vn.y, vn.z);
  45084. normals.push(vn.x, vn.y, vn.z);
  45085. normals.push(vn.x, vn.y, vn.z);
  45086. normals.push(vn.x, vn.y, vn.z);
  45087. indices.push(StartIndex);
  45088. indices.push(StartIndex + 2);
  45089. indices.push(StartIndex + 1);
  45090. indices.push(StartIndex + 1);
  45091. indices.push(StartIndex + 2);
  45092. indices.push(StartIndex + 3);
  45093. }
  45094. StartIndex += 4;
  45095. }
  45096. ;
  45097. };
  45098. return PolygonMeshBuilder;
  45099. }());
  45100. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  45101. })(BABYLON || (BABYLON = {}));
  45102. //# sourceMappingURL=../Mesh/babylon.polygonMesh.js.map
  45103. var BABYLON;
  45104. (function (BABYLON) {
  45105. var Octree = (function () {
  45106. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  45107. if (maxDepth === void 0) { maxDepth = 2; }
  45108. this.maxDepth = maxDepth;
  45109. this.dynamicContent = new Array();
  45110. this._maxBlockCapacity = maxBlockCapacity || 64;
  45111. this._selectionContent = new BABYLON.SmartArray(1024);
  45112. this._creationFunc = creationFunc;
  45113. }
  45114. // Methods
  45115. Octree.prototype.update = function (worldMin, worldMax, entries) {
  45116. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  45117. };
  45118. Octree.prototype.addMesh = function (entry) {
  45119. for (var index = 0; index < this.blocks.length; index++) {
  45120. var block = this.blocks[index];
  45121. block.addEntry(entry);
  45122. }
  45123. };
  45124. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  45125. this._selectionContent.reset();
  45126. for (var index = 0; index < this.blocks.length; index++) {
  45127. var block = this.blocks[index];
  45128. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  45129. }
  45130. if (allowDuplicate) {
  45131. this._selectionContent.concat(this.dynamicContent);
  45132. }
  45133. else {
  45134. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45135. }
  45136. return this._selectionContent;
  45137. };
  45138. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  45139. this._selectionContent.reset();
  45140. for (var index = 0; index < this.blocks.length; index++) {
  45141. var block = this.blocks[index];
  45142. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  45143. }
  45144. if (allowDuplicate) {
  45145. this._selectionContent.concat(this.dynamicContent);
  45146. }
  45147. else {
  45148. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45149. }
  45150. return this._selectionContent;
  45151. };
  45152. Octree.prototype.intersectsRay = function (ray) {
  45153. this._selectionContent.reset();
  45154. for (var index = 0; index < this.blocks.length; index++) {
  45155. var block = this.blocks[index];
  45156. block.intersectsRay(ray, this._selectionContent);
  45157. }
  45158. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45159. return this._selectionContent;
  45160. };
  45161. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  45162. target.blocks = new Array();
  45163. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  45164. // Segmenting space
  45165. for (var x = 0; x < 2; x++) {
  45166. for (var y = 0; y < 2; y++) {
  45167. for (var z = 0; z < 2; z++) {
  45168. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  45169. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  45170. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  45171. block.addEntries(entries);
  45172. target.blocks.push(block);
  45173. }
  45174. }
  45175. }
  45176. };
  45177. Octree.CreationFuncForMeshes = function (entry, block) {
  45178. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  45179. block.entries.push(entry);
  45180. }
  45181. };
  45182. Octree.CreationFuncForSubMeshes = function (entry, block) {
  45183. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  45184. block.entries.push(entry);
  45185. }
  45186. };
  45187. return Octree;
  45188. }());
  45189. BABYLON.Octree = Octree;
  45190. })(BABYLON || (BABYLON = {}));
  45191. //# sourceMappingURL=../../Culling/Octrees/babylon.octree.js.map
  45192. var BABYLON;
  45193. (function (BABYLON) {
  45194. var OctreeBlock = (function () {
  45195. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  45196. this.entries = new Array();
  45197. this._boundingVectors = new Array();
  45198. this._capacity = capacity;
  45199. this._depth = depth;
  45200. this._maxDepth = maxDepth;
  45201. this._creationFunc = creationFunc;
  45202. this._minPoint = minPoint;
  45203. this._maxPoint = maxPoint;
  45204. this._boundingVectors.push(minPoint.clone());
  45205. this._boundingVectors.push(maxPoint.clone());
  45206. this._boundingVectors.push(minPoint.clone());
  45207. this._boundingVectors[2].x = maxPoint.x;
  45208. this._boundingVectors.push(minPoint.clone());
  45209. this._boundingVectors[3].y = maxPoint.y;
  45210. this._boundingVectors.push(minPoint.clone());
  45211. this._boundingVectors[4].z = maxPoint.z;
  45212. this._boundingVectors.push(maxPoint.clone());
  45213. this._boundingVectors[5].z = minPoint.z;
  45214. this._boundingVectors.push(maxPoint.clone());
  45215. this._boundingVectors[6].x = minPoint.x;
  45216. this._boundingVectors.push(maxPoint.clone());
  45217. this._boundingVectors[7].y = minPoint.y;
  45218. }
  45219. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  45220. // Property
  45221. get: function () {
  45222. return this._capacity;
  45223. },
  45224. enumerable: true,
  45225. configurable: true
  45226. });
  45227. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  45228. get: function () {
  45229. return this._minPoint;
  45230. },
  45231. enumerable: true,
  45232. configurable: true
  45233. });
  45234. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  45235. get: function () {
  45236. return this._maxPoint;
  45237. },
  45238. enumerable: true,
  45239. configurable: true
  45240. });
  45241. // Methods
  45242. OctreeBlock.prototype.addEntry = function (entry) {
  45243. if (this.blocks) {
  45244. for (var index = 0; index < this.blocks.length; index++) {
  45245. var block = this.blocks[index];
  45246. block.addEntry(entry);
  45247. }
  45248. return;
  45249. }
  45250. this._creationFunc(entry, this);
  45251. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  45252. this.createInnerBlocks();
  45253. }
  45254. };
  45255. OctreeBlock.prototype.addEntries = function (entries) {
  45256. for (var index = 0; index < entries.length; index++) {
  45257. var mesh = entries[index];
  45258. this.addEntry(mesh);
  45259. }
  45260. };
  45261. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  45262. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  45263. if (this.blocks) {
  45264. for (var index = 0; index < this.blocks.length; index++) {
  45265. var block = this.blocks[index];
  45266. block.select(frustumPlanes, selection, allowDuplicate);
  45267. }
  45268. return;
  45269. }
  45270. if (allowDuplicate) {
  45271. selection.concat(this.entries);
  45272. }
  45273. else {
  45274. selection.concatWithNoDuplicate(this.entries);
  45275. }
  45276. }
  45277. };
  45278. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  45279. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  45280. if (this.blocks) {
  45281. for (var index = 0; index < this.blocks.length; index++) {
  45282. var block = this.blocks[index];
  45283. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  45284. }
  45285. return;
  45286. }
  45287. if (allowDuplicate) {
  45288. selection.concat(this.entries);
  45289. }
  45290. else {
  45291. selection.concatWithNoDuplicate(this.entries);
  45292. }
  45293. }
  45294. };
  45295. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  45296. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  45297. if (this.blocks) {
  45298. for (var index = 0; index < this.blocks.length; index++) {
  45299. var block = this.blocks[index];
  45300. block.intersectsRay(ray, selection);
  45301. }
  45302. return;
  45303. }
  45304. selection.concatWithNoDuplicate(this.entries);
  45305. }
  45306. };
  45307. OctreeBlock.prototype.createInnerBlocks = function () {
  45308. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  45309. };
  45310. return OctreeBlock;
  45311. }());
  45312. BABYLON.OctreeBlock = OctreeBlock;
  45313. })(BABYLON || (BABYLON = {}));
  45314. //# sourceMappingURL=../../Culling/Octrees/babylon.octreeBlock.js.map
  45315. var BABYLON;
  45316. (function (BABYLON) {
  45317. var BlurPostProcess = (function (_super) {
  45318. __extends(BlurPostProcess, _super);
  45319. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  45320. var _this = this;
  45321. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  45322. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  45323. this.direction = direction;
  45324. this.blurWidth = blurWidth;
  45325. this.onApplyObservable.add(function (effect) {
  45326. effect.setFloat2("screenSize", _this.width, _this.height);
  45327. effect.setVector2("direction", _this.direction);
  45328. effect.setFloat("blurWidth", _this.blurWidth);
  45329. });
  45330. }
  45331. return BlurPostProcess;
  45332. }(BABYLON.PostProcess));
  45333. BABYLON.BlurPostProcess = BlurPostProcess;
  45334. })(BABYLON || (BABYLON = {}));
  45335. //# sourceMappingURL=../PostProcess/babylon.blurPostProcess.js.map
  45336. var BABYLON;
  45337. (function (BABYLON) {
  45338. var RefractionPostProcess = (function (_super) {
  45339. __extends(RefractionPostProcess, _super);
  45340. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  45341. var _this = this;
  45342. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  45343. this.color = color;
  45344. this.depth = depth;
  45345. this.colorLevel = colorLevel;
  45346. this.onActivateObservable.add(function (cam) {
  45347. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  45348. });
  45349. this.onApplyObservable.add(function (effect) {
  45350. effect.setColor3("baseColor", _this.color);
  45351. effect.setFloat("depth", _this.depth);
  45352. effect.setFloat("colorLevel", _this.colorLevel);
  45353. effect.setTexture("refractionSampler", _this._refRexture);
  45354. });
  45355. }
  45356. // Methods
  45357. RefractionPostProcess.prototype.dispose = function (camera) {
  45358. if (this._refRexture) {
  45359. this._refRexture.dispose();
  45360. }
  45361. _super.prototype.dispose.call(this, camera);
  45362. };
  45363. return RefractionPostProcess;
  45364. }(BABYLON.PostProcess));
  45365. BABYLON.RefractionPostProcess = RefractionPostProcess;
  45366. })(BABYLON || (BABYLON = {}));
  45367. //# sourceMappingURL=../PostProcess/babylon.refractionPostProcess.js.map
  45368. var BABYLON;
  45369. (function (BABYLON) {
  45370. var BlackAndWhitePostProcess = (function (_super) {
  45371. __extends(BlackAndWhitePostProcess, _super);
  45372. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  45373. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  45374. }
  45375. return BlackAndWhitePostProcess;
  45376. }(BABYLON.PostProcess));
  45377. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  45378. })(BABYLON || (BABYLON = {}));
  45379. //# sourceMappingURL=../PostProcess/babylon.blackAndWhitePostProcess.js.map
  45380. var BABYLON;
  45381. (function (BABYLON) {
  45382. var ConvolutionPostProcess = (function (_super) {
  45383. __extends(ConvolutionPostProcess, _super);
  45384. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  45385. var _this = this;
  45386. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  45387. this.kernel = kernel;
  45388. this.onApply = function (effect) {
  45389. effect.setFloat2("screenSize", _this.width, _this.height);
  45390. effect.setArray("kernel", _this.kernel);
  45391. };
  45392. }
  45393. // Statics
  45394. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  45395. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  45396. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  45397. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  45398. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  45399. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  45400. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  45401. return ConvolutionPostProcess;
  45402. }(BABYLON.PostProcess));
  45403. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  45404. })(BABYLON || (BABYLON = {}));
  45405. //# sourceMappingURL=../PostProcess/babylon.convolutionPostProcess.js.map
  45406. var BABYLON;
  45407. (function (BABYLON) {
  45408. var FilterPostProcess = (function (_super) {
  45409. __extends(FilterPostProcess, _super);
  45410. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  45411. var _this = this;
  45412. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  45413. this.kernelMatrix = kernelMatrix;
  45414. this.onApply = function (effect) {
  45415. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  45416. };
  45417. }
  45418. return FilterPostProcess;
  45419. }(BABYLON.PostProcess));
  45420. BABYLON.FilterPostProcess = FilterPostProcess;
  45421. })(BABYLON || (BABYLON = {}));
  45422. //# sourceMappingURL=../PostProcess/babylon.filterPostProcess.js.map
  45423. var BABYLON;
  45424. (function (BABYLON) {
  45425. var FxaaPostProcess = (function (_super) {
  45426. __extends(FxaaPostProcess, _super);
  45427. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  45428. var _this = this;
  45429. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  45430. this.onSizeChangedObservable.add(function () {
  45431. _this.texelWidth = 1.0 / _this.width;
  45432. _this.texelHeight = 1.0 / _this.height;
  45433. });
  45434. this.onApplyObservable.add(function (effect) {
  45435. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  45436. });
  45437. }
  45438. return FxaaPostProcess;
  45439. }(BABYLON.PostProcess));
  45440. BABYLON.FxaaPostProcess = FxaaPostProcess;
  45441. })(BABYLON || (BABYLON = {}));
  45442. //# sourceMappingURL=../PostProcess/babylon.fxaaPostProcess.js.map
  45443. var BABYLON;
  45444. (function (BABYLON) {
  45445. var StereoscopicInterlacePostProcess = (function (_super) {
  45446. __extends(StereoscopicInterlacePostProcess, _super);
  45447. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  45448. var _this = this;
  45449. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  45450. this._passedProcess = rigCameras[0]._rigPostProcess;
  45451. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  45452. this.onSizeChangedObservable.add(function () {
  45453. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  45454. });
  45455. this.onApplyObservable.add(function (effect) {
  45456. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  45457. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  45458. });
  45459. }
  45460. return StereoscopicInterlacePostProcess;
  45461. }(BABYLON.PostProcess));
  45462. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  45463. })(BABYLON || (BABYLON = {}));
  45464. //# sourceMappingURL=../PostProcess/babylon.stereoscopicInterlacePostProcess.js.map
  45465. var BABYLON;
  45466. (function (BABYLON) {
  45467. var LensFlare = (function () {
  45468. function LensFlare(size, position, color, imgUrl, system) {
  45469. this.size = size;
  45470. this.position = position;
  45471. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  45472. this.dispose = function () {
  45473. if (this.texture) {
  45474. this.texture.dispose();
  45475. }
  45476. // Remove from scene
  45477. var index = this._system.lensFlares.indexOf(this);
  45478. this._system.lensFlares.splice(index, 1);
  45479. };
  45480. this.color = color || new BABYLON.Color3(1, 1, 1);
  45481. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  45482. this._system = system;
  45483. system.lensFlares.push(this);
  45484. }
  45485. return LensFlare;
  45486. }());
  45487. BABYLON.LensFlare = LensFlare;
  45488. })(BABYLON || (BABYLON = {}));
  45489. //# sourceMappingURL=../LensFlare/babylon.lensFlare.js.map
  45490. var BABYLON;
  45491. (function (BABYLON) {
  45492. var LensFlareSystem = (function () {
  45493. function LensFlareSystem(name, emitter, scene) {
  45494. this.name = name;
  45495. this.lensFlares = new Array();
  45496. this.borderLimit = 300;
  45497. this.viewportBorder = 0;
  45498. this.layerMask = 0x0FFFFFFF;
  45499. this._vertexBuffers = {};
  45500. this._isEnabled = true;
  45501. this._scene = scene;
  45502. this._emitter = emitter;
  45503. this.id = name;
  45504. scene.lensFlareSystems.push(this);
  45505. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  45506. var engine = scene.getEngine();
  45507. // VBO
  45508. var vertices = [];
  45509. vertices.push(1, 1);
  45510. vertices.push(-1, 1);
  45511. vertices.push(-1, -1);
  45512. vertices.push(1, -1);
  45513. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  45514. // Indices
  45515. var indices = [];
  45516. indices.push(0);
  45517. indices.push(1);
  45518. indices.push(2);
  45519. indices.push(0);
  45520. indices.push(2);
  45521. indices.push(3);
  45522. this._indexBuffer = engine.createIndexBuffer(indices);
  45523. // Effects
  45524. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  45525. }
  45526. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  45527. get: function () {
  45528. return this._isEnabled;
  45529. },
  45530. set: function (value) {
  45531. this._isEnabled = value;
  45532. },
  45533. enumerable: true,
  45534. configurable: true
  45535. });
  45536. LensFlareSystem.prototype.getScene = function () {
  45537. return this._scene;
  45538. };
  45539. LensFlareSystem.prototype.getEmitter = function () {
  45540. return this._emitter;
  45541. };
  45542. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  45543. this._emitter = newEmitter;
  45544. };
  45545. LensFlareSystem.prototype.getEmitterPosition = function () {
  45546. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  45547. };
  45548. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  45549. var position = this.getEmitterPosition();
  45550. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  45551. this._positionX = position.x;
  45552. this._positionY = position.y;
  45553. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  45554. if (this.viewportBorder > 0) {
  45555. globalViewport.x -= this.viewportBorder;
  45556. globalViewport.y -= this.viewportBorder;
  45557. globalViewport.width += this.viewportBorder * 2;
  45558. globalViewport.height += this.viewportBorder * 2;
  45559. position.x += this.viewportBorder;
  45560. position.y += this.viewportBorder;
  45561. this._positionX += this.viewportBorder;
  45562. this._positionY += this.viewportBorder;
  45563. }
  45564. if (position.z > 0) {
  45565. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  45566. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  45567. return true;
  45568. }
  45569. return true;
  45570. }
  45571. return false;
  45572. };
  45573. LensFlareSystem.prototype._isVisible = function () {
  45574. if (!this._isEnabled) {
  45575. return false;
  45576. }
  45577. var emitterPosition = this.getEmitterPosition();
  45578. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  45579. var distance = direction.length();
  45580. direction.normalize();
  45581. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  45582. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  45583. return !pickInfo.hit || pickInfo.distance > distance;
  45584. };
  45585. LensFlareSystem.prototype.render = function () {
  45586. if (!this._effect.isReady())
  45587. return false;
  45588. var engine = this._scene.getEngine();
  45589. var viewport = this._scene.activeCamera.viewport;
  45590. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  45591. // Position
  45592. if (!this.computeEffectivePosition(globalViewport)) {
  45593. return false;
  45594. }
  45595. // Visibility
  45596. if (!this._isVisible()) {
  45597. return false;
  45598. }
  45599. // Intensity
  45600. var awayX;
  45601. var awayY;
  45602. if (this._positionX < this.borderLimit + globalViewport.x) {
  45603. awayX = this.borderLimit + globalViewport.x - this._positionX;
  45604. }
  45605. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  45606. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  45607. }
  45608. else {
  45609. awayX = 0;
  45610. }
  45611. if (this._positionY < this.borderLimit + globalViewport.y) {
  45612. awayY = this.borderLimit + globalViewport.y - this._positionY;
  45613. }
  45614. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  45615. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  45616. }
  45617. else {
  45618. awayY = 0;
  45619. }
  45620. var away = (awayX > awayY) ? awayX : awayY;
  45621. away -= this.viewportBorder;
  45622. if (away > this.borderLimit) {
  45623. away = this.borderLimit;
  45624. }
  45625. var intensity = 1.0 - (away / this.borderLimit);
  45626. if (intensity < 0) {
  45627. return false;
  45628. }
  45629. if (intensity > 1.0) {
  45630. intensity = 1.0;
  45631. }
  45632. if (this.viewportBorder > 0) {
  45633. globalViewport.x += this.viewportBorder;
  45634. globalViewport.y += this.viewportBorder;
  45635. globalViewport.width -= this.viewportBorder * 2;
  45636. globalViewport.height -= this.viewportBorder * 2;
  45637. this._positionX -= this.viewportBorder;
  45638. this._positionY -= this.viewportBorder;
  45639. }
  45640. // Position
  45641. var centerX = globalViewport.x + globalViewport.width / 2;
  45642. var centerY = globalViewport.y + globalViewport.height / 2;
  45643. var distX = centerX - this._positionX;
  45644. var distY = centerY - this._positionY;
  45645. // Effects
  45646. engine.enableEffect(this._effect);
  45647. engine.setState(false);
  45648. engine.setDepthBuffer(false);
  45649. // VBOs
  45650. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  45651. // Flares
  45652. for (var index = 0; index < this.lensFlares.length; index++) {
  45653. var flare = this.lensFlares[index];
  45654. engine.setAlphaMode(flare.alphaMode);
  45655. var x = centerX - (distX * flare.position);
  45656. var y = centerY - (distY * flare.position);
  45657. var cw = flare.size;
  45658. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  45659. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  45660. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  45661. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  45662. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  45663. // Texture
  45664. this._effect.setTexture("textureSampler", flare.texture);
  45665. // Color
  45666. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  45667. // Draw order
  45668. engine.draw(true, 0, 6);
  45669. }
  45670. engine.setDepthBuffer(true);
  45671. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  45672. return true;
  45673. };
  45674. LensFlareSystem.prototype.dispose = function () {
  45675. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  45676. if (vertexBuffer) {
  45677. vertexBuffer.dispose();
  45678. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  45679. }
  45680. if (this._indexBuffer) {
  45681. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45682. this._indexBuffer = null;
  45683. }
  45684. while (this.lensFlares.length) {
  45685. this.lensFlares[0].dispose();
  45686. }
  45687. // Remove from scene
  45688. var index = this._scene.lensFlareSystems.indexOf(this);
  45689. this._scene.lensFlareSystems.splice(index, 1);
  45690. };
  45691. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  45692. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  45693. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  45694. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  45695. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  45696. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  45697. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  45698. var parsedFlare = parsedLensFlareSystem.flares[index];
  45699. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  45700. }
  45701. return lensFlareSystem;
  45702. };
  45703. LensFlareSystem.prototype.serialize = function () {
  45704. var serializationObject = {};
  45705. serializationObject.id = this.id;
  45706. serializationObject.name = this.name;
  45707. serializationObject.emitterId = this.getEmitter().id;
  45708. serializationObject.borderLimit = this.borderLimit;
  45709. serializationObject.flares = [];
  45710. for (var index = 0; index < this.lensFlares.length; index++) {
  45711. var flare = this.lensFlares[index];
  45712. serializationObject.flares.push({
  45713. size: flare.size,
  45714. position: flare.position,
  45715. color: flare.color.asArray(),
  45716. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  45717. });
  45718. }
  45719. return serializationObject;
  45720. };
  45721. return LensFlareSystem;
  45722. }());
  45723. BABYLON.LensFlareSystem = LensFlareSystem;
  45724. })(BABYLON || (BABYLON = {}));
  45725. //# sourceMappingURL=../LensFlare/babylon.lensFlareSystem.js.map
  45726. var BABYLON;
  45727. (function (BABYLON) {
  45728. // We're mainly based on the logic defined into the FreeCamera code
  45729. var DeviceOrientationCamera = (function (_super) {
  45730. __extends(DeviceOrientationCamera, _super);
  45731. function DeviceOrientationCamera(name, position, scene) {
  45732. _super.call(this, name, position, scene);
  45733. this._quaternionCache = new BABYLON.Quaternion();
  45734. this.inputs.addDeviceOrientation();
  45735. }
  45736. DeviceOrientationCamera.prototype.getTypeName = function () {
  45737. return "DeviceOrientationCamera";
  45738. };
  45739. DeviceOrientationCamera.prototype._checkInputs = function () {
  45740. _super.prototype._checkInputs.call(this);
  45741. this._quaternionCache.copyFrom(this.rotationQuaternion);
  45742. if (this._initialQuaternion) {
  45743. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  45744. }
  45745. };
  45746. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  45747. var _this = this;
  45748. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  45749. //can only work if this camera has a rotation quaternion already.
  45750. if (!this.rotationQuaternion)
  45751. return;
  45752. if (!this._initialQuaternion) {
  45753. this._initialQuaternion = new BABYLON.Quaternion();
  45754. }
  45755. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  45756. ['x', 'y', 'z'].forEach(function (axisName) {
  45757. if (!axis[axisName]) {
  45758. _this._initialQuaternion[axisName] = 0;
  45759. }
  45760. else {
  45761. _this._initialQuaternion[axisName] *= -1;
  45762. }
  45763. });
  45764. this._initialQuaternion.normalize();
  45765. //force rotation update
  45766. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  45767. };
  45768. return DeviceOrientationCamera;
  45769. }(BABYLON.FreeCamera));
  45770. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  45771. })(BABYLON || (BABYLON = {}));
  45772. //# sourceMappingURL=../Cameras/babylon.deviceOrientationCamera.js.map
  45773. var BABYLON;
  45774. (function (BABYLON) {
  45775. var VRDeviceOrientationFreeCamera = (function (_super) {
  45776. __extends(VRDeviceOrientationFreeCamera, _super);
  45777. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  45778. if (compensateDistortion === void 0) { compensateDistortion = true; }
  45779. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  45780. _super.call(this, name, position, scene);
  45781. vrCameraMetrics.compensateDistortion = compensateDistortion;
  45782. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  45783. }
  45784. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  45785. return "VRDeviceOrientationFreeCamera";
  45786. };
  45787. return VRDeviceOrientationFreeCamera;
  45788. }(BABYLON.DeviceOrientationCamera));
  45789. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  45790. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  45791. __extends(VRDeviceOrientationArcRotateCamera, _super);
  45792. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  45793. if (compensateDistortion === void 0) { compensateDistortion = true; }
  45794. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  45795. _super.call(this, name, alpha, beta, radius, target, scene);
  45796. vrCameraMetrics.compensateDistortion = compensateDistortion;
  45797. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  45798. this.inputs.addVRDeviceOrientation();
  45799. }
  45800. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  45801. return "VRDeviceOrientationArcRotateCamera";
  45802. };
  45803. return VRDeviceOrientationArcRotateCamera;
  45804. }(BABYLON.ArcRotateCamera));
  45805. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  45806. })(BABYLON || (BABYLON = {}));
  45807. //# sourceMappingURL=../../Cameras/VR/babylon.vrDeviceOrientationCamera.js.map
  45808. var BABYLON;
  45809. (function (BABYLON) {
  45810. // We're mainly based on the logic defined into the FreeCamera code
  45811. var UniversalCamera = (function (_super) {
  45812. __extends(UniversalCamera, _super);
  45813. //-- end properties for backward compatibility for inputs
  45814. function UniversalCamera(name, position, scene) {
  45815. _super.call(this, name, position, scene);
  45816. this.inputs.addGamepad();
  45817. }
  45818. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  45819. //-- Begin properties for backward compatibility for inputs
  45820. get: function () {
  45821. var gamepad = this.inputs.attached["gamepad"];
  45822. if (gamepad)
  45823. return gamepad.gamepadAngularSensibility;
  45824. },
  45825. set: function (value) {
  45826. var gamepad = this.inputs.attached["gamepad"];
  45827. if (gamepad)
  45828. gamepad.gamepadAngularSensibility = value;
  45829. },
  45830. enumerable: true,
  45831. configurable: true
  45832. });
  45833. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  45834. get: function () {
  45835. var gamepad = this.inputs.attached["gamepad"];
  45836. if (gamepad)
  45837. return gamepad.gamepadMoveSensibility;
  45838. },
  45839. set: function (value) {
  45840. var gamepad = this.inputs.attached["gamepad"];
  45841. if (gamepad)
  45842. gamepad.gamepadMoveSensibility = value;
  45843. },
  45844. enumerable: true,
  45845. configurable: true
  45846. });
  45847. UniversalCamera.prototype.getTypeName = function () {
  45848. return "UniversalCamera";
  45849. };
  45850. return UniversalCamera;
  45851. }(BABYLON.TouchCamera));
  45852. BABYLON.UniversalCamera = UniversalCamera;
  45853. })(BABYLON || (BABYLON = {}));
  45854. //# sourceMappingURL=../Cameras/babylon.universalCamera.js.map
  45855. var BABYLON;
  45856. (function (BABYLON) {
  45857. var Gamepads = (function () {
  45858. function Gamepads(ongamedpadconnected) {
  45859. var _this = this;
  45860. this.babylonGamepads = [];
  45861. this.oneGamepadConnected = false;
  45862. this.isMonitoring = false;
  45863. this.gamepadEventSupported = 'GamepadEvent' in window;
  45864. this.gamepadSupportAvailable = (navigator.getGamepads ||
  45865. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  45866. this._callbackGamepadConnected = ongamedpadconnected;
  45867. if (this.gamepadSupportAvailable) {
  45868. // Checking if the gamepad connected event is supported (like in Firefox)
  45869. if (this.gamepadEventSupported) {
  45870. this._onGamepadConnectedEvent = function (evt) {
  45871. _this._onGamepadConnected(evt);
  45872. };
  45873. this._onGamepadDisonnectedEvent = function (evt) {
  45874. _this._onGamepadDisconnected(evt);
  45875. };
  45876. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45877. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45878. }
  45879. else {
  45880. this._startMonitoringGamepads();
  45881. }
  45882. }
  45883. }
  45884. Gamepads.prototype.dispose = function () {
  45885. if (Gamepads.gamepadDOMInfo) {
  45886. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45887. }
  45888. if (this._onGamepadConnectedEvent) {
  45889. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45890. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45891. this._onGamepadConnectedEvent = null;
  45892. this._onGamepadDisonnectedEvent = null;
  45893. }
  45894. };
  45895. Gamepads.prototype._onGamepadConnected = function (evt) {
  45896. var newGamepad = this._addNewGamepad(evt.gamepad);
  45897. if (this._callbackGamepadConnected)
  45898. this._callbackGamepadConnected(newGamepad);
  45899. this._startMonitoringGamepads();
  45900. };
  45901. Gamepads.prototype._addNewGamepad = function (gamepad) {
  45902. if (!this.oneGamepadConnected) {
  45903. this.oneGamepadConnected = true;
  45904. if (Gamepads.gamepadDOMInfo) {
  45905. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45906. Gamepads.gamepadDOMInfo = null;
  45907. }
  45908. }
  45909. var newGamepad;
  45910. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  45911. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  45912. }
  45913. else {
  45914. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  45915. }
  45916. this.babylonGamepads.push(newGamepad);
  45917. return newGamepad;
  45918. };
  45919. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  45920. // Remove the gamepad from the list of gamepads to monitor.
  45921. for (var i in this.babylonGamepads) {
  45922. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  45923. this.babylonGamepads.splice(+i, 1);
  45924. break;
  45925. }
  45926. }
  45927. // If no gamepads are left, stop the polling loop.
  45928. if (this.babylonGamepads.length == 0) {
  45929. this._stopMonitoringGamepads();
  45930. }
  45931. };
  45932. Gamepads.prototype._startMonitoringGamepads = function () {
  45933. if (!this.isMonitoring) {
  45934. this.isMonitoring = true;
  45935. this._checkGamepadsStatus();
  45936. }
  45937. };
  45938. Gamepads.prototype._stopMonitoringGamepads = function () {
  45939. this.isMonitoring = false;
  45940. };
  45941. Gamepads.prototype._checkGamepadsStatus = function () {
  45942. var _this = this;
  45943. // updating gamepad objects
  45944. this._updateGamepadObjects();
  45945. for (var i in this.babylonGamepads) {
  45946. this.babylonGamepads[i].update();
  45947. }
  45948. if (this.isMonitoring) {
  45949. if (window.requestAnimationFrame) {
  45950. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45951. }
  45952. else if (window.mozRequestAnimationFrame) {
  45953. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45954. }
  45955. else if (window.webkitRequestAnimationFrame) {
  45956. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45957. }
  45958. }
  45959. };
  45960. // This function is called only on Chrome, which does not yet support
  45961. // connection/disconnection events, but requires you to monitor
  45962. // an array for changes.
  45963. Gamepads.prototype._updateGamepadObjects = function () {
  45964. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  45965. for (var i = 0; i < gamepads.length; i++) {
  45966. if (gamepads[i]) {
  45967. if (!(gamepads[i].index in this.babylonGamepads)) {
  45968. var newGamepad = this._addNewGamepad(gamepads[i]);
  45969. if (this._callbackGamepadConnected) {
  45970. this._callbackGamepadConnected(newGamepad);
  45971. }
  45972. }
  45973. else {
  45974. this.babylonGamepads[i].browserGamepad = gamepads[i];
  45975. }
  45976. }
  45977. }
  45978. };
  45979. return Gamepads;
  45980. }());
  45981. BABYLON.Gamepads = Gamepads;
  45982. var StickValues = (function () {
  45983. function StickValues(x, y) {
  45984. this.x = x;
  45985. this.y = y;
  45986. }
  45987. return StickValues;
  45988. }());
  45989. BABYLON.StickValues = StickValues;
  45990. var Gamepad = (function () {
  45991. function Gamepad(id, index, browserGamepad) {
  45992. this.id = id;
  45993. this.index = index;
  45994. this.browserGamepad = browserGamepad;
  45995. if (this.browserGamepad.axes.length >= 2) {
  45996. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  45997. }
  45998. if (this.browserGamepad.axes.length >= 4) {
  45999. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  46000. }
  46001. }
  46002. Gamepad.prototype.onleftstickchanged = function (callback) {
  46003. this._onleftstickchanged = callback;
  46004. };
  46005. Gamepad.prototype.onrightstickchanged = function (callback) {
  46006. this._onrightstickchanged = callback;
  46007. };
  46008. Object.defineProperty(Gamepad.prototype, "leftStick", {
  46009. get: function () {
  46010. return this._leftStick;
  46011. },
  46012. set: function (newValues) {
  46013. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  46014. this._onleftstickchanged(newValues);
  46015. }
  46016. this._leftStick = newValues;
  46017. },
  46018. enumerable: true,
  46019. configurable: true
  46020. });
  46021. Object.defineProperty(Gamepad.prototype, "rightStick", {
  46022. get: function () {
  46023. return this._rightStick;
  46024. },
  46025. set: function (newValues) {
  46026. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  46027. this._onrightstickchanged(newValues);
  46028. }
  46029. this._rightStick = newValues;
  46030. },
  46031. enumerable: true,
  46032. configurable: true
  46033. });
  46034. Gamepad.prototype.update = function () {
  46035. if (this._leftStick) {
  46036. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  46037. }
  46038. if (this._rightStick) {
  46039. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  46040. }
  46041. };
  46042. return Gamepad;
  46043. }());
  46044. BABYLON.Gamepad = Gamepad;
  46045. var GenericPad = (function (_super) {
  46046. __extends(GenericPad, _super);
  46047. function GenericPad(id, index, gamepad) {
  46048. _super.call(this, id, index, gamepad);
  46049. this.id = id;
  46050. this.index = index;
  46051. this.gamepad = gamepad;
  46052. this._buttons = new Array(gamepad.buttons.length);
  46053. }
  46054. GenericPad.prototype.onbuttondown = function (callback) {
  46055. this._onbuttondown = callback;
  46056. };
  46057. GenericPad.prototype.onbuttonup = function (callback) {
  46058. this._onbuttonup = callback;
  46059. };
  46060. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  46061. if (newValue !== currentValue) {
  46062. if (this._onbuttondown && newValue === 1) {
  46063. this._onbuttondown(buttonIndex);
  46064. }
  46065. if (this._onbuttonup && newValue === 0) {
  46066. this._onbuttonup(buttonIndex);
  46067. }
  46068. }
  46069. return newValue;
  46070. };
  46071. GenericPad.prototype.update = function () {
  46072. _super.prototype.update.call(this);
  46073. for (var index = 0; index < this._buttons.length; index++) {
  46074. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  46075. }
  46076. };
  46077. return GenericPad;
  46078. }(Gamepad));
  46079. BABYLON.GenericPad = GenericPad;
  46080. (function (Xbox360Button) {
  46081. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  46082. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  46083. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  46084. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  46085. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  46086. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  46087. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  46088. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  46089. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  46090. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  46091. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  46092. var Xbox360Button = BABYLON.Xbox360Button;
  46093. (function (Xbox360Dpad) {
  46094. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  46095. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  46096. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  46097. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  46098. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  46099. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  46100. var Xbox360Pad = (function (_super) {
  46101. __extends(Xbox360Pad, _super);
  46102. function Xbox360Pad() {
  46103. _super.apply(this, arguments);
  46104. this._leftTrigger = 0;
  46105. this._rightTrigger = 0;
  46106. this._buttonA = 0;
  46107. this._buttonB = 0;
  46108. this._buttonX = 0;
  46109. this._buttonY = 0;
  46110. this._buttonBack = 0;
  46111. this._buttonStart = 0;
  46112. this._buttonLB = 0;
  46113. this._buttonRB = 0;
  46114. this._buttonLeftStick = 0;
  46115. this._buttonRightStick = 0;
  46116. this._dPadUp = 0;
  46117. this._dPadDown = 0;
  46118. this._dPadLeft = 0;
  46119. this._dPadRight = 0;
  46120. }
  46121. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  46122. this._onlefttriggerchanged = callback;
  46123. };
  46124. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  46125. this._onrighttriggerchanged = callback;
  46126. };
  46127. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  46128. get: function () {
  46129. return this._leftTrigger;
  46130. },
  46131. set: function (newValue) {
  46132. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  46133. this._onlefttriggerchanged(newValue);
  46134. }
  46135. this._leftTrigger = newValue;
  46136. },
  46137. enumerable: true,
  46138. configurable: true
  46139. });
  46140. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  46141. get: function () {
  46142. return this._rightTrigger;
  46143. },
  46144. set: function (newValue) {
  46145. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  46146. this._onrighttriggerchanged(newValue);
  46147. }
  46148. this._rightTrigger = newValue;
  46149. },
  46150. enumerable: true,
  46151. configurable: true
  46152. });
  46153. Xbox360Pad.prototype.onbuttondown = function (callback) {
  46154. this._onbuttondown = callback;
  46155. };
  46156. Xbox360Pad.prototype.onbuttonup = function (callback) {
  46157. this._onbuttonup = callback;
  46158. };
  46159. Xbox360Pad.prototype.ondpaddown = function (callback) {
  46160. this._ondpaddown = callback;
  46161. };
  46162. Xbox360Pad.prototype.ondpadup = function (callback) {
  46163. this._ondpadup = callback;
  46164. };
  46165. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  46166. if (newValue !== currentValue) {
  46167. if (this._onbuttondown && newValue === 1) {
  46168. this._onbuttondown(buttonType);
  46169. }
  46170. if (this._onbuttonup && newValue === 0) {
  46171. this._onbuttonup(buttonType);
  46172. }
  46173. }
  46174. return newValue;
  46175. };
  46176. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  46177. if (newValue !== currentValue) {
  46178. if (this._ondpaddown && newValue === 1) {
  46179. this._ondpaddown(buttonType);
  46180. }
  46181. if (this._ondpadup && newValue === 0) {
  46182. this._ondpadup(buttonType);
  46183. }
  46184. }
  46185. return newValue;
  46186. };
  46187. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  46188. get: function () {
  46189. return this._buttonA;
  46190. },
  46191. set: function (value) {
  46192. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  46193. },
  46194. enumerable: true,
  46195. configurable: true
  46196. });
  46197. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  46198. get: function () {
  46199. return this._buttonB;
  46200. },
  46201. set: function (value) {
  46202. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  46203. },
  46204. enumerable: true,
  46205. configurable: true
  46206. });
  46207. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  46208. get: function () {
  46209. return this._buttonX;
  46210. },
  46211. set: function (value) {
  46212. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  46213. },
  46214. enumerable: true,
  46215. configurable: true
  46216. });
  46217. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  46218. get: function () {
  46219. return this._buttonY;
  46220. },
  46221. set: function (value) {
  46222. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  46223. },
  46224. enumerable: true,
  46225. configurable: true
  46226. });
  46227. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  46228. get: function () {
  46229. return this._buttonStart;
  46230. },
  46231. set: function (value) {
  46232. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  46233. },
  46234. enumerable: true,
  46235. configurable: true
  46236. });
  46237. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  46238. get: function () {
  46239. return this._buttonBack;
  46240. },
  46241. set: function (value) {
  46242. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  46243. },
  46244. enumerable: true,
  46245. configurable: true
  46246. });
  46247. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  46248. get: function () {
  46249. return this._buttonLB;
  46250. },
  46251. set: function (value) {
  46252. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  46253. },
  46254. enumerable: true,
  46255. configurable: true
  46256. });
  46257. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  46258. get: function () {
  46259. return this._buttonRB;
  46260. },
  46261. set: function (value) {
  46262. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  46263. },
  46264. enumerable: true,
  46265. configurable: true
  46266. });
  46267. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  46268. get: function () {
  46269. return this._buttonLeftStick;
  46270. },
  46271. set: function (value) {
  46272. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  46273. },
  46274. enumerable: true,
  46275. configurable: true
  46276. });
  46277. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  46278. get: function () {
  46279. return this._buttonRightStick;
  46280. },
  46281. set: function (value) {
  46282. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  46283. },
  46284. enumerable: true,
  46285. configurable: true
  46286. });
  46287. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  46288. get: function () {
  46289. return this._dPadUp;
  46290. },
  46291. set: function (value) {
  46292. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  46293. },
  46294. enumerable: true,
  46295. configurable: true
  46296. });
  46297. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  46298. get: function () {
  46299. return this._dPadDown;
  46300. },
  46301. set: function (value) {
  46302. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  46303. },
  46304. enumerable: true,
  46305. configurable: true
  46306. });
  46307. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  46308. get: function () {
  46309. return this._dPadLeft;
  46310. },
  46311. set: function (value) {
  46312. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  46313. },
  46314. enumerable: true,
  46315. configurable: true
  46316. });
  46317. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  46318. get: function () {
  46319. return this._dPadRight;
  46320. },
  46321. set: function (value) {
  46322. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  46323. },
  46324. enumerable: true,
  46325. configurable: true
  46326. });
  46327. Xbox360Pad.prototype.update = function () {
  46328. _super.prototype.update.call(this);
  46329. this.buttonA = this.browserGamepad.buttons[0].value;
  46330. this.buttonB = this.browserGamepad.buttons[1].value;
  46331. this.buttonX = this.browserGamepad.buttons[2].value;
  46332. this.buttonY = this.browserGamepad.buttons[3].value;
  46333. this.buttonLB = this.browserGamepad.buttons[4].value;
  46334. this.buttonRB = this.browserGamepad.buttons[5].value;
  46335. this.leftTrigger = this.browserGamepad.buttons[6].value;
  46336. this.rightTrigger = this.browserGamepad.buttons[7].value;
  46337. this.buttonBack = this.browserGamepad.buttons[8].value;
  46338. this.buttonStart = this.browserGamepad.buttons[9].value;
  46339. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  46340. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  46341. this.dPadUp = this.browserGamepad.buttons[12].value;
  46342. this.dPadDown = this.browserGamepad.buttons[13].value;
  46343. this.dPadLeft = this.browserGamepad.buttons[14].value;
  46344. this.dPadRight = this.browserGamepad.buttons[15].value;
  46345. };
  46346. return Xbox360Pad;
  46347. }(Gamepad));
  46348. BABYLON.Xbox360Pad = Xbox360Pad;
  46349. })(BABYLON || (BABYLON = {}));
  46350. //# sourceMappingURL=../Tools/babylon.gamepads.js.map
  46351. var BABYLON;
  46352. (function (BABYLON) {
  46353. // We're mainly based on the logic defined into the FreeCamera code
  46354. var GamepadCamera = (function (_super) {
  46355. __extends(GamepadCamera, _super);
  46356. //-- end properties for backward compatibility for inputs
  46357. function GamepadCamera(name, position, scene) {
  46358. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  46359. _super.call(this, name, position, scene);
  46360. }
  46361. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  46362. //-- Begin properties for backward compatibility for inputs
  46363. get: function () {
  46364. var gamepad = this.inputs.attached["gamepad"];
  46365. if (gamepad)
  46366. return gamepad.gamepadAngularSensibility;
  46367. },
  46368. set: function (value) {
  46369. var gamepad = this.inputs.attached["gamepad"];
  46370. if (gamepad)
  46371. gamepad.gamepadAngularSensibility = value;
  46372. },
  46373. enumerable: true,
  46374. configurable: true
  46375. });
  46376. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  46377. get: function () {
  46378. var gamepad = this.inputs.attached["gamepad"];
  46379. if (gamepad)
  46380. return gamepad.gamepadMoveSensibility;
  46381. },
  46382. set: function (value) {
  46383. var gamepad = this.inputs.attached["gamepad"];
  46384. if (gamepad)
  46385. gamepad.gamepadMoveSensibility = value;
  46386. },
  46387. enumerable: true,
  46388. configurable: true
  46389. });
  46390. GamepadCamera.prototype.getTypeName = function () {
  46391. return "GamepadCamera";
  46392. };
  46393. return GamepadCamera;
  46394. }(BABYLON.UniversalCamera));
  46395. BABYLON.GamepadCamera = GamepadCamera;
  46396. })(BABYLON || (BABYLON = {}));
  46397. //# sourceMappingURL=../Cameras/babylon.gamepadCamera.js.map
  46398. var BABYLON;
  46399. (function (BABYLON) {
  46400. var Analyser = (function () {
  46401. function Analyser(scene) {
  46402. this.SMOOTHING = 0.75;
  46403. this.FFT_SIZE = 512;
  46404. this.BARGRAPHAMPLITUDE = 256;
  46405. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  46406. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  46407. this._scene = scene;
  46408. this._audioEngine = BABYLON.Engine.audioEngine;
  46409. if (this._audioEngine.canUseWebAudio) {
  46410. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  46411. this._webAudioAnalyser.minDecibels = -140;
  46412. this._webAudioAnalyser.maxDecibels = 0;
  46413. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  46414. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  46415. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  46416. }
  46417. }
  46418. Analyser.prototype.getFrequencyBinCount = function () {
  46419. if (this._audioEngine.canUseWebAudio) {
  46420. return this._webAudioAnalyser.frequencyBinCount;
  46421. }
  46422. else {
  46423. return 0;
  46424. }
  46425. };
  46426. Analyser.prototype.getByteFrequencyData = function () {
  46427. if (this._audioEngine.canUseWebAudio) {
  46428. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46429. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46430. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  46431. }
  46432. return this._byteFreqs;
  46433. };
  46434. Analyser.prototype.getByteTimeDomainData = function () {
  46435. if (this._audioEngine.canUseWebAudio) {
  46436. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46437. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46438. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  46439. }
  46440. return this._byteTime;
  46441. };
  46442. Analyser.prototype.getFloatFrequencyData = function () {
  46443. if (this._audioEngine.canUseWebAudio) {
  46444. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  46445. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  46446. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  46447. }
  46448. return this._floatFreqs;
  46449. };
  46450. Analyser.prototype.drawDebugCanvas = function () {
  46451. var _this = this;
  46452. if (this._audioEngine.canUseWebAudio) {
  46453. if (!this._debugCanvas) {
  46454. this._debugCanvas = document.createElement("canvas");
  46455. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  46456. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  46457. this._debugCanvas.style.position = "absolute";
  46458. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  46459. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  46460. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  46461. document.body.appendChild(this._debugCanvas);
  46462. this._registerFunc = function () {
  46463. _this.drawDebugCanvas();
  46464. };
  46465. this._scene.registerBeforeRender(this._registerFunc);
  46466. }
  46467. if (this._registerFunc) {
  46468. var workingArray = this.getByteFrequencyData();
  46469. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  46470. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  46471. // Draw the frequency domain chart.
  46472. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  46473. var value = workingArray[i];
  46474. var percent = value / this.BARGRAPHAMPLITUDE;
  46475. var height = this.DEBUGCANVASSIZE.height * percent;
  46476. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  46477. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  46478. var hue = i / this.getFrequencyBinCount() * 360;
  46479. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  46480. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  46481. }
  46482. }
  46483. }
  46484. };
  46485. Analyser.prototype.stopDebugCanvas = function () {
  46486. if (this._debugCanvas) {
  46487. this._scene.unregisterBeforeRender(this._registerFunc);
  46488. this._registerFunc = null;
  46489. document.body.removeChild(this._debugCanvas);
  46490. this._debugCanvas = null;
  46491. this._debugCanvasContext = null;
  46492. }
  46493. };
  46494. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  46495. if (this._audioEngine.canUseWebAudio) {
  46496. inputAudioNode.connect(this._webAudioAnalyser);
  46497. this._webAudioAnalyser.connect(outputAudioNode);
  46498. }
  46499. };
  46500. Analyser.prototype.dispose = function () {
  46501. if (this._audioEngine.canUseWebAudio) {
  46502. this._webAudioAnalyser.disconnect();
  46503. }
  46504. };
  46505. return Analyser;
  46506. }());
  46507. BABYLON.Analyser = Analyser;
  46508. })(BABYLON || (BABYLON = {}));
  46509. //# sourceMappingURL=../Audio/babylon.analyser.js.map
  46510. var BABYLON;
  46511. (function (BABYLON) {
  46512. var DepthRenderer = (function () {
  46513. function DepthRenderer(scene, type) {
  46514. var _this = this;
  46515. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  46516. this._viewMatrix = BABYLON.Matrix.Zero();
  46517. this._projectionMatrix = BABYLON.Matrix.Zero();
  46518. this._transformMatrix = BABYLON.Matrix.Zero();
  46519. this._worldViewProjection = BABYLON.Matrix.Zero();
  46520. this._scene = scene;
  46521. var engine = scene.getEngine();
  46522. // Render target
  46523. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  46524. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46525. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46526. this._depthMap.refreshRate = 1;
  46527. this._depthMap.renderParticles = false;
  46528. this._depthMap.renderList = null;
  46529. // set default depth value to 1.0 (far away)
  46530. this._depthMap.onClearObservable.add(function (engine) {
  46531. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  46532. });
  46533. // Custom render function
  46534. var renderSubMesh = function (subMesh) {
  46535. var mesh = subMesh.getRenderingMesh();
  46536. var scene = _this._scene;
  46537. var engine = scene.getEngine();
  46538. // Culling
  46539. engine.setState(subMesh.getMaterial().backFaceCulling);
  46540. // Managing instances
  46541. var batch = mesh._getInstancesRenderList(subMesh._id);
  46542. if (batch.mustReturn) {
  46543. return;
  46544. }
  46545. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  46546. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  46547. engine.enableEffect(_this._effect);
  46548. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  46549. var material = subMesh.getMaterial();
  46550. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  46551. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  46552. // Alpha test
  46553. if (material && material.needAlphaTesting()) {
  46554. var alphaTexture = material.getAlphaTestTexture();
  46555. _this._effect.setTexture("diffuseSampler", alphaTexture);
  46556. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  46557. }
  46558. // Bones
  46559. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46560. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46561. }
  46562. // Draw
  46563. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  46564. }
  46565. };
  46566. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  46567. var index;
  46568. for (index = 0; index < opaqueSubMeshes.length; index++) {
  46569. renderSubMesh(opaqueSubMeshes.data[index]);
  46570. }
  46571. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  46572. renderSubMesh(alphaTestSubMeshes.data[index]);
  46573. }
  46574. };
  46575. }
  46576. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  46577. var material = subMesh.getMaterial();
  46578. if (material.disableDepthWrite) {
  46579. return false;
  46580. }
  46581. var defines = [];
  46582. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46583. var mesh = subMesh.getMesh();
  46584. var scene = mesh.getScene();
  46585. // Alpha test
  46586. if (material && material.needAlphaTesting()) {
  46587. defines.push("#define ALPHATEST");
  46588. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46589. attribs.push(BABYLON.VertexBuffer.UVKind);
  46590. defines.push("#define UV1");
  46591. }
  46592. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  46593. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46594. defines.push("#define UV2");
  46595. }
  46596. }
  46597. // Bones
  46598. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46599. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46600. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46601. if (mesh.numBoneInfluencers > 4) {
  46602. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46603. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46604. }
  46605. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46606. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46607. }
  46608. else {
  46609. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46610. }
  46611. // Instances
  46612. if (useInstances) {
  46613. defines.push("#define INSTANCES");
  46614. attribs.push("world0");
  46615. attribs.push("world1");
  46616. attribs.push("world2");
  46617. attribs.push("world3");
  46618. }
  46619. // Get correct effect
  46620. var join = defines.join("\n");
  46621. if (this._cachedDefines !== join) {
  46622. this._cachedDefines = join;
  46623. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  46624. }
  46625. return this._effect.isReady();
  46626. };
  46627. DepthRenderer.prototype.getDepthMap = function () {
  46628. return this._depthMap;
  46629. };
  46630. // Methods
  46631. DepthRenderer.prototype.dispose = function () {
  46632. this._depthMap.dispose();
  46633. };
  46634. return DepthRenderer;
  46635. }());
  46636. BABYLON.DepthRenderer = DepthRenderer;
  46637. })(BABYLON || (BABYLON = {}));
  46638. //# sourceMappingURL=../Rendering/babylon.depthRenderer.js.map
  46639. var BABYLON;
  46640. (function (BABYLON) {
  46641. var SSAORenderingPipeline = (function (_super) {
  46642. __extends(SSAORenderingPipeline, _super);
  46643. /**
  46644. * @constructor
  46645. * @param {string} name - The rendering pipeline name
  46646. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46647. * @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 }
  46648. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46649. */
  46650. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  46651. var _this = this;
  46652. _super.call(this, scene.getEngine(), name);
  46653. // Members
  46654. /**
  46655. * The PassPostProcess id in the pipeline that contains the original scene color
  46656. * @type {string}
  46657. */
  46658. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  46659. /**
  46660. * The SSAO PostProcess id in the pipeline
  46661. * @type {string}
  46662. */
  46663. this.SSAORenderEffect = "SSAORenderEffect";
  46664. /**
  46665. * The horizontal blur PostProcess id in the pipeline
  46666. * @type {string}
  46667. */
  46668. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  46669. /**
  46670. * The vertical blur PostProcess id in the pipeline
  46671. * @type {string}
  46672. */
  46673. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  46674. /**
  46675. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  46676. * @type {string}
  46677. */
  46678. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  46679. /**
  46680. * The output strength of the SSAO post-process. Default value is 1.0.
  46681. * @type {number}
  46682. */
  46683. this.totalStrength = 1.0;
  46684. /**
  46685. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  46686. * @type {number}
  46687. */
  46688. this.radius = 0.0001;
  46689. /**
  46690. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  46691. * Must not be equal to fallOff and superior to fallOff.
  46692. * Default value is 0.975
  46693. * @type {number}
  46694. */
  46695. this.area = 0.0075;
  46696. /**
  46697. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  46698. * Must not be equal to area and inferior to area.
  46699. * Default value is 0.0
  46700. * @type {number}
  46701. */
  46702. this.fallOff = 0.000001;
  46703. /**
  46704. * The base color of the SSAO post-process
  46705. * The final result is "base + ssao" between [0, 1]
  46706. * @type {number}
  46707. */
  46708. this.base = 0.5;
  46709. this._firstUpdate = true;
  46710. this._scene = scene;
  46711. // Set up assets
  46712. this._createRandomTexture();
  46713. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  46714. var ssaoRatio = ratio.ssaoRatio || ratio;
  46715. var combineRatio = ratio.combineRatio || ratio;
  46716. this._ratio = {
  46717. ssaoRatio: ssaoRatio,
  46718. combineRatio: combineRatio
  46719. };
  46720. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  46721. this._createSSAOPostProcess(ssaoRatio);
  46722. this._createBlurPostProcess(ssaoRatio);
  46723. this._createSSAOCombinePostProcess(combineRatio);
  46724. // Set up pipeline
  46725. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  46726. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  46727. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  46728. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  46729. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  46730. // Finish
  46731. scene.postProcessRenderPipelineManager.addPipeline(this);
  46732. if (cameras)
  46733. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46734. }
  46735. // Public Methods
  46736. /**
  46737. * Returns the horizontal blur PostProcess
  46738. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  46739. */
  46740. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  46741. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  46742. return null;
  46743. };
  46744. /**
  46745. * Returns the vertical blur PostProcess
  46746. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  46747. */
  46748. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  46749. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  46750. return null;
  46751. };
  46752. /**
  46753. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  46754. */
  46755. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  46756. if (disableDepthRender === void 0) { disableDepthRender = false; }
  46757. for (var i = 0; i < this._scene.cameras.length; i++) {
  46758. var camera = this._scene.cameras[i];
  46759. this._originalColorPostProcess.dispose(camera);
  46760. this._ssaoPostProcess.dispose(camera);
  46761. this._blurHPostProcess.dispose(camera);
  46762. this._blurVPostProcess.dispose(camera);
  46763. this._ssaoCombinePostProcess.dispose(camera);
  46764. }
  46765. this._randomTexture.dispose();
  46766. if (disableDepthRender)
  46767. this._scene.disableDepthRenderer();
  46768. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46769. };
  46770. // Private Methods
  46771. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  46772. var _this = this;
  46773. /*
  46774. var samplerOffsets = [
  46775. -8.0, -6.0, -4.0, -2.0,
  46776. 0.0,
  46777. 2.0, 4.0, 6.0, 8.0
  46778. ];
  46779. */
  46780. var samples = 16;
  46781. var samplerOffsets = [];
  46782. for (var i = -8; i < 8; i++) {
  46783. samplerOffsets.push(i * 2);
  46784. }
  46785. 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");
  46786. this._blurHPostProcess.onApply = function (effect) {
  46787. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  46788. effect.setTexture("depthSampler", _this._depthTexture);
  46789. if (_this._firstUpdate) {
  46790. effect.setArray("samplerOffsets", samplerOffsets);
  46791. }
  46792. };
  46793. 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");
  46794. this._blurVPostProcess.onApply = function (effect) {
  46795. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  46796. effect.setTexture("depthSampler", _this._depthTexture);
  46797. if (_this._firstUpdate) {
  46798. effect.setArray("samplerOffsets", samplerOffsets);
  46799. _this._firstUpdate = false;
  46800. }
  46801. };
  46802. };
  46803. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  46804. var _this = this;
  46805. var numSamples = 16;
  46806. var sampleSphere = [
  46807. 0.5381, 0.1856, -0.4319,
  46808. 0.1379, 0.2486, 0.4430,
  46809. 0.3371, 0.5679, -0.0057,
  46810. -0.6999, -0.0451, -0.0019,
  46811. 0.0689, -0.1598, -0.8547,
  46812. 0.0560, 0.0069, -0.1843,
  46813. -0.0146, 0.1402, 0.0762,
  46814. 0.0100, -0.1924, -0.0344,
  46815. -0.3577, -0.5301, -0.4358,
  46816. -0.3169, 0.1063, 0.0158,
  46817. 0.0103, -0.5869, 0.0046,
  46818. -0.0897, -0.4940, 0.3287,
  46819. 0.7119, -0.0154, -0.0918,
  46820. -0.0533, 0.0596, -0.5411,
  46821. 0.0352, -0.0631, 0.5460,
  46822. -0.4776, 0.2847, -0.0271
  46823. ];
  46824. var samplesFactor = 1.0 / numSamples;
  46825. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  46826. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  46827. "area", "fallOff", "base", "range", "viewport"
  46828. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  46829. var viewport = new BABYLON.Vector2(0, 0);
  46830. this._ssaoPostProcess.onApply = function (effect) {
  46831. if (_this._firstUpdate) {
  46832. effect.setArray3("sampleSphere", sampleSphere);
  46833. effect.setFloat("samplesFactor", samplesFactor);
  46834. effect.setFloat("randTextureTiles", 4.0);
  46835. }
  46836. effect.setFloat("totalStrength", _this.totalStrength);
  46837. effect.setFloat("radius", _this.radius);
  46838. effect.setFloat("area", _this.area);
  46839. effect.setFloat("fallOff", _this.fallOff);
  46840. effect.setFloat("base", _this.base);
  46841. effect.setTexture("textureSampler", _this._depthTexture);
  46842. effect.setTexture("randomSampler", _this._randomTexture);
  46843. };
  46844. };
  46845. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  46846. var _this = this;
  46847. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46848. this._ssaoCombinePostProcess.onApply = function (effect) {
  46849. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  46850. };
  46851. };
  46852. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  46853. var size = 512;
  46854. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  46855. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46856. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46857. var context = this._randomTexture.getContext();
  46858. var rand = function (min, max) {
  46859. return Math.random() * (max - min) + min;
  46860. };
  46861. var randVector = BABYLON.Vector3.Zero();
  46862. for (var x = 0; x < size; x++) {
  46863. for (var y = 0; y < size; y++) {
  46864. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  46865. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  46866. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  46867. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  46868. context.fillRect(x, y, 1, 1);
  46869. }
  46870. }
  46871. this._randomTexture.update(false);
  46872. };
  46873. __decorate([
  46874. BABYLON.serialize()
  46875. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  46876. __decorate([
  46877. BABYLON.serialize()
  46878. ], SSAORenderingPipeline.prototype, "radius", void 0);
  46879. __decorate([
  46880. BABYLON.serialize()
  46881. ], SSAORenderingPipeline.prototype, "area", void 0);
  46882. __decorate([
  46883. BABYLON.serialize()
  46884. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  46885. __decorate([
  46886. BABYLON.serialize()
  46887. ], SSAORenderingPipeline.prototype, "base", void 0);
  46888. __decorate([
  46889. BABYLON.serialize()
  46890. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  46891. return SSAORenderingPipeline;
  46892. }(BABYLON.PostProcessRenderPipeline));
  46893. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  46894. })(BABYLON || (BABYLON = {}));
  46895. //# sourceMappingURL=../PostProcess/babylon.ssaoRenderingPipeline.js.map
  46896. var BABYLON;
  46897. (function (BABYLON) {
  46898. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  46899. var VolumetricLightScatteringPostProcess = (function (_super) {
  46900. __extends(VolumetricLightScatteringPostProcess, _super);
  46901. /**
  46902. * @constructor
  46903. * @param {string} name - The post-process name
  46904. * @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)
  46905. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  46906. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  46907. * @param {number} samples - The post-process quality, default 100
  46908. * @param {number} samplingMode - The post-process filtering mode
  46909. * @param {BABYLON.Engine} engine - The babylon engine
  46910. * @param {boolean} reusable - If the post-process is reusable
  46911. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  46912. */
  46913. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  46914. var _this = this;
  46915. if (samples === void 0) { samples = 100; }
  46916. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46917. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  46918. this._screenCoordinates = BABYLON.Vector2.Zero();
  46919. /**
  46920. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  46921. * @type {Vector3}
  46922. */
  46923. this.customMeshPosition = BABYLON.Vector3.Zero();
  46924. /**
  46925. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  46926. * @type {boolean}
  46927. */
  46928. this.useCustomMeshPosition = false;
  46929. /**
  46930. * If the post-process should inverse the light scattering direction
  46931. * @type {boolean}
  46932. */
  46933. this.invert = true;
  46934. /**
  46935. * Array containing the excluded meshes not rendered in the internal pass
  46936. */
  46937. this.excludedMeshes = new Array();
  46938. /**
  46939. * Controls the overall intensity of the post-process
  46940. * @type {number}
  46941. */
  46942. this.exposure = 0.3;
  46943. /**
  46944. * Dissipates each sample's contribution in range [0, 1]
  46945. * @type {number}
  46946. */
  46947. this.decay = 0.96815;
  46948. /**
  46949. * Controls the overall intensity of each sample
  46950. * @type {number}
  46951. */
  46952. this.weight = 0.58767;
  46953. /**
  46954. * Controls the density of each sample
  46955. * @type {number}
  46956. */
  46957. this.density = 0.926;
  46958. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  46959. var engine = scene.getEngine();
  46960. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  46961. // Configure mesh
  46962. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  46963. // Configure
  46964. this._createPass(scene, ratio.passRatio || ratio);
  46965. this.onActivate = function (camera) {
  46966. if (!_this.isSupported) {
  46967. _this.dispose(camera);
  46968. }
  46969. _this.onActivate = null;
  46970. };
  46971. this.onApplyObservable.add(function (effect) {
  46972. _this._updateMeshScreenCoordinates(scene);
  46973. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  46974. effect.setFloat("exposure", _this.exposure);
  46975. effect.setFloat("decay", _this.decay);
  46976. effect.setFloat("weight", _this.weight);
  46977. effect.setFloat("density", _this.density);
  46978. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  46979. });
  46980. }
  46981. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  46982. get: function () {
  46983. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  46984. return false;
  46985. },
  46986. set: function (useDiffuseColor) {
  46987. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  46988. },
  46989. enumerable: true,
  46990. configurable: true
  46991. });
  46992. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  46993. var mesh = subMesh.getMesh();
  46994. // Render this.mesh as default
  46995. if (mesh === this.mesh) {
  46996. return mesh.material.isReady(mesh);
  46997. }
  46998. var defines = [];
  46999. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47000. var material = subMesh.getMaterial();
  47001. var needUV = false;
  47002. // Alpha test
  47003. if (material) {
  47004. if (material.needAlphaTesting()) {
  47005. defines.push("#define ALPHATEST");
  47006. }
  47007. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47008. attribs.push(BABYLON.VertexBuffer.UVKind);
  47009. defines.push("#define UV1");
  47010. }
  47011. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47012. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47013. defines.push("#define UV2");
  47014. }
  47015. }
  47016. // Bones
  47017. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47018. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47019. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47020. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47021. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47022. }
  47023. else {
  47024. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47025. }
  47026. // Instances
  47027. if (useInstances) {
  47028. defines.push("#define INSTANCES");
  47029. attribs.push("world0");
  47030. attribs.push("world1");
  47031. attribs.push("world2");
  47032. attribs.push("world3");
  47033. }
  47034. // Get correct effect
  47035. var join = defines.join("\n");
  47036. if (this._cachedDefines !== join) {
  47037. this._cachedDefines = join;
  47038. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  47039. }
  47040. return this._volumetricLightScatteringPass.isReady();
  47041. };
  47042. /**
  47043. * Sets the new light position for light scattering effect
  47044. * @param {BABYLON.Vector3} The new custom light position
  47045. */
  47046. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  47047. this.customMeshPosition = position;
  47048. };
  47049. /**
  47050. * Returns the light position for light scattering effect
  47051. * @return {BABYLON.Vector3} The custom light position
  47052. */
  47053. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  47054. return this.customMeshPosition;
  47055. };
  47056. /**
  47057. * Disposes the internal assets and detaches the post-process from the camera
  47058. */
  47059. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  47060. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  47061. if (rttIndex !== -1) {
  47062. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  47063. }
  47064. this._volumetricLightScatteringRTT.dispose();
  47065. _super.prototype.dispose.call(this, camera);
  47066. };
  47067. /**
  47068. * Returns the render target texture used by the post-process
  47069. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  47070. */
  47071. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  47072. return this._volumetricLightScatteringRTT;
  47073. };
  47074. // Private methods
  47075. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  47076. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  47077. return true;
  47078. }
  47079. return false;
  47080. };
  47081. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  47082. var _this = this;
  47083. var engine = scene.getEngine();
  47084. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47085. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47086. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47087. this._volumetricLightScatteringRTT.renderList = null;
  47088. this._volumetricLightScatteringRTT.renderParticles = false;
  47089. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  47090. // Custom render function for submeshes
  47091. var renderSubMesh = function (subMesh) {
  47092. var mesh = subMesh.getRenderingMesh();
  47093. if (_this._meshExcluded(mesh)) {
  47094. return;
  47095. }
  47096. var scene = mesh.getScene();
  47097. var engine = scene.getEngine();
  47098. // Culling
  47099. engine.setState(subMesh.getMaterial().backFaceCulling);
  47100. // Managing instances
  47101. var batch = mesh._getInstancesRenderList(subMesh._id);
  47102. if (batch.mustReturn) {
  47103. return;
  47104. }
  47105. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47106. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47107. var effect = _this._volumetricLightScatteringPass;
  47108. if (mesh === _this.mesh) {
  47109. effect = subMesh.getMaterial().getEffect();
  47110. }
  47111. engine.enableEffect(effect);
  47112. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  47113. if (mesh === _this.mesh) {
  47114. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  47115. }
  47116. else {
  47117. var material = subMesh.getMaterial();
  47118. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  47119. // Alpha test
  47120. if (material && material.needAlphaTesting()) {
  47121. var alphaTexture = material.getAlphaTestTexture();
  47122. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  47123. if (alphaTexture) {
  47124. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47125. }
  47126. }
  47127. // Bones
  47128. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47129. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47130. }
  47131. }
  47132. // Draw
  47133. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  47134. }
  47135. };
  47136. // Render target texture callbacks
  47137. var savedSceneClearColor;
  47138. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  47139. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  47140. savedSceneClearColor = scene.clearColor;
  47141. scene.clearColor = sceneClearColor;
  47142. });
  47143. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  47144. scene.clearColor = savedSceneClearColor;
  47145. });
  47146. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  47147. var engine = scene.getEngine();
  47148. var index;
  47149. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47150. renderSubMesh(opaqueSubMeshes.data[index]);
  47151. }
  47152. engine.setAlphaTesting(true);
  47153. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47154. renderSubMesh(alphaTestSubMeshes.data[index]);
  47155. }
  47156. engine.setAlphaTesting(false);
  47157. if (transparentSubMeshes.length) {
  47158. // Sort sub meshes
  47159. for (index = 0; index < transparentSubMeshes.length; index++) {
  47160. var submesh = transparentSubMeshes.data[index];
  47161. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  47162. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  47163. }
  47164. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  47165. sortedArray.sort(function (a, b) {
  47166. // Alpha index first
  47167. if (a._alphaIndex > b._alphaIndex) {
  47168. return 1;
  47169. }
  47170. if (a._alphaIndex < b._alphaIndex) {
  47171. return -1;
  47172. }
  47173. // Then distance to camera
  47174. if (a._distanceToCamera < b._distanceToCamera) {
  47175. return 1;
  47176. }
  47177. if (a._distanceToCamera > b._distanceToCamera) {
  47178. return -1;
  47179. }
  47180. return 0;
  47181. });
  47182. // Render sub meshes
  47183. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47184. for (index = 0; index < sortedArray.length; index++) {
  47185. renderSubMesh(sortedArray[index]);
  47186. }
  47187. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47188. }
  47189. };
  47190. };
  47191. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  47192. var transform = scene.getTransformMatrix();
  47193. var meshPosition;
  47194. if (this.useCustomMeshPosition) {
  47195. meshPosition = this.customMeshPosition;
  47196. }
  47197. else if (this.attachedNode) {
  47198. meshPosition = this.attachedNode.position;
  47199. }
  47200. else {
  47201. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  47202. }
  47203. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  47204. this._screenCoordinates.x = pos.x / this._viewPort.width;
  47205. this._screenCoordinates.y = pos.y / this._viewPort.height;
  47206. if (this.invert)
  47207. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  47208. };
  47209. // Static methods
  47210. /**
  47211. * Creates a default mesh for the Volumeric Light Scattering post-process
  47212. * @param {string} The mesh name
  47213. * @param {BABYLON.Scene} The scene where to create the mesh
  47214. * @return {BABYLON.Mesh} the default mesh
  47215. */
  47216. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  47217. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  47218. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  47219. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  47220. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  47221. mesh.material = material;
  47222. return mesh;
  47223. };
  47224. __decorate([
  47225. BABYLON.serializeAsVector3()
  47226. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  47227. __decorate([
  47228. BABYLON.serialize()
  47229. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  47230. __decorate([
  47231. BABYLON.serialize()
  47232. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  47233. __decorate([
  47234. BABYLON.serializeAsMeshReference()
  47235. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  47236. __decorate([
  47237. BABYLON.serialize()
  47238. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  47239. __decorate([
  47240. BABYLON.serialize()
  47241. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  47242. __decorate([
  47243. BABYLON.serialize()
  47244. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  47245. __decorate([
  47246. BABYLON.serialize()
  47247. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  47248. __decorate([
  47249. BABYLON.serialize()
  47250. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  47251. return VolumetricLightScatteringPostProcess;
  47252. }(BABYLON.PostProcess));
  47253. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  47254. })(BABYLON || (BABYLON = {}));
  47255. //# sourceMappingURL=../PostProcess/babylon.volumetricLightScatteringPostProcess.js.map
  47256. // BABYLON.JS Chromatic Aberration GLSL Shader
  47257. // Author: Olivier Guyot
  47258. // Separates very slightly R, G and B colors on the edges of the screen
  47259. // Inspired by Francois Tarlier & Martins Upitis
  47260. var BABYLON;
  47261. (function (BABYLON) {
  47262. var LensRenderingPipeline = (function (_super) {
  47263. __extends(LensRenderingPipeline, _super);
  47264. /**
  47265. * @constructor
  47266. *
  47267. * Effect parameters are as follow:
  47268. * {
  47269. * chromatic_aberration: number; // from 0 to x (1 for realism)
  47270. * edge_blur: number; // from 0 to x (1 for realism)
  47271. * distortion: number; // from 0 to x (1 for realism)
  47272. * grain_amount: number; // from 0 to 1
  47273. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  47274. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  47275. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  47276. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  47277. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  47278. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  47279. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  47280. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  47281. * }
  47282. * Note: if an effect parameter is unset, effect is disabled
  47283. *
  47284. * @param {string} name - The rendering pipeline name
  47285. * @param {object} parameters - An object containing all parameters (see above)
  47286. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47287. * @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)
  47288. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47289. */
  47290. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  47291. var _this = this;
  47292. if (ratio === void 0) { ratio = 1.0; }
  47293. _super.call(this, scene.getEngine(), name);
  47294. // Lens effects can be of the following:
  47295. // - chromatic aberration (slight shift of RGB colors)
  47296. // - blur on the edge of the lens
  47297. // - lens distortion
  47298. // - depth-of-field blur & highlights enhancing
  47299. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  47300. // - grain effect (noise or custom texture)
  47301. // Two additional texture samplers are needed:
  47302. // - depth map (for depth-of-field)
  47303. // - grain texture
  47304. /**
  47305. * The chromatic aberration PostProcess id in the pipeline
  47306. * @type {string}
  47307. */
  47308. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  47309. /**
  47310. * The highlights enhancing PostProcess id in the pipeline
  47311. * @type {string}
  47312. */
  47313. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  47314. /**
  47315. * The depth-of-field PostProcess id in the pipeline
  47316. * @type {string}
  47317. */
  47318. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  47319. this._scene = scene;
  47320. // Fetch texture samplers
  47321. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47322. if (parameters.grain_texture) {
  47323. this._grainTexture = parameters.grain_texture;
  47324. }
  47325. else {
  47326. this._createGrainTexture();
  47327. }
  47328. // save parameters
  47329. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  47330. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  47331. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  47332. this._distortion = parameters.distortion ? parameters.distortion : 0;
  47333. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  47334. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  47335. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  47336. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  47337. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  47338. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  47339. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  47340. // Create effects
  47341. this._createChromaticAberrationPostProcess(ratio);
  47342. this._createHighlightsPostProcess(ratio);
  47343. this._createDepthOfFieldPostProcess(ratio / 4);
  47344. // Set up pipeline
  47345. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  47346. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  47347. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  47348. if (this._highlightsGain === -1) {
  47349. this._disableEffect(this.HighlightsEnhancingEffect, null);
  47350. }
  47351. // Finish
  47352. scene.postProcessRenderPipelineManager.addPipeline(this);
  47353. if (cameras) {
  47354. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47355. }
  47356. }
  47357. // public methods (self explanatory)
  47358. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  47359. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  47360. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  47361. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  47362. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  47363. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  47364. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  47365. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  47366. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  47367. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  47368. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  47369. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  47370. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  47371. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  47372. };
  47373. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  47374. this._highlightsPostProcess.updateEffect();
  47375. };
  47376. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  47377. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  47378. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  47379. this._highlightsGain = amount;
  47380. };
  47381. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  47382. if (this._highlightsGain === -1) {
  47383. this._highlightsGain = 1.0;
  47384. }
  47385. this._highlightsThreshold = amount;
  47386. };
  47387. LensRenderingPipeline.prototype.disableHighlights = function () {
  47388. this._highlightsGain = -1;
  47389. };
  47390. /**
  47391. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  47392. */
  47393. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47394. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47395. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47396. this._chromaticAberrationPostProcess = undefined;
  47397. this._highlightsPostProcess = undefined;
  47398. this._depthOfFieldPostProcess = undefined;
  47399. this._grainTexture.dispose();
  47400. if (disableDepthRender)
  47401. this._scene.disableDepthRenderer();
  47402. };
  47403. // colors shifting and distortion
  47404. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  47405. var _this = this;
  47406. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  47407. [], // samplers
  47408. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47409. this._chromaticAberrationPostProcess.onApply = function (effect) {
  47410. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  47411. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47412. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47413. };
  47414. };
  47415. // highlights enhancing
  47416. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  47417. var _this = this;
  47418. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  47419. [], // samplers
  47420. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  47421. this._highlightsPostProcess.onApply = function (effect) {
  47422. effect.setFloat('gain', _this._highlightsGain);
  47423. effect.setFloat('threshold', _this._highlightsThreshold);
  47424. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  47425. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47426. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47427. };
  47428. };
  47429. // colors shifting and distortion
  47430. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  47431. var _this = this;
  47432. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  47433. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  47434. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  47435. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47436. this._depthOfFieldPostProcess.onApply = function (effect) {
  47437. effect.setTexture("depthSampler", _this._depthTexture);
  47438. effect.setTexture("grainSampler", _this._grainTexture);
  47439. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  47440. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  47441. effect.setFloat('grain_amount', _this._grainAmount);
  47442. effect.setBool('blur_noise', _this._blurNoise);
  47443. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47444. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47445. effect.setFloat('distortion', _this._distortion);
  47446. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  47447. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  47448. effect.setFloat('aperture', _this._dofAperture);
  47449. effect.setFloat('darken', _this._dofDarken);
  47450. effect.setFloat('edge_blur', _this._edgeBlur);
  47451. effect.setBool('highlights', (_this._highlightsGain !== -1));
  47452. effect.setFloat('near', _this._scene.activeCamera.minZ);
  47453. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  47454. };
  47455. };
  47456. // creates a black and white random noise texture, 512x512
  47457. LensRenderingPipeline.prototype._createGrainTexture = function () {
  47458. var size = 512;
  47459. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47460. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47461. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47462. var context = this._grainTexture.getContext();
  47463. var rand = function (min, max) {
  47464. return Math.random() * (max - min) + min;
  47465. };
  47466. var value;
  47467. for (var x = 0; x < size; x++) {
  47468. for (var y = 0; y < size; y++) {
  47469. value = Math.floor(rand(0.42, 0.58) * 255);
  47470. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  47471. context.fillRect(x, y, 1, 1);
  47472. }
  47473. }
  47474. this._grainTexture.update(false);
  47475. };
  47476. return LensRenderingPipeline;
  47477. }(BABYLON.PostProcessRenderPipeline));
  47478. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  47479. })(BABYLON || (BABYLON = {}));
  47480. //# sourceMappingURL=../PostProcess/babylon.lensRenderingPipeline.js.map
  47481. //
  47482. // This post-process allows the modification of rendered colors by using
  47483. // a 'look-up table' (LUT). This effect is also called Color Grading.
  47484. //
  47485. // The object needs to be provided an url to a texture containing the color
  47486. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  47487. // Use an image editing software to tweak the LUT to match your needs.
  47488. //
  47489. // For an example of a color LUT, see here:
  47490. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  47491. // For explanations on color grading, see here:
  47492. // http://udn.epicgames.com/Three/ColorGrading.html
  47493. //
  47494. var BABYLON;
  47495. (function (BABYLON) {
  47496. var ColorCorrectionPostProcess = (function (_super) {
  47497. __extends(ColorCorrectionPostProcess, _super);
  47498. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  47499. var _this = this;
  47500. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  47501. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47502. this._colorTableTexture.anisotropicFilteringLevel = 1;
  47503. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47504. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47505. this.onApply = function (effect) {
  47506. effect.setTexture("colorTable", _this._colorTableTexture);
  47507. };
  47508. }
  47509. return ColorCorrectionPostProcess;
  47510. }(BABYLON.PostProcess));
  47511. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  47512. })(BABYLON || (BABYLON = {}));
  47513. //# sourceMappingURL=../PostProcess/babylon.colorCorrectionPostProcess.js.map
  47514. var BABYLON;
  47515. (function (BABYLON) {
  47516. var AnaglyphFreeCamera = (function (_super) {
  47517. __extends(AnaglyphFreeCamera, _super);
  47518. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  47519. _super.call(this, name, position, scene);
  47520. this.interaxialDistance = interaxialDistance;
  47521. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  47522. }
  47523. AnaglyphFreeCamera.prototype.getTypeName = function () {
  47524. return "AnaglyphFreeCamera";
  47525. };
  47526. return AnaglyphFreeCamera;
  47527. }(BABYLON.FreeCamera));
  47528. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  47529. var AnaglyphArcRotateCamera = (function (_super) {
  47530. __extends(AnaglyphArcRotateCamera, _super);
  47531. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  47532. _super.call(this, name, alpha, beta, radius, target, scene);
  47533. this.interaxialDistance = interaxialDistance;
  47534. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  47535. }
  47536. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  47537. return "AnaglyphArcRotateCamera";
  47538. };
  47539. return AnaglyphArcRotateCamera;
  47540. }(BABYLON.ArcRotateCamera));
  47541. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  47542. var AnaglyphGamepadCamera = (function (_super) {
  47543. __extends(AnaglyphGamepadCamera, _super);
  47544. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  47545. _super.call(this, name, position, scene);
  47546. this.interaxialDistance = interaxialDistance;
  47547. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  47548. }
  47549. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  47550. return "AnaglyphGamepadCamera";
  47551. };
  47552. return AnaglyphGamepadCamera;
  47553. }(BABYLON.GamepadCamera));
  47554. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  47555. var AnaglyphUniversalCamera = (function (_super) {
  47556. __extends(AnaglyphUniversalCamera, _super);
  47557. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  47558. _super.call(this, name, position, scene);
  47559. this.interaxialDistance = interaxialDistance;
  47560. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  47561. }
  47562. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  47563. return "AnaglyphUniversalCamera";
  47564. };
  47565. return AnaglyphUniversalCamera;
  47566. }(BABYLON.UniversalCamera));
  47567. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  47568. var StereoscopicFreeCamera = (function (_super) {
  47569. __extends(StereoscopicFreeCamera, _super);
  47570. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  47571. _super.call(this, name, position, scene);
  47572. this.interaxialDistance = interaxialDistance;
  47573. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  47574. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  47575. }
  47576. StereoscopicFreeCamera.prototype.getTypeName = function () {
  47577. return "StereoscopicFreeCamera";
  47578. };
  47579. return StereoscopicFreeCamera;
  47580. }(BABYLON.FreeCamera));
  47581. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  47582. var StereoscopicArcRotateCamera = (function (_super) {
  47583. __extends(StereoscopicArcRotateCamera, _super);
  47584. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  47585. _super.call(this, name, alpha, beta, radius, target, scene);
  47586. this.interaxialDistance = interaxialDistance;
  47587. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  47588. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  47589. }
  47590. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  47591. return "StereoscopicArcRotateCamera";
  47592. };
  47593. return StereoscopicArcRotateCamera;
  47594. }(BABYLON.ArcRotateCamera));
  47595. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  47596. var StereoscopicGamepadCamera = (function (_super) {
  47597. __extends(StereoscopicGamepadCamera, _super);
  47598. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  47599. _super.call(this, name, position, scene);
  47600. this.interaxialDistance = interaxialDistance;
  47601. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  47602. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  47603. }
  47604. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  47605. return "StereoscopicGamepadCamera";
  47606. };
  47607. return StereoscopicGamepadCamera;
  47608. }(BABYLON.GamepadCamera));
  47609. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  47610. var StereoscopicUniversalCamera = (function (_super) {
  47611. __extends(StereoscopicUniversalCamera, _super);
  47612. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  47613. _super.call(this, name, position, scene);
  47614. this.interaxialDistance = interaxialDistance;
  47615. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  47616. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  47617. }
  47618. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  47619. return "StereoscopicUniversalCamera";
  47620. };
  47621. return StereoscopicUniversalCamera;
  47622. }(BABYLON.UniversalCamera));
  47623. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  47624. })(BABYLON || (BABYLON = {}));
  47625. //# sourceMappingURL=../Cameras/babylon.stereoscopicCameras.js.map
  47626. var BABYLON;
  47627. (function (BABYLON) {
  47628. var HDRRenderingPipeline = (function (_super) {
  47629. __extends(HDRRenderingPipeline, _super);
  47630. /**
  47631. * @constructor
  47632. * @param {string} name - The rendering pipeline name
  47633. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47634. * @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)
  47635. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  47636. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47637. */
  47638. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  47639. var _this = this;
  47640. if (originalPostProcess === void 0) { originalPostProcess = null; }
  47641. _super.call(this, scene.getEngine(), name);
  47642. /**
  47643. * Public members
  47644. */
  47645. // Gaussian Blur
  47646. /**
  47647. * Gaussian blur coefficient
  47648. * @type {number}
  47649. */
  47650. this.gaussCoeff = 0.3;
  47651. /**
  47652. * Gaussian blur mean
  47653. * @type {number}
  47654. */
  47655. this.gaussMean = 1.0;
  47656. /**
  47657. * Gaussian blur standard deviation
  47658. * @type {number}
  47659. */
  47660. this.gaussStandDev = 0.8;
  47661. /**
  47662. * Gaussian blur multiplier. Multiplies the blur effect
  47663. * @type {number}
  47664. */
  47665. this.gaussMultiplier = 4.0;
  47666. // HDR
  47667. /**
  47668. * Exposure, controls the overall intensity of the pipeline
  47669. * @type {number}
  47670. */
  47671. this.exposure = 1.0;
  47672. /**
  47673. * Minimum luminance that the post-process can output. Luminance is >= 0
  47674. * @type {number}
  47675. */
  47676. this.minimumLuminance = 1.0;
  47677. /**
  47678. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  47679. * @type {number}
  47680. */
  47681. this.maximumLuminance = 1e20;
  47682. /**
  47683. * Increase rate for luminance: eye adaptation speed to dark
  47684. * @type {number}
  47685. */
  47686. this.luminanceIncreaserate = 0.5;
  47687. /**
  47688. * Decrease rate for luminance: eye adaptation speed to bright
  47689. * @type {number}
  47690. */
  47691. this.luminanceDecreaseRate = 0.5;
  47692. // Bright pass
  47693. /**
  47694. * Minimum luminance needed to compute HDR
  47695. * @type {number}
  47696. */
  47697. this.brightThreshold = 0.8;
  47698. this._needUpdate = true;
  47699. this._scene = scene;
  47700. // Bright pass
  47701. this._createBrightPassPostProcess(scene, ratio);
  47702. // Down sample X4
  47703. this._createDownSampleX4PostProcess(scene, ratio);
  47704. // Create gaussian blur post-processes
  47705. this._createGaussianBlurPostProcess(scene, ratio);
  47706. // Texture adder
  47707. this._createTextureAdderPostProcess(scene, ratio);
  47708. // Luminance generator
  47709. this._createLuminanceGeneratorPostProcess(scene);
  47710. // HDR
  47711. this._createHDRPostProcess(scene, ratio);
  47712. // Pass postprocess
  47713. if (originalPostProcess === null) {
  47714. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47715. }
  47716. else {
  47717. this._originalPostProcess = originalPostProcess;
  47718. }
  47719. // Configure pipeline
  47720. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  47721. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  47722. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  47723. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  47724. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  47725. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  47726. var addDownSamplerPostProcess = function (id) {
  47727. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  47728. };
  47729. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  47730. addDownSamplerPostProcess(i);
  47731. }
  47732. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  47733. // Finish
  47734. scene.postProcessRenderPipelineManager.addPipeline(this);
  47735. if (cameras !== null) {
  47736. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47737. }
  47738. this.update();
  47739. }
  47740. /**
  47741. * Tells the pipeline to update its post-processes
  47742. */
  47743. HDRRenderingPipeline.prototype.update = function () {
  47744. this._needUpdate = true;
  47745. };
  47746. /**
  47747. * Returns the current calculated luminance
  47748. */
  47749. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  47750. return this._hdrCurrentLuminance;
  47751. };
  47752. /**
  47753. * Returns the currently drawn luminance
  47754. */
  47755. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  47756. return this._hdrOutputLuminance;
  47757. };
  47758. /**
  47759. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  47760. */
  47761. HDRRenderingPipeline.prototype.dispose = function () {
  47762. this._originalPostProcess = undefined;
  47763. this._brightPassPostProcess = undefined;
  47764. this._downSampleX4PostProcess = undefined;
  47765. this._guassianBlurHPostProcess = undefined;
  47766. this._guassianBlurVPostProcess = undefined;
  47767. this._textureAdderPostProcess = undefined;
  47768. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  47769. this._downSamplePostProcesses[i] = undefined;
  47770. }
  47771. this._hdrPostProcess = undefined;
  47772. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47773. };
  47774. /**
  47775. * Creates the HDR post-process and computes the luminance adaptation
  47776. */
  47777. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  47778. var _this = this;
  47779. var hdrLastLuminance = 0.0;
  47780. this._hdrOutputLuminance = -1.0;
  47781. this._hdrCurrentLuminance = 1.0;
  47782. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  47783. this._hdrPostProcess.onApply = function (effect) {
  47784. if (_this._hdrOutputLuminance < 0.0) {
  47785. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  47786. }
  47787. else {
  47788. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  47789. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  47790. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  47791. }
  47792. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  47793. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  47794. }
  47795. else {
  47796. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  47797. }
  47798. }
  47799. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  47800. hdrLastLuminance += scene.getEngine().getDeltaTime();
  47801. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  47802. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  47803. effect.setFloat("exposure", _this.exposure);
  47804. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  47805. _this._needUpdate = false;
  47806. };
  47807. };
  47808. /**
  47809. * Texture Adder post-process
  47810. */
  47811. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  47812. var _this = this;
  47813. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  47814. this._textureAdderPostProcess.onApply = function (effect) {
  47815. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  47816. };
  47817. };
  47818. /**
  47819. * Down sample X4 post-process
  47820. */
  47821. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  47822. var _this = this;
  47823. var downSampleX4Offsets = new Array(32);
  47824. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  47825. this._downSampleX4PostProcess.onApply = function (effect) {
  47826. if (_this._needUpdate) {
  47827. var id = 0;
  47828. for (var i = -2; i < 2; i++) {
  47829. for (var j = -2; j < 2; j++) {
  47830. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  47831. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  47832. id += 2;
  47833. }
  47834. }
  47835. }
  47836. effect.setArray2("dsOffsets", downSampleX4Offsets);
  47837. };
  47838. };
  47839. /**
  47840. * Bright pass post-process
  47841. */
  47842. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  47843. var _this = this;
  47844. var brightOffsets = new Array(8);
  47845. var brightPassCallback = function (effect) {
  47846. if (_this._needUpdate) {
  47847. var sU = (1.0 / _this._brightPassPostProcess.width);
  47848. var sV = (1.0 / _this._brightPassPostProcess.height);
  47849. brightOffsets[0] = -0.5 * sU;
  47850. brightOffsets[1] = 0.5 * sV;
  47851. brightOffsets[2] = 0.5 * sU;
  47852. brightOffsets[3] = 0.5 * sV;
  47853. brightOffsets[4] = -0.5 * sU;
  47854. brightOffsets[5] = -0.5 * sV;
  47855. brightOffsets[6] = 0.5 * sU;
  47856. brightOffsets[7] = -0.5 * sV;
  47857. }
  47858. effect.setArray2("dsOffsets", brightOffsets);
  47859. effect.setFloat("brightThreshold", _this.brightThreshold);
  47860. };
  47861. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  47862. this._brightPassPostProcess.onApply = brightPassCallback;
  47863. };
  47864. /**
  47865. * Luminance generator. Creates the luminance post-process and down sample post-processes
  47866. */
  47867. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  47868. var _this = this;
  47869. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  47870. var luminanceOffsets = new Array(8);
  47871. var downSampleOffsets = new Array(18);
  47872. var halfDestPixelSize;
  47873. this._downSamplePostProcesses = new Array(lumSteps);
  47874. // Utils for luminance
  47875. var luminanceUpdateSourceOffsets = function (width, height) {
  47876. var sU = (1.0 / width);
  47877. var sV = (1.0 / height);
  47878. luminanceOffsets[0] = -0.5 * sU;
  47879. luminanceOffsets[1] = 0.5 * sV;
  47880. luminanceOffsets[2] = 0.5 * sU;
  47881. luminanceOffsets[3] = 0.5 * sV;
  47882. luminanceOffsets[4] = -0.5 * sU;
  47883. luminanceOffsets[5] = -0.5 * sV;
  47884. luminanceOffsets[6] = 0.5 * sU;
  47885. luminanceOffsets[7] = -0.5 * sV;
  47886. };
  47887. var luminanceUpdateDestOffsets = function (width, height) {
  47888. var id = 0;
  47889. for (var x = -1; x < 2; x++) {
  47890. for (var y = -1; y < 2; y++) {
  47891. downSampleOffsets[id] = (x) / width;
  47892. downSampleOffsets[id + 1] = (y) / height;
  47893. id += 2;
  47894. }
  47895. }
  47896. };
  47897. // Luminance callback
  47898. var luminanceCallback = function (effect) {
  47899. if (_this._needUpdate) {
  47900. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  47901. }
  47902. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  47903. effect.setArray2("lumOffsets", luminanceOffsets);
  47904. };
  47905. // Down sample callbacks
  47906. var downSampleCallback = function (indice) {
  47907. var i = indice;
  47908. return function (effect) {
  47909. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47910. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47911. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  47912. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  47913. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  47914. effect.setArray2("dsOffsets", downSampleOffsets);
  47915. };
  47916. };
  47917. var downSampleAfterRenderCallback = function (effect) {
  47918. // Unpack result
  47919. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  47920. 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);
  47921. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  47922. };
  47923. // Create luminance post-process
  47924. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  47925. 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);
  47926. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  47927. // Create down sample post-processes
  47928. for (var i = lumSteps - 2; i >= 0; i--) {
  47929. var length = Math.pow(3, i);
  47930. ratio = { width: length, height: length };
  47931. var defines = "#define DOWN_SAMPLE\n";
  47932. if (i === 0) {
  47933. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  47934. }
  47935. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  47936. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  47937. if (i === 0) {
  47938. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  47939. }
  47940. }
  47941. };
  47942. /**
  47943. * Gaussian blur post-processes. Horizontal and Vertical
  47944. */
  47945. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  47946. var _this = this;
  47947. var blurOffsetsW = new Array(9);
  47948. var blurOffsetsH = new Array(9);
  47949. var blurWeights = new Array(9);
  47950. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  47951. // Utils for gaussian blur
  47952. var calculateBlurOffsets = function (height) {
  47953. var lastOutputDimensions = {
  47954. width: scene.getEngine().getRenderWidth(),
  47955. height: scene.getEngine().getRenderHeight()
  47956. };
  47957. for (var i = 0; i < 9; i++) {
  47958. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  47959. if (height) {
  47960. blurOffsetsH[i] = value;
  47961. }
  47962. else {
  47963. blurOffsetsW[i] = value;
  47964. }
  47965. }
  47966. };
  47967. var calculateWeights = function () {
  47968. var x = 0.0;
  47969. for (var i = 0; i < 9; i++) {
  47970. x = (i - 4.0) / 4.0;
  47971. 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));
  47972. }
  47973. };
  47974. // Callback
  47975. var gaussianBlurCallback = function (height) {
  47976. return function (effect) {
  47977. if (_this._needUpdate) {
  47978. calculateWeights();
  47979. calculateBlurOffsets(height);
  47980. }
  47981. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  47982. effect.setArray("blurWeights", blurWeights);
  47983. effect.setFloat("multiplier", _this.gaussMultiplier);
  47984. };
  47985. };
  47986. // Create horizontal gaussian blur post-processes
  47987. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  47988. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  47989. // Create vertical gaussian blur post-process
  47990. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  47991. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  47992. };
  47993. // Luminance generator
  47994. HDRRenderingPipeline.LUM_STEPS = 6;
  47995. return HDRRenderingPipeline;
  47996. }(BABYLON.PostProcessRenderPipeline));
  47997. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  47998. })(BABYLON || (BABYLON = {}));
  47999. //# sourceMappingURL=../PostProcess/babylon.hdrRenderingPipeline.js.map
  48000. var BABYLON;
  48001. (function (BABYLON) {
  48002. var FaceAdjacencies = (function () {
  48003. function FaceAdjacencies() {
  48004. this.edges = new Array();
  48005. this.edgesConnectedCount = 0;
  48006. }
  48007. return FaceAdjacencies;
  48008. }());
  48009. var EdgesRenderer = (function () {
  48010. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  48011. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  48012. if (epsilon === void 0) { epsilon = 0.95; }
  48013. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  48014. this.edgesWidthScalerForOrthographic = 1000.0;
  48015. this.edgesWidthScalerForPerspective = 50.0;
  48016. this._linesPositions = new Array();
  48017. this._linesNormals = new Array();
  48018. this._linesIndices = new Array();
  48019. this._buffers = {};
  48020. this._checkVerticesInsteadOfIndices = false;
  48021. this._source = source;
  48022. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  48023. this._epsilon = epsilon;
  48024. this._prepareRessources();
  48025. this._generateEdgesLines();
  48026. }
  48027. EdgesRenderer.prototype._prepareRessources = function () {
  48028. if (this._lineShader) {
  48029. return;
  48030. }
  48031. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  48032. attributes: ["position", "normal"],
  48033. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  48034. });
  48035. this._lineShader.disableDepthWrite = true;
  48036. this._lineShader.backFaceCulling = false;
  48037. };
  48038. EdgesRenderer.prototype.dispose = function () {
  48039. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  48040. if (buffer) {
  48041. buffer.dispose();
  48042. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  48043. }
  48044. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  48045. if (buffer) {
  48046. buffer.dispose();
  48047. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  48048. }
  48049. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  48050. this._lineShader.dispose();
  48051. };
  48052. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  48053. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  48054. return 0;
  48055. }
  48056. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  48057. return 1;
  48058. }
  48059. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  48060. return 2;
  48061. }
  48062. return -1;
  48063. };
  48064. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  48065. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  48066. return 0;
  48067. }
  48068. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  48069. return 1;
  48070. }
  48071. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  48072. return 2;
  48073. }
  48074. return -1;
  48075. };
  48076. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  48077. var needToCreateLine;
  48078. if (edge === undefined) {
  48079. needToCreateLine = true;
  48080. }
  48081. else {
  48082. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  48083. needToCreateLine = dotProduct < this._epsilon;
  48084. }
  48085. if (needToCreateLine) {
  48086. var offset = this._linesPositions.length / 3;
  48087. var normal = p0.subtract(p1);
  48088. normal.normalize();
  48089. // Positions
  48090. this._linesPositions.push(p0.x);
  48091. this._linesPositions.push(p0.y);
  48092. this._linesPositions.push(p0.z);
  48093. this._linesPositions.push(p0.x);
  48094. this._linesPositions.push(p0.y);
  48095. this._linesPositions.push(p0.z);
  48096. this._linesPositions.push(p1.x);
  48097. this._linesPositions.push(p1.y);
  48098. this._linesPositions.push(p1.z);
  48099. this._linesPositions.push(p1.x);
  48100. this._linesPositions.push(p1.y);
  48101. this._linesPositions.push(p1.z);
  48102. // Normals
  48103. this._linesNormals.push(p1.x);
  48104. this._linesNormals.push(p1.y);
  48105. this._linesNormals.push(p1.z);
  48106. this._linesNormals.push(-1);
  48107. this._linesNormals.push(p1.x);
  48108. this._linesNormals.push(p1.y);
  48109. this._linesNormals.push(p1.z);
  48110. this._linesNormals.push(1);
  48111. this._linesNormals.push(p0.x);
  48112. this._linesNormals.push(p0.y);
  48113. this._linesNormals.push(p0.z);
  48114. this._linesNormals.push(-1);
  48115. this._linesNormals.push(p0.x);
  48116. this._linesNormals.push(p0.y);
  48117. this._linesNormals.push(p0.z);
  48118. this._linesNormals.push(1);
  48119. // Indices
  48120. this._linesIndices.push(offset);
  48121. this._linesIndices.push(offset + 1);
  48122. this._linesIndices.push(offset + 2);
  48123. this._linesIndices.push(offset);
  48124. this._linesIndices.push(offset + 2);
  48125. this._linesIndices.push(offset + 3);
  48126. }
  48127. };
  48128. EdgesRenderer.prototype._generateEdgesLines = function () {
  48129. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48130. var indices = this._source.getIndices();
  48131. // First let's find adjacencies
  48132. var adjacencies = new Array();
  48133. var faceNormals = new Array();
  48134. var index;
  48135. var faceAdjacencies;
  48136. // Prepare faces
  48137. for (index = 0; index < indices.length; index += 3) {
  48138. faceAdjacencies = new FaceAdjacencies();
  48139. var p0Index = indices[index];
  48140. var p1Index = indices[index + 1];
  48141. var p2Index = indices[index + 2];
  48142. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  48143. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  48144. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  48145. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  48146. faceNormal.normalize();
  48147. faceNormals.push(faceNormal);
  48148. adjacencies.push(faceAdjacencies);
  48149. }
  48150. // Scan
  48151. for (index = 0; index < adjacencies.length; index++) {
  48152. faceAdjacencies = adjacencies[index];
  48153. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  48154. var otherFaceAdjacencies = adjacencies[otherIndex];
  48155. if (faceAdjacencies.edgesConnectedCount === 3) {
  48156. break;
  48157. }
  48158. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  48159. continue;
  48160. }
  48161. var otherP0 = indices[otherIndex * 3];
  48162. var otherP1 = indices[otherIndex * 3 + 1];
  48163. var otherP2 = indices[otherIndex * 3 + 2];
  48164. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  48165. var otherEdgeIndex;
  48166. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  48167. continue;
  48168. }
  48169. switch (edgeIndex) {
  48170. case 0:
  48171. if (this._checkVerticesInsteadOfIndices) {
  48172. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48173. }
  48174. else {
  48175. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  48176. }
  48177. break;
  48178. case 1:
  48179. if (this._checkVerticesInsteadOfIndices) {
  48180. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48181. }
  48182. else {
  48183. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  48184. }
  48185. break;
  48186. case 2:
  48187. if (this._checkVerticesInsteadOfIndices) {
  48188. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48189. }
  48190. else {
  48191. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  48192. }
  48193. break;
  48194. }
  48195. if (otherEdgeIndex === -1) {
  48196. continue;
  48197. }
  48198. faceAdjacencies.edges[edgeIndex] = otherIndex;
  48199. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  48200. faceAdjacencies.edgesConnectedCount++;
  48201. otherFaceAdjacencies.edgesConnectedCount++;
  48202. if (faceAdjacencies.edgesConnectedCount === 3) {
  48203. break;
  48204. }
  48205. }
  48206. }
  48207. }
  48208. // Create lines
  48209. for (index = 0; index < adjacencies.length; index++) {
  48210. // 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
  48211. var current = adjacencies[index];
  48212. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  48213. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  48214. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  48215. }
  48216. // Merge into a single mesh
  48217. var engine = this._source.getScene().getEngine();
  48218. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  48219. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  48220. this._ib = engine.createIndexBuffer(this._linesIndices);
  48221. this._indicesCount = this._linesIndices.length;
  48222. };
  48223. EdgesRenderer.prototype.render = function () {
  48224. if (!this._lineShader.isReady()) {
  48225. return;
  48226. }
  48227. var scene = this._source.getScene();
  48228. var engine = scene.getEngine();
  48229. this._lineShader._preBind();
  48230. // VBOs
  48231. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  48232. scene.resetCachedMaterial();
  48233. this._lineShader.setColor4("color", this._source.edgesColor);
  48234. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  48235. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  48236. }
  48237. else {
  48238. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  48239. }
  48240. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  48241. this._lineShader.bind(this._source.getWorldMatrix());
  48242. // Draw order
  48243. engine.draw(true, 0, this._indicesCount);
  48244. this._lineShader.unbind();
  48245. engine.setDepthWrite(true);
  48246. };
  48247. return EdgesRenderer;
  48248. }());
  48249. BABYLON.EdgesRenderer = EdgesRenderer;
  48250. })(BABYLON || (BABYLON = {}));
  48251. //# sourceMappingURL=../Rendering/babylon.edgesRenderer.js.map
  48252. var BABYLON;
  48253. (function (BABYLON) {
  48254. (function (TonemappingOperator) {
  48255. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  48256. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  48257. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  48258. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  48259. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  48260. var TonemappingOperator = BABYLON.TonemappingOperator;
  48261. ;
  48262. var TonemapPostProcess = (function (_super) {
  48263. __extends(TonemapPostProcess, _super);
  48264. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  48265. var _this = this;
  48266. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48267. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48268. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  48269. this._operator = _operator;
  48270. this.exposureAdjustment = exposureAdjustment;
  48271. var defines = "#define ";
  48272. if (this._operator === TonemappingOperator.Hable)
  48273. defines += "HABLE_TONEMAPPING";
  48274. else if (this._operator === TonemappingOperator.Reinhard)
  48275. defines += "REINHARD_TONEMAPPING";
  48276. else if (this._operator === TonemappingOperator.HejiDawson)
  48277. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  48278. else if (this._operator === TonemappingOperator.Photographic)
  48279. defines += "PHOTOGRAPHIC_TONEMAPPING";
  48280. //sadly a second call to create the effect.
  48281. this.updateEffect(defines);
  48282. this.onApply = function (effect) {
  48283. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  48284. };
  48285. }
  48286. return TonemapPostProcess;
  48287. }(BABYLON.PostProcess));
  48288. BABYLON.TonemapPostProcess = TonemapPostProcess;
  48289. })(BABYLON || (BABYLON = {}));
  48290. //# sourceMappingURL=../PostProcess/babylon.tonemapPostProcess.js.map
  48291. var BABYLON;
  48292. (function (BABYLON) {
  48293. var ReflectionProbe = (function () {
  48294. function ReflectionProbe(name, size, scene, generateMipMaps) {
  48295. var _this = this;
  48296. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48297. this.name = name;
  48298. this._viewMatrix = BABYLON.Matrix.Identity();
  48299. this._target = BABYLON.Vector3.Zero();
  48300. this._add = BABYLON.Vector3.Zero();
  48301. this.invertYAxis = false;
  48302. this.position = BABYLON.Vector3.Zero();
  48303. this._scene = scene;
  48304. this._scene.reflectionProbes.push(this);
  48305. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  48306. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  48307. switch (faceIndex) {
  48308. case 0:
  48309. _this._add.copyFromFloats(1, 0, 0);
  48310. break;
  48311. case 1:
  48312. _this._add.copyFromFloats(-1, 0, 0);
  48313. break;
  48314. case 2:
  48315. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  48316. break;
  48317. case 3:
  48318. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  48319. break;
  48320. case 4:
  48321. _this._add.copyFromFloats(0, 0, 1);
  48322. break;
  48323. case 5:
  48324. _this._add.copyFromFloats(0, 0, -1);
  48325. break;
  48326. }
  48327. if (_this._attachedMesh) {
  48328. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  48329. }
  48330. _this.position.addToRef(_this._add, _this._target);
  48331. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  48332. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  48333. });
  48334. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  48335. scene.updateTransformMatrix(true);
  48336. });
  48337. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  48338. }
  48339. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  48340. get: function () {
  48341. return this._renderTargetTexture.refreshRate;
  48342. },
  48343. set: function (value) {
  48344. this._renderTargetTexture.refreshRate = value;
  48345. },
  48346. enumerable: true,
  48347. configurable: true
  48348. });
  48349. ReflectionProbe.prototype.getScene = function () {
  48350. return this._scene;
  48351. };
  48352. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  48353. get: function () {
  48354. return this._renderTargetTexture;
  48355. },
  48356. enumerable: true,
  48357. configurable: true
  48358. });
  48359. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  48360. get: function () {
  48361. return this._renderTargetTexture.renderList;
  48362. },
  48363. enumerable: true,
  48364. configurable: true
  48365. });
  48366. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  48367. this._attachedMesh = mesh;
  48368. };
  48369. ReflectionProbe.prototype.dispose = function () {
  48370. var index = this._scene.reflectionProbes.indexOf(this);
  48371. if (index !== -1) {
  48372. // Remove from the scene if found
  48373. this._scene.reflectionProbes.splice(index, 1);
  48374. }
  48375. if (this._renderTargetTexture) {
  48376. this._renderTargetTexture.dispose();
  48377. this._renderTargetTexture = null;
  48378. }
  48379. };
  48380. return ReflectionProbe;
  48381. }());
  48382. BABYLON.ReflectionProbe = ReflectionProbe;
  48383. })(BABYLON || (BABYLON = {}));
  48384. //# sourceMappingURL=../Probes/babylon.reflectionProbe.js.map
  48385. var BABYLON;
  48386. (function (BABYLON) {
  48387. var SolidParticle = (function () {
  48388. /**
  48389. * Creates a Solid Particle object.
  48390. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  48391. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  48392. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  48393. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  48394. * `shapeId` (integer) is the model shape identifier in the SPS.
  48395. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  48396. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  48397. */
  48398. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  48399. this.idx = 0; // particle global index
  48400. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  48401. this.position = BABYLON.Vector3.Zero(); // position
  48402. this.rotation = BABYLON.Vector3.Zero(); // rotation
  48403. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  48404. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  48405. this.velocity = BABYLON.Vector3.Zero(); // velocity
  48406. this.alive = true; // alive
  48407. this.isVisible = true; // visibility
  48408. this._pos = 0; // index of this particle in the global "positions" array
  48409. this.shapeId = 0; // model shape id
  48410. this.idxInShape = 0; // index of the particle in its shape id
  48411. this.idx = particleIndex;
  48412. this._pos = positionIndex;
  48413. this._model = model;
  48414. this.shapeId = shapeId;
  48415. this.idxInShape = idxInShape;
  48416. this._sps = sps;
  48417. if (modelBoundingInfo) {
  48418. this._modelBoundingInfo = modelBoundingInfo;
  48419. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  48420. }
  48421. }
  48422. Object.defineProperty(SolidParticle.prototype, "scale", {
  48423. /**
  48424. * legacy support, changed scale to scaling
  48425. */
  48426. get: function () {
  48427. return this.scaling;
  48428. },
  48429. set: function (scale) {
  48430. this.scaling = scale;
  48431. },
  48432. enumerable: true,
  48433. configurable: true
  48434. });
  48435. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  48436. /**
  48437. * legacy support, changed quaternion to rotationQuaternion
  48438. */
  48439. get: function () {
  48440. return this.rotationQuaternion;
  48441. },
  48442. set: function (q) {
  48443. this.rotationQuaternion = q;
  48444. },
  48445. enumerable: true,
  48446. configurable: true
  48447. });
  48448. /**
  48449. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  48450. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  48451. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  48452. */
  48453. SolidParticle.prototype.intersectsMesh = function (target) {
  48454. if (!this._boundingInfo || !target._boundingInfo) {
  48455. return false;
  48456. }
  48457. if (this._sps._bSphereOnly) {
  48458. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  48459. }
  48460. return this._boundingInfo.intersects(target._boundingInfo, false);
  48461. };
  48462. return SolidParticle;
  48463. }());
  48464. BABYLON.SolidParticle = SolidParticle;
  48465. var ModelShape = (function () {
  48466. /**
  48467. * 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.
  48468. * SPS internal tool, don't use it manually.
  48469. */
  48470. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  48471. this.shapeID = id;
  48472. this._shape = shape;
  48473. this._shapeUV = shapeUV;
  48474. this._positionFunction = posFunction;
  48475. this._vertexFunction = vtxFunction;
  48476. }
  48477. return ModelShape;
  48478. }());
  48479. BABYLON.ModelShape = ModelShape;
  48480. })(BABYLON || (BABYLON = {}));
  48481. //# sourceMappingURL=../Particles/babylon.solidParticle.js.map
  48482. var BABYLON;
  48483. (function (BABYLON) {
  48484. /**
  48485. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  48486. */
  48487. var SolidParticleSystem = (function () {
  48488. /**
  48489. * Creates a SPS (Solid Particle System) object.
  48490. * `name` (String) is the SPS name, this will be the underlying mesh name.
  48491. * `scene` (Scene) is the scene in which the SPS is added.
  48492. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  48493. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  48494. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  48495. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  48496. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  48497. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  48498. */
  48499. function SolidParticleSystem(name, scene, options) {
  48500. // public members
  48501. /**
  48502. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  48503. * Example : var p = SPS.particles[i];
  48504. */
  48505. this.particles = new Array();
  48506. /**
  48507. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  48508. */
  48509. this.nbParticles = 0;
  48510. /**
  48511. * If the particles must ever face the camera (default false). Useful for planar particles.
  48512. */
  48513. this.billboard = false;
  48514. /**
  48515. * Recompute normals when adding a shape
  48516. */
  48517. this.recomputeNormals = true;
  48518. /**
  48519. * This a counter ofr your own usage. It's not set by any SPS functions.
  48520. */
  48521. this.counter = 0;
  48522. /**
  48523. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  48524. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  48525. */
  48526. this.vars = {};
  48527. this._positions = new Array();
  48528. this._indices = new Array();
  48529. this._normals = new Array();
  48530. this._colors = new Array();
  48531. this._uvs = new Array();
  48532. this._index = 0; // indices index
  48533. this._updatable = true;
  48534. this._pickable = false;
  48535. this._isVisibilityBoxLocked = false;
  48536. this._alwaysVisible = false;
  48537. this._shapeCounter = 0;
  48538. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  48539. this._color = new BABYLON.Color4(0, 0, 0, 0);
  48540. this._computeParticleColor = true;
  48541. this._computeParticleTexture = true;
  48542. this._computeParticleRotation = true;
  48543. this._computeParticleVertex = false;
  48544. this._computeBoundingBox = false;
  48545. this._cam_axisZ = BABYLON.Vector3.Zero();
  48546. this._cam_axisY = BABYLON.Vector3.Zero();
  48547. this._cam_axisX = BABYLON.Vector3.Zero();
  48548. this._axisX = BABYLON.Axis.X;
  48549. this._axisY = BABYLON.Axis.Y;
  48550. this._axisZ = BABYLON.Axis.Z;
  48551. this._camDir = BABYLON.Vector3.Zero();
  48552. this._rotMatrix = new BABYLON.Matrix();
  48553. this._invertMatrix = new BABYLON.Matrix();
  48554. this._rotated = BABYLON.Vector3.Zero();
  48555. this._quaternion = new BABYLON.Quaternion();
  48556. this._vertex = BABYLON.Vector3.Zero();
  48557. this._normal = BABYLON.Vector3.Zero();
  48558. this._yaw = 0.0;
  48559. this._pitch = 0.0;
  48560. this._roll = 0.0;
  48561. this._halfroll = 0.0;
  48562. this._halfpitch = 0.0;
  48563. this._halfyaw = 0.0;
  48564. this._sinRoll = 0.0;
  48565. this._cosRoll = 0.0;
  48566. this._sinPitch = 0.0;
  48567. this._cosPitch = 0.0;
  48568. this._sinYaw = 0.0;
  48569. this._cosYaw = 0.0;
  48570. this._w = 0.0;
  48571. this._minimum = BABYLON.Tmp.Vector3[0];
  48572. this._maximum = BABYLON.Tmp.Vector3[1];
  48573. this._scale = BABYLON.Tmp.Vector3[2];
  48574. this._translation = BABYLON.Tmp.Vector3[3];
  48575. this._minBbox = BABYLON.Tmp.Vector3[4];
  48576. this._maxBbox = BABYLON.Tmp.Vector3[5];
  48577. this._particlesIntersect = false;
  48578. this._bSphereOnly = false;
  48579. this._bSphereRadiusFactor = 1.0;
  48580. this.name = name;
  48581. this._scene = scene;
  48582. this._camera = scene.activeCamera;
  48583. this._pickable = options ? options.isPickable : false;
  48584. this._particlesIntersect = options ? options.particleIntersection : false;
  48585. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  48586. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  48587. if (options && options.updatable) {
  48588. this._updatable = options.updatable;
  48589. }
  48590. else {
  48591. this._updatable = true;
  48592. }
  48593. if (this._pickable) {
  48594. this.pickedParticles = [];
  48595. }
  48596. }
  48597. /**
  48598. * Builds the SPS underlying mesh. Returns a standard Mesh.
  48599. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  48600. */
  48601. SolidParticleSystem.prototype.buildMesh = function () {
  48602. if (this.nbParticles === 0) {
  48603. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  48604. this.addShape(triangle, 1);
  48605. triangle.dispose();
  48606. }
  48607. this._positions32 = new Float32Array(this._positions);
  48608. this._uvs32 = new Float32Array(this._uvs);
  48609. this._colors32 = new Float32Array(this._colors);
  48610. if (this.recomputeNormals) {
  48611. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  48612. }
  48613. this._normals32 = new Float32Array(this._normals);
  48614. this._fixedNormal32 = new Float32Array(this._normals);
  48615. var vertexData = new BABYLON.VertexData();
  48616. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  48617. vertexData.indices = this._indices;
  48618. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  48619. if (this._uvs32) {
  48620. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  48621. ;
  48622. }
  48623. if (this._colors32) {
  48624. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  48625. }
  48626. var mesh = new BABYLON.Mesh(this.name, this._scene);
  48627. vertexData.applyToMesh(mesh, this._updatable);
  48628. this.mesh = mesh;
  48629. this.mesh.isPickable = this._pickable;
  48630. // free memory
  48631. this._positions = null;
  48632. this._normals = null;
  48633. this._uvs = null;
  48634. this._colors = null;
  48635. if (!this._updatable) {
  48636. this.particles.length = 0;
  48637. }
  48638. return mesh;
  48639. };
  48640. /**
  48641. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  48642. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  48643. * Thus the particles generated from `digest()` have their property `position` set yet.
  48644. * `mesh` ( Mesh ) is the mesh to be digested
  48645. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  48646. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  48647. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  48648. */
  48649. SolidParticleSystem.prototype.digest = function (mesh, options) {
  48650. var size = (options && options.facetNb) || 1;
  48651. var number = (options && options.number);
  48652. var delta = (options && options.delta) || 0;
  48653. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48654. var meshInd = mesh.getIndices();
  48655. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48656. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48657. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48658. var f = 0; // facet counter
  48659. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  48660. // compute size from number
  48661. if (number) {
  48662. number = (number > totalFacets) ? totalFacets : number;
  48663. size = Math.round(totalFacets / number);
  48664. delta = 0;
  48665. }
  48666. else {
  48667. size = (size > totalFacets) ? totalFacets : size;
  48668. }
  48669. var facetPos = []; // submesh positions
  48670. var facetInd = []; // submesh indices
  48671. var facetUV = []; // submesh UV
  48672. var facetCol = []; // submesh colors
  48673. var barycenter = BABYLON.Tmp.Vector3[0];
  48674. var rand;
  48675. var sizeO = size;
  48676. while (f < totalFacets) {
  48677. size = sizeO + Math.floor((1 + delta) * Math.random());
  48678. if (f > totalFacets - size) {
  48679. size = totalFacets - f;
  48680. }
  48681. // reset temp arrays
  48682. facetPos.length = 0;
  48683. facetInd.length = 0;
  48684. facetUV.length = 0;
  48685. facetCol.length = 0;
  48686. // iterate over "size" facets
  48687. var fi = 0;
  48688. for (var j = f * 3; j < (f + size) * 3; j++) {
  48689. facetInd.push(fi);
  48690. var i = meshInd[j];
  48691. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  48692. if (meshUV) {
  48693. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  48694. }
  48695. if (meshCol) {
  48696. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  48697. }
  48698. fi++;
  48699. }
  48700. // create a model shape for each single particle
  48701. var idx = this.nbParticles;
  48702. var shape = this._posToShape(facetPos);
  48703. var shapeUV = this._uvsToShapeUV(facetUV);
  48704. // compute the barycenter of the shape
  48705. var v;
  48706. for (v = 0; v < shape.length; v++) {
  48707. barycenter.addInPlace(shape[v]);
  48708. }
  48709. barycenter.scaleInPlace(1 / shape.length);
  48710. // shift the shape from its barycenter to the origin
  48711. for (v = 0; v < shape.length; v++) {
  48712. shape[v].subtractInPlace(barycenter);
  48713. }
  48714. var bInfo;
  48715. if (this._particlesIntersect) {
  48716. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  48717. }
  48718. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  48719. // add the particle in the SPS
  48720. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  48721. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
  48722. // initialize the particle position
  48723. this.particles[this.nbParticles].position.addInPlace(barycenter);
  48724. this._index += shape.length;
  48725. idx++;
  48726. this.nbParticles++;
  48727. this._shapeCounter++;
  48728. f += size;
  48729. }
  48730. return this;
  48731. };
  48732. //reset copy
  48733. SolidParticleSystem.prototype._resetCopy = function () {
  48734. this._copy.position.x = 0;
  48735. this._copy.position.y = 0;
  48736. this._copy.position.z = 0;
  48737. this._copy.rotation.x = 0;
  48738. this._copy.rotation.y = 0;
  48739. this._copy.rotation.z = 0;
  48740. this._copy.rotationQuaternion = null;
  48741. this._copy.scaling.x = 1;
  48742. this._copy.scaling.y = 1;
  48743. this._copy.scaling.z = 1;
  48744. this._copy.uvs.x = 0;
  48745. this._copy.uvs.y = 0;
  48746. this._copy.uvs.z = 1;
  48747. this._copy.uvs.w = 1;
  48748. this._copy.color = null;
  48749. };
  48750. // _meshBuilder : inserts the shape model in the global SPS mesh
  48751. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  48752. var i;
  48753. var u = 0;
  48754. var c = 0;
  48755. var n = 0;
  48756. this._resetCopy();
  48757. if (options && options.positionFunction) {
  48758. options.positionFunction(this._copy, idx, idxInShape);
  48759. }
  48760. if (this._copy.rotationQuaternion) {
  48761. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  48762. }
  48763. else {
  48764. this._yaw = this._copy.rotation.y;
  48765. this._pitch = this._copy.rotation.x;
  48766. this._roll = this._copy.rotation.z;
  48767. this._quaternionRotationYPR();
  48768. }
  48769. this._quaternionToRotationMatrix();
  48770. for (i = 0; i < shape.length; i++) {
  48771. this._vertex.x = shape[i].x;
  48772. this._vertex.y = shape[i].y;
  48773. this._vertex.z = shape[i].z;
  48774. if (options && options.vertexFunction) {
  48775. options.vertexFunction(this._copy, this._vertex, i);
  48776. }
  48777. this._vertex.x *= this._copy.scaling.x;
  48778. this._vertex.y *= this._copy.scaling.y;
  48779. this._vertex.z *= this._copy.scaling.z;
  48780. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  48781. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  48782. if (meshUV) {
  48783. 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);
  48784. u += 2;
  48785. }
  48786. if (this._copy.color) {
  48787. this._color = this._copy.color;
  48788. }
  48789. else if (meshCol && meshCol[c] !== undefined) {
  48790. this._color.r = meshCol[c];
  48791. this._color.g = meshCol[c + 1];
  48792. this._color.b = meshCol[c + 2];
  48793. this._color.a = meshCol[c + 3];
  48794. }
  48795. else {
  48796. this._color.r = 1;
  48797. this._color.g = 1;
  48798. this._color.b = 1;
  48799. this._color.a = 1;
  48800. }
  48801. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  48802. c += 4;
  48803. if (!this.recomputeNormals && meshNor) {
  48804. this._normal.x = meshNor[n];
  48805. this._normal.y = meshNor[n + 1];
  48806. this._normal.z = meshNor[n + 2];
  48807. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  48808. normals.push(this._normal.x, this._normal.y, this._normal.z);
  48809. n += 3;
  48810. }
  48811. }
  48812. for (i = 0; i < meshInd.length; i++) {
  48813. indices.push(p + meshInd[i]);
  48814. }
  48815. if (this._pickable) {
  48816. var nbfaces = meshInd.length / 3;
  48817. for (i = 0; i < nbfaces; i++) {
  48818. this.pickedParticles.push({ idx: idx, faceId: i });
  48819. }
  48820. }
  48821. };
  48822. // returns a shape array from positions array
  48823. SolidParticleSystem.prototype._posToShape = function (positions) {
  48824. var shape = [];
  48825. for (var i = 0; i < positions.length; i += 3) {
  48826. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  48827. }
  48828. return shape;
  48829. };
  48830. // returns a shapeUV array from a Vector4 uvs
  48831. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  48832. var shapeUV = [];
  48833. if (uvs) {
  48834. for (var i = 0; i < uvs.length; i++)
  48835. shapeUV.push(uvs[i]);
  48836. }
  48837. return shapeUV;
  48838. };
  48839. // adds a new particle object in the particles array
  48840. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  48841. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
  48842. };
  48843. /**
  48844. * Adds some particles to the SPS from the model shape. Returns the shape id.
  48845. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  48846. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  48847. * `nb` (positive integer) the number of particles to be created from this model
  48848. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  48849. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  48850. */
  48851. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  48852. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48853. var meshInd = mesh.getIndices();
  48854. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48855. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48856. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48857. var bbInfo;
  48858. if (this._particlesIntersect) {
  48859. bbInfo = mesh.getBoundingInfo();
  48860. }
  48861. var shape = this._posToShape(meshPos);
  48862. var shapeUV = this._uvsToShapeUV(meshUV);
  48863. var posfunc = options ? options.positionFunction : null;
  48864. var vtxfunc = options ? options.vertexFunction : null;
  48865. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  48866. // particles
  48867. var idx = this.nbParticles;
  48868. for (var i = 0; i < nb; i++) {
  48869. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  48870. if (this._updatable) {
  48871. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  48872. }
  48873. this._index += shape.length;
  48874. idx++;
  48875. }
  48876. this.nbParticles += nb;
  48877. this._shapeCounter++;
  48878. return this._shapeCounter - 1;
  48879. };
  48880. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  48881. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  48882. this._resetCopy();
  48883. if (particle._model._positionFunction) {
  48884. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  48885. }
  48886. if (this._copy.rotationQuaternion) {
  48887. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  48888. }
  48889. else {
  48890. this._yaw = this._copy.rotation.y;
  48891. this._pitch = this._copy.rotation.x;
  48892. this._roll = this._copy.rotation.z;
  48893. this._quaternionRotationYPR();
  48894. }
  48895. this._quaternionToRotationMatrix();
  48896. this._shape = particle._model._shape;
  48897. for (var pt = 0; pt < this._shape.length; pt++) {
  48898. this._vertex.x = this._shape[pt].x;
  48899. this._vertex.y = this._shape[pt].y;
  48900. this._vertex.z = this._shape[pt].z;
  48901. if (particle._model._vertexFunction) {
  48902. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  48903. }
  48904. this._vertex.x *= this._copy.scaling.x;
  48905. this._vertex.y *= this._copy.scaling.y;
  48906. this._vertex.z *= this._copy.scaling.z;
  48907. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  48908. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  48909. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  48910. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  48911. }
  48912. particle.position.x = 0.0;
  48913. particle.position.y = 0.0;
  48914. particle.position.z = 0.0;
  48915. particle.rotation.x = 0.0;
  48916. particle.rotation.y = 0.0;
  48917. particle.rotation.z = 0.0;
  48918. particle.rotationQuaternion = null;
  48919. particle.scaling.x = 1.0;
  48920. particle.scaling.y = 1.0;
  48921. particle.scaling.z = 1.0;
  48922. };
  48923. /**
  48924. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  48925. */
  48926. SolidParticleSystem.prototype.rebuildMesh = function () {
  48927. for (var p = 0; p < this.particles.length; p++) {
  48928. this._rebuildParticle(this.particles[p]);
  48929. }
  48930. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  48931. };
  48932. /**
  48933. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  48934. * This method calls `updateParticle()` for each particle of the SPS.
  48935. * For an animated SPS, it is usually called within the render loop.
  48936. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  48937. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  48938. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  48939. */
  48940. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  48941. if (start === void 0) { start = 0; }
  48942. if (end === void 0) { end = this.nbParticles - 1; }
  48943. if (update === void 0) { update = true; }
  48944. if (!this._updatable) {
  48945. return;
  48946. }
  48947. // custom beforeUpdate
  48948. this.beforeUpdateParticles(start, end, update);
  48949. this._cam_axisX.x = 1.0;
  48950. this._cam_axisX.y = 0.0;
  48951. this._cam_axisX.z = 0.0;
  48952. this._cam_axisY.x = 0.0;
  48953. this._cam_axisY.y = 1.0;
  48954. this._cam_axisY.z = 0.0;
  48955. this._cam_axisZ.x = 0.0;
  48956. this._cam_axisZ.y = 0.0;
  48957. this._cam_axisZ.z = 1.0;
  48958. // if the particles will always face the camera
  48959. if (this.billboard) {
  48960. // compute the camera position and un-rotate it by the current mesh rotation
  48961. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  48962. this._quaternionToRotationMatrix();
  48963. this._rotMatrix.invertToRef(this._invertMatrix);
  48964. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  48965. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  48966. this._cam_axisZ.normalize();
  48967. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  48968. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  48969. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  48970. this._cam_axisY.normalize();
  48971. this._cam_axisX.normalize();
  48972. }
  48973. }
  48974. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  48975. var idx = 0;
  48976. var index = 0;
  48977. var colidx = 0;
  48978. var colorIndex = 0;
  48979. var uvidx = 0;
  48980. var uvIndex = 0;
  48981. var pt = 0;
  48982. if (this._computeBoundingBox) {
  48983. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  48984. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  48985. }
  48986. // particle loop
  48987. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  48988. for (var p = start; p <= end; p++) {
  48989. this._particle = this.particles[p];
  48990. this._shape = this._particle._model._shape;
  48991. this._shapeUV = this._particle._model._shapeUV;
  48992. // call to custom user function to update the particle properties
  48993. this.updateParticle(this._particle);
  48994. if (this._particle.isVisible) {
  48995. // particle rotation matrix
  48996. if (this.billboard) {
  48997. this._particle.rotation.x = 0.0;
  48998. this._particle.rotation.y = 0.0;
  48999. }
  49000. if (this._computeParticleRotation || this.billboard) {
  49001. if (this._particle.rotationQuaternion) {
  49002. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49003. }
  49004. else {
  49005. this._yaw = this._particle.rotation.y;
  49006. this._pitch = this._particle.rotation.x;
  49007. this._roll = this._particle.rotation.z;
  49008. this._quaternionRotationYPR();
  49009. }
  49010. this._quaternionToRotationMatrix();
  49011. }
  49012. // particle vertex loop
  49013. for (pt = 0; pt < this._shape.length; pt++) {
  49014. idx = index + pt * 3;
  49015. colidx = colorIndex + pt * 4;
  49016. uvidx = uvIndex + pt * 2;
  49017. this._vertex.x = this._shape[pt].x;
  49018. this._vertex.y = this._shape[pt].y;
  49019. this._vertex.z = this._shape[pt].z;
  49020. if (this._computeParticleVertex) {
  49021. this.updateParticleVertex(this._particle, this._vertex, pt);
  49022. }
  49023. // positions
  49024. this._vertex.x *= this._particle.scaling.x;
  49025. this._vertex.y *= this._particle.scaling.y;
  49026. this._vertex.z *= this._particle.scaling.z;
  49027. 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];
  49028. 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;
  49029. 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;
  49030. 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;
  49031. 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;
  49032. 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;
  49033. 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;
  49034. if (this._computeBoundingBox) {
  49035. if (this._positions32[idx] < this._minimum.x) {
  49036. this._minimum.x = this._positions32[idx];
  49037. }
  49038. if (this._positions32[idx] > this._maximum.x) {
  49039. this._maximum.x = this._positions32[idx];
  49040. }
  49041. if (this._positions32[idx + 1] < this._minimum.y) {
  49042. this._minimum.y = this._positions32[idx + 1];
  49043. }
  49044. if (this._positions32[idx + 1] > this._maximum.y) {
  49045. this._maximum.y = this._positions32[idx + 1];
  49046. }
  49047. if (this._positions32[idx + 2] < this._minimum.z) {
  49048. this._minimum.z = this._positions32[idx + 2];
  49049. }
  49050. if (this._positions32[idx + 2] > this._maximum.z) {
  49051. this._maximum.z = this._positions32[idx + 2];
  49052. }
  49053. }
  49054. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  49055. if (!this._computeParticleVertex) {
  49056. this._normal.x = this._fixedNormal32[idx];
  49057. this._normal.y = this._fixedNormal32[idx + 1];
  49058. this._normal.z = this._fixedNormal32[idx + 2];
  49059. this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  49060. 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]) / this._w;
  49061. 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]) / this._w;
  49062. 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]) / this._w;
  49063. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49064. 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;
  49065. 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;
  49066. }
  49067. if (this._computeParticleColor) {
  49068. this._colors32[colidx] = this._particle.color.r;
  49069. this._colors32[colidx + 1] = this._particle.color.g;
  49070. this._colors32[colidx + 2] = this._particle.color.b;
  49071. this._colors32[colidx + 3] = this._particle.color.a;
  49072. }
  49073. if (this._computeParticleTexture) {
  49074. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49075. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49076. }
  49077. }
  49078. }
  49079. else {
  49080. for (pt = 0; pt < this._shape.length; pt++) {
  49081. idx = index + pt * 3;
  49082. colidx = colorIndex + pt * 4;
  49083. uvidx = uvIndex + pt * 2;
  49084. this._positions32[idx] = this._camera.position.x;
  49085. this._positions32[idx + 1] = this._camera.position.y;
  49086. this._positions32[idx + 2] = this._camera.position.z;
  49087. this._normals32[idx] = 0.0;
  49088. this._normals32[idx + 1] = 0.0;
  49089. this._normals32[idx + 2] = 0.0;
  49090. if (this._computeParticleColor) {
  49091. this._colors32[colidx] = this._particle.color.r;
  49092. this._colors32[colidx + 1] = this._particle.color.g;
  49093. this._colors32[colidx + 2] = this._particle.color.b;
  49094. this._colors32[colidx + 3] = this._particle.color.a;
  49095. }
  49096. if (this._computeParticleTexture) {
  49097. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49098. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49099. }
  49100. }
  49101. }
  49102. // if the particle intersections must be computed : update the bbInfo
  49103. if (this._particlesIntersect) {
  49104. var bInfo = this._particle._boundingInfo;
  49105. var bBox = bInfo.boundingBox;
  49106. var bSphere = bInfo.boundingSphere;
  49107. if (!this._bSphereOnly) {
  49108. // place, scale and rotate the particle bbox within the SPS local system, then update it
  49109. for (var b = 0; b < bBox.vectors.length; b++) {
  49110. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  49111. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  49112. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  49113. 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];
  49114. 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;
  49115. 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;
  49116. 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;
  49117. 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;
  49118. 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;
  49119. 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;
  49120. }
  49121. bBox._update(this.mesh._worldMatrix);
  49122. }
  49123. // place and scale the particle bouding sphere in the SPS local system, then update it
  49124. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  49125. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  49126. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  49127. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  49128. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  49129. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  49130. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  49131. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  49132. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  49133. 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));
  49134. bSphere._update(this.mesh._worldMatrix);
  49135. }
  49136. // increment indexes for the next particle
  49137. index = idx + 3;
  49138. colorIndex = colidx + 4;
  49139. uvIndex = uvidx + 2;
  49140. }
  49141. // if the VBO must be updated
  49142. if (update) {
  49143. if (this._computeParticleColor) {
  49144. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  49145. }
  49146. if (this._computeParticleTexture) {
  49147. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  49148. }
  49149. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49150. if (!this.mesh.areNormalsFrozen) {
  49151. if (this._computeParticleVertex) {
  49152. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  49153. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  49154. for (var i = 0; i < this._normals32.length; i++) {
  49155. this._fixedNormal32[i] = this._normals32[i];
  49156. }
  49157. }
  49158. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  49159. }
  49160. }
  49161. if (this._computeBoundingBox) {
  49162. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  49163. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  49164. }
  49165. this.afterUpdateParticles(start, end, update);
  49166. };
  49167. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  49168. this._halfroll = this._roll * 0.5;
  49169. this._halfpitch = this._pitch * 0.5;
  49170. this._halfyaw = this._yaw * 0.5;
  49171. this._sinRoll = Math.sin(this._halfroll);
  49172. this._cosRoll = Math.cos(this._halfroll);
  49173. this._sinPitch = Math.sin(this._halfpitch);
  49174. this._cosPitch = Math.cos(this._halfpitch);
  49175. this._sinYaw = Math.sin(this._halfyaw);
  49176. this._cosYaw = Math.cos(this._halfyaw);
  49177. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  49178. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  49179. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  49180. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  49181. };
  49182. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  49183. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  49184. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  49185. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  49186. this._rotMatrix.m[3] = 0;
  49187. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  49188. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  49189. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  49190. this._rotMatrix.m[7] = 0;
  49191. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  49192. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  49193. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  49194. this._rotMatrix.m[11] = 0;
  49195. this._rotMatrix.m[12] = 0;
  49196. this._rotMatrix.m[13] = 0;
  49197. this._rotMatrix.m[14] = 0;
  49198. this._rotMatrix.m[15] = 1.0;
  49199. };
  49200. /**
  49201. * Disposes the SPS
  49202. */
  49203. SolidParticleSystem.prototype.dispose = function () {
  49204. this.mesh.dispose();
  49205. this.vars = null;
  49206. // drop references to internal big arrays for the GC
  49207. this._positions = null;
  49208. this._indices = null;
  49209. this._normals = null;
  49210. this._uvs = null;
  49211. this._colors = null;
  49212. this._positions32 = null;
  49213. this._normals32 = null;
  49214. this._fixedNormal32 = null;
  49215. this._uvs32 = null;
  49216. this._colors32 = null;
  49217. this.pickedParticles = null;
  49218. };
  49219. /**
  49220. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  49221. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49222. */
  49223. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  49224. if (!this._isVisibilityBoxLocked) {
  49225. this.mesh.refreshBoundingInfo();
  49226. }
  49227. };
  49228. /**
  49229. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  49230. * @param size the size (float) of the visibility box
  49231. * note : this doesn't lock the SPS mesh bounding box.
  49232. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49233. */
  49234. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  49235. var vis = size / 2;
  49236. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  49237. };
  49238. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  49239. // getter and setter
  49240. get: function () {
  49241. return this._alwaysVisible;
  49242. },
  49243. /**
  49244. * Sets the SPS as always visible or not
  49245. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49246. */
  49247. set: function (val) {
  49248. this._alwaysVisible = val;
  49249. this.mesh.alwaysSelectAsActiveMesh = val;
  49250. },
  49251. enumerable: true,
  49252. configurable: true
  49253. });
  49254. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  49255. get: function () {
  49256. return this._isVisibilityBoxLocked;
  49257. },
  49258. /**
  49259. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49260. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49261. */
  49262. set: function (val) {
  49263. this._isVisibilityBoxLocked = val;
  49264. this.mesh.getBoundingInfo().isLocked = val;
  49265. },
  49266. enumerable: true,
  49267. configurable: true
  49268. });
  49269. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  49270. // getters
  49271. get: function () {
  49272. return this._computeParticleRotation;
  49273. },
  49274. // Optimizer setters
  49275. /**
  49276. * Tells to `setParticles()` to compute the particle rotations or not.
  49277. * Default value : true. The SPS is faster when it's set to false.
  49278. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49279. */
  49280. set: function (val) {
  49281. this._computeParticleRotation = val;
  49282. },
  49283. enumerable: true,
  49284. configurable: true
  49285. });
  49286. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  49287. get: function () {
  49288. return this._computeParticleColor;
  49289. },
  49290. /**
  49291. * Tells to `setParticles()` to compute the particle colors or not.
  49292. * Default value : true. The SPS is faster when it's set to false.
  49293. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49294. */
  49295. set: function (val) {
  49296. this._computeParticleColor = val;
  49297. },
  49298. enumerable: true,
  49299. configurable: true
  49300. });
  49301. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  49302. get: function () {
  49303. return this._computeParticleTexture;
  49304. },
  49305. /**
  49306. * Tells to `setParticles()` to compute the particle textures or not.
  49307. * Default value : true. The SPS is faster when it's set to false.
  49308. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  49309. */
  49310. set: function (val) {
  49311. this._computeParticleTexture = val;
  49312. },
  49313. enumerable: true,
  49314. configurable: true
  49315. });
  49316. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  49317. get: function () {
  49318. return this._computeParticleVertex;
  49319. },
  49320. /**
  49321. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  49322. * Default value : false. The SPS is faster when it's set to false.
  49323. * Note : the particle custom vertex positions aren't stored values.
  49324. */
  49325. set: function (val) {
  49326. this._computeParticleVertex = val;
  49327. },
  49328. enumerable: true,
  49329. configurable: true
  49330. });
  49331. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  49332. get: function () {
  49333. return this._computeBoundingBox;
  49334. },
  49335. /**
  49336. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  49337. */
  49338. set: function (val) {
  49339. this._computeBoundingBox = val;
  49340. },
  49341. enumerable: true,
  49342. configurable: true
  49343. });
  49344. // =======================================================================
  49345. // Particle behavior logic
  49346. // these following methods may be overwritten by the user to fit his needs
  49347. /**
  49348. * This function does nothing. It may be overwritten to set all the particle first values.
  49349. * The SPS doesn't call this function, you may have to call it by your own.
  49350. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49351. */
  49352. SolidParticleSystem.prototype.initParticles = function () {
  49353. };
  49354. /**
  49355. * This function does nothing. It may be overwritten to recycle a particle.
  49356. * The SPS doesn't call this function, you may have to call it by your own.
  49357. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49358. */
  49359. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  49360. return particle;
  49361. };
  49362. /**
  49363. * Updates a particle : this function should be overwritten by the user.
  49364. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  49365. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49366. * ex : just set a particle position or velocity and recycle conditions
  49367. */
  49368. SolidParticleSystem.prototype.updateParticle = function (particle) {
  49369. return particle;
  49370. };
  49371. /**
  49372. * Updates a vertex of a particle : it can be overwritten by the user.
  49373. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  49374. * @param particle the current particle
  49375. * @param vertex the current index of the current particle
  49376. * @param pt the index of the current vertex in the particle shape
  49377. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  49378. * ex : just set a vertex particle position
  49379. */
  49380. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  49381. return vertex;
  49382. };
  49383. /**
  49384. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  49385. * This does nothing and may be overwritten by the user.
  49386. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49387. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49388. * @param update the boolean update value actually passed to setParticles()
  49389. */
  49390. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  49391. };
  49392. /**
  49393. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  49394. * This will be passed three parameters.
  49395. * This does nothing and may be overwritten by the user.
  49396. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49397. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49398. * @param update the boolean update value actually passed to setParticles()
  49399. */
  49400. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  49401. };
  49402. return SolidParticleSystem;
  49403. }());
  49404. BABYLON.SolidParticleSystem = SolidParticleSystem;
  49405. })(BABYLON || (BABYLON = {}));
  49406. //# sourceMappingURL=../Particles/babylon.solidParticleSystem.js.map
  49407. var BABYLON;
  49408. (function (BABYLON) {
  49409. var Internals;
  49410. (function (Internals) {
  49411. var FileFaceOrientation = (function () {
  49412. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  49413. this.name = name;
  49414. this.worldAxisForNormal = worldAxisForNormal;
  49415. this.worldAxisForFileX = worldAxisForFileX;
  49416. this.worldAxisForFileY = worldAxisForFileY;
  49417. }
  49418. return FileFaceOrientation;
  49419. }());
  49420. ;
  49421. /**
  49422. * Helper class dealing with the extraction of spherical polynomial dataArray
  49423. * from a cube map.
  49424. */
  49425. var CubeMapToSphericalPolynomialTools = (function () {
  49426. function CubeMapToSphericalPolynomialTools() {
  49427. }
  49428. /**
  49429. * Converts a cubemap to the according Spherical Polynomial data.
  49430. * This extracts the first 3 orders only as they are the only one used in the lighting.
  49431. *
  49432. * @param cubeInfo The Cube map to extract the information from.
  49433. * @return The Spherical Polynomial data.
  49434. */
  49435. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  49436. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  49437. var totalSolidAngle = 0.0;
  49438. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  49439. var du = 2.0 / cubeInfo.size;
  49440. var dv = du;
  49441. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  49442. var minUV = du * 0.5 - 1.0;
  49443. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  49444. var fileFace = this.FileFaces[faceIndex];
  49445. var dataArray = cubeInfo[fileFace.name];
  49446. var v = minUV;
  49447. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  49448. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  49449. // Because SP is still linear, so summation is fine in that basis.
  49450. for (var y = 0; y < cubeInfo.size; y++) {
  49451. var u = minUV;
  49452. for (var x = 0; x < cubeInfo.size; x++) {
  49453. // World direction (not normalised)
  49454. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  49455. worldDirection.normalize();
  49456. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  49457. if (1) {
  49458. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  49459. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  49460. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  49461. var color = new BABYLON.Color3(r, g, b);
  49462. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  49463. }
  49464. else {
  49465. if (faceIndex == 0) {
  49466. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49467. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49468. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49469. }
  49470. else if (faceIndex == 1) {
  49471. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49472. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49473. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49474. }
  49475. else if (faceIndex == 2) {
  49476. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49477. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49478. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49479. }
  49480. else if (faceIndex == 3) {
  49481. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49482. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49483. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  49484. }
  49485. else if (faceIndex == 4) {
  49486. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  49487. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  49488. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49489. }
  49490. else if (faceIndex == 5) {
  49491. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  49492. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  49493. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  49494. }
  49495. 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]);
  49496. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  49497. }
  49498. totalSolidAngle += deltaSolidAngle;
  49499. u += du;
  49500. }
  49501. v += dv;
  49502. }
  49503. }
  49504. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  49505. var correction = correctSolidAngle / totalSolidAngle;
  49506. sphericalHarmonics.scale(correction);
  49507. // Additionally scale by pi -- audit needed
  49508. sphericalHarmonics.scale(1.0 / Math.PI);
  49509. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  49510. };
  49511. CubeMapToSphericalPolynomialTools.FileFaces = [
  49512. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  49513. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  49514. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  49515. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  49516. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  49517. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  49518. ];
  49519. return CubeMapToSphericalPolynomialTools;
  49520. }());
  49521. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  49522. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49523. })(BABYLON || (BABYLON = {}));
  49524. //# sourceMappingURL=../../Tools/HDR/babylon.tools.cubemapToSphericalPolynomial.js.map
  49525. var BABYLON;
  49526. (function (BABYLON) {
  49527. var Internals;
  49528. (function (Internals) {
  49529. /**
  49530. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  49531. */
  49532. var PanoramaToCubeMapTools = (function () {
  49533. function PanoramaToCubeMapTools() {
  49534. }
  49535. /**
  49536. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  49537. *
  49538. * @param float32Array The source data.
  49539. * @param inputWidth The width of the input panorama.
  49540. * @param inputhHeight The height of the input panorama.
  49541. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  49542. * @return The cubemap data
  49543. */
  49544. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  49545. if (!float32Array) {
  49546. throw "ConvertPanoramaToCubemap: input cannot be null";
  49547. }
  49548. if (float32Array.length != inputWidth * inputHeight * 3) {
  49549. throw "ConvertPanoramaToCubemap: input size is wrong";
  49550. }
  49551. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  49552. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  49553. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  49554. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  49555. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  49556. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  49557. return {
  49558. front: textureFront,
  49559. back: textureBack,
  49560. left: textureLeft,
  49561. right: textureRight,
  49562. up: textureUp,
  49563. down: textureDown,
  49564. size: size
  49565. };
  49566. };
  49567. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  49568. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  49569. var textureArray = new Float32Array(buffer);
  49570. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  49571. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  49572. var dy = 1 / texSize;
  49573. var fy = 0;
  49574. for (var y = 0; y < texSize; y++) {
  49575. var xv1 = faceData[0];
  49576. var xv2 = faceData[2];
  49577. for (var x = 0; x < texSize; x++) {
  49578. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  49579. v.normalize();
  49580. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  49581. // 3 channels per pixels
  49582. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  49583. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  49584. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  49585. xv1 = xv1.add(rotDX1);
  49586. xv2 = xv2.add(rotDX2);
  49587. }
  49588. fy += dy;
  49589. }
  49590. return textureArray;
  49591. };
  49592. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  49593. var theta = Math.atan2(vDir.z, vDir.x);
  49594. var phi = Math.acos(vDir.y);
  49595. while (theta < -Math.PI)
  49596. theta += 2 * Math.PI;
  49597. while (theta > Math.PI)
  49598. theta -= 2 * Math.PI;
  49599. var dx = theta / Math.PI;
  49600. var dy = phi / Math.PI;
  49601. // recenter.
  49602. dx = dx * 0.5 + 0.5;
  49603. var px = Math.round(dx * inputWidth);
  49604. if (px < 0)
  49605. px = 0;
  49606. else if (px >= inputWidth)
  49607. px = inputWidth - 1;
  49608. var py = Math.round(dy * inputHeight);
  49609. if (py < 0)
  49610. py = 0;
  49611. else if (py >= inputHeight)
  49612. py = inputHeight - 1;
  49613. var inputY = (inputHeight - py - 1);
  49614. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  49615. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  49616. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  49617. return {
  49618. r: r,
  49619. g: g,
  49620. b: b
  49621. };
  49622. };
  49623. PanoramaToCubeMapTools.FACE_FRONT = [
  49624. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  49625. new BABYLON.Vector3(1.0, -1.0, -1.0),
  49626. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  49627. new BABYLON.Vector3(1.0, 1.0, -1.0)
  49628. ];
  49629. PanoramaToCubeMapTools.FACE_BACK = [
  49630. new BABYLON.Vector3(1.0, -1.0, 1.0),
  49631. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  49632. new BABYLON.Vector3(1.0, 1.0, 1.0),
  49633. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  49634. ];
  49635. PanoramaToCubeMapTools.FACE_RIGHT = [
  49636. new BABYLON.Vector3(1.0, -1.0, -1.0),
  49637. new BABYLON.Vector3(1.0, -1.0, 1.0),
  49638. new BABYLON.Vector3(1.0, 1.0, -1.0),
  49639. new BABYLON.Vector3(1.0, 1.0, 1.0)
  49640. ];
  49641. PanoramaToCubeMapTools.FACE_LEFT = [
  49642. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  49643. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  49644. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  49645. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  49646. ];
  49647. PanoramaToCubeMapTools.FACE_DOWN = [
  49648. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  49649. new BABYLON.Vector3(1.0, 1.0, -1.0),
  49650. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  49651. new BABYLON.Vector3(1.0, 1.0, 1.0)
  49652. ];
  49653. PanoramaToCubeMapTools.FACE_UP = [
  49654. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  49655. new BABYLON.Vector3(1.0, -1.0, 1.0),
  49656. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  49657. new BABYLON.Vector3(1.0, -1.0, -1.0)
  49658. ];
  49659. return PanoramaToCubeMapTools;
  49660. }());
  49661. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  49662. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49663. })(BABYLON || (BABYLON = {}));
  49664. //# sourceMappingURL=../../Tools/HDR/babylon.tools.panoramaToCubemap.js.map
  49665. var BABYLON;
  49666. (function (BABYLON) {
  49667. var Internals;
  49668. (function (Internals) {
  49669. ;
  49670. /**
  49671. * This groups tools to convert HDR texture to native colors array.
  49672. */
  49673. var HDRTools = (function () {
  49674. function HDRTools() {
  49675. }
  49676. HDRTools.Ldexp = function (mantissa, exponent) {
  49677. if (exponent > 1023) {
  49678. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  49679. }
  49680. if (exponent < -1074) {
  49681. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  49682. }
  49683. return mantissa * Math.pow(2, exponent);
  49684. };
  49685. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  49686. if (exponent > 0) {
  49687. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  49688. float32array[index + 0] = red * exponent;
  49689. float32array[index + 1] = green * exponent;
  49690. float32array[index + 2] = blue * exponent;
  49691. }
  49692. else {
  49693. float32array[index + 0] = 0;
  49694. float32array[index + 1] = 0;
  49695. float32array[index + 2] = 0;
  49696. }
  49697. };
  49698. HDRTools.readStringLine = function (uint8array, startIndex) {
  49699. var line = "";
  49700. var character = "";
  49701. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  49702. character = String.fromCharCode(uint8array[i]);
  49703. if (character == "\n") {
  49704. break;
  49705. }
  49706. line += character;
  49707. }
  49708. return line;
  49709. };
  49710. /**
  49711. * Reads header information from an RGBE texture stored in a native array.
  49712. * More information on this format are available here:
  49713. * https://en.wikipedia.org/wiki/RGBE_image_format
  49714. *
  49715. * @param uint8array The binary file stored in native array.
  49716. * @return The header information.
  49717. */
  49718. HDRTools.RGBE_ReadHeader = function (uint8array) {
  49719. var height = 0;
  49720. var width = 0;
  49721. var line = this.readStringLine(uint8array, 0);
  49722. if (line[0] != '#' || line[1] != '?') {
  49723. throw "Bad HDR Format.";
  49724. }
  49725. var endOfHeader = false;
  49726. var findFormat = false;
  49727. var lineIndex = 0;
  49728. do {
  49729. lineIndex += (line.length + 1);
  49730. line = this.readStringLine(uint8array, lineIndex);
  49731. if (line == "FORMAT=32-bit_rle_rgbe") {
  49732. findFormat = true;
  49733. }
  49734. else if (line.length == 0) {
  49735. endOfHeader = true;
  49736. }
  49737. } while (!endOfHeader);
  49738. if (!findFormat) {
  49739. throw "HDR Bad header format, unsupported FORMAT";
  49740. }
  49741. lineIndex += (line.length + 1);
  49742. line = this.readStringLine(uint8array, lineIndex);
  49743. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  49744. var match = sizeRegexp.exec(line);
  49745. // TODO. Support +Y and -X if needed.
  49746. if (match.length < 3) {
  49747. throw "HDR Bad header format, no size";
  49748. }
  49749. width = parseInt(match[2]);
  49750. height = parseInt(match[1]);
  49751. if (width < 8 || width > 0x7fff) {
  49752. throw "HDR Bad header format, unsupported size";
  49753. }
  49754. lineIndex += (line.length + 1);
  49755. return {
  49756. height: height,
  49757. width: width,
  49758. dataPosition: lineIndex
  49759. };
  49760. };
  49761. /**
  49762. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  49763. * This RGBE texture needs to store the information as a panorama.
  49764. *
  49765. * More information on this format are available here:
  49766. * https://en.wikipedia.org/wiki/RGBE_image_format
  49767. *
  49768. * @param buffer The binary file stored in an array buffer.
  49769. * @param size The expected size of the extracted cubemap.
  49770. * @return The Cube Map information.
  49771. */
  49772. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  49773. var uint8array = new Uint8Array(buffer);
  49774. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  49775. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  49776. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  49777. return cubeMapData;
  49778. };
  49779. /**
  49780. * Returns the pixels data extracted from an RGBE texture.
  49781. * This pixels will be stored left to right up to down in the R G B order in one array.
  49782. *
  49783. * More information on this format are available here:
  49784. * https://en.wikipedia.org/wiki/RGBE_image_format
  49785. *
  49786. * @param uint8array The binary file stored in an array buffer.
  49787. * @param hdrInfo The header information of the file.
  49788. * @return The pixels data in RGB right to left up to down order.
  49789. */
  49790. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  49791. // Keep for multi format supports.
  49792. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  49793. };
  49794. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  49795. var num_scanlines = hdrInfo.height;
  49796. var scanline_width = hdrInfo.width;
  49797. var a, b, c, d, count;
  49798. var dataIndex = hdrInfo.dataPosition;
  49799. var index = 0, endIndex = 0, i = 0;
  49800. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  49801. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  49802. // 3 channels of 4 bytes per pixel in float.
  49803. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  49804. var resultArray = new Float32Array(resultBuffer);
  49805. // read in each successive scanline
  49806. while (num_scanlines > 0) {
  49807. a = uint8array[dataIndex++];
  49808. b = uint8array[dataIndex++];
  49809. c = uint8array[dataIndex++];
  49810. d = uint8array[dataIndex++];
  49811. if (a != 2 || b != 2 || (c & 0x80)) {
  49812. // this file is not run length encoded
  49813. throw "HDR Bad header format, not RLE";
  49814. }
  49815. if (((c << 8) | d) != scanline_width) {
  49816. throw "HDR Bad header format, wrong scan line width";
  49817. }
  49818. index = 0;
  49819. // read each of the four channels for the scanline into the buffer
  49820. for (i = 0; i < 4; i++) {
  49821. endIndex = (i + 1) * scanline_width;
  49822. while (index < endIndex) {
  49823. a = uint8array[dataIndex++];
  49824. b = uint8array[dataIndex++];
  49825. if (a > 128) {
  49826. // a run of the same value
  49827. count = a - 128;
  49828. if ((count == 0) || (count > endIndex - index)) {
  49829. throw "HDR Bad Format, bad scanline data (run)";
  49830. }
  49831. while (count-- > 0) {
  49832. scanLineArray[index++] = b;
  49833. }
  49834. }
  49835. else {
  49836. // a non-run
  49837. count = a;
  49838. if ((count == 0) || (count > endIndex - index)) {
  49839. throw "HDR Bad Format, bad scanline data (non-run)";
  49840. }
  49841. scanLineArray[index++] = b;
  49842. if (--count > 0) {
  49843. for (var j = 0; j < count; j++) {
  49844. scanLineArray[index++] = uint8array[dataIndex++];
  49845. }
  49846. }
  49847. }
  49848. }
  49849. }
  49850. // now convert data from buffer into floats
  49851. for (i = 0; i < scanline_width; i++) {
  49852. a = scanLineArray[i];
  49853. b = scanLineArray[i + scanline_width];
  49854. c = scanLineArray[i + 2 * scanline_width];
  49855. d = scanLineArray[i + 3 * scanline_width];
  49856. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  49857. }
  49858. num_scanlines--;
  49859. }
  49860. return resultArray;
  49861. };
  49862. return HDRTools;
  49863. }());
  49864. Internals.HDRTools = HDRTools;
  49865. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49866. })(BABYLON || (BABYLON = {}));
  49867. //# sourceMappingURL=../../Tools/HDR/babylon.tools.hdr.js.map
  49868. //_______________________________________________________________
  49869. // Extracted from CubeMapGen:
  49870. // https://code.google.com/archive/p/cubemapgen/
  49871. //
  49872. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  49873. //_______________________________________________________________
  49874. var BABYLON;
  49875. (function (BABYLON) {
  49876. var Internals;
  49877. (function (Internals) {
  49878. /**
  49879. * The bounding box information used during the conversion process.
  49880. */
  49881. var CMGBoundinBox = (function () {
  49882. function CMGBoundinBox() {
  49883. this.min = new BABYLON.Vector3(0, 0, 0);
  49884. this.max = new BABYLON.Vector3(0, 0, 0);
  49885. this.clear();
  49886. }
  49887. CMGBoundinBox.prototype.clear = function () {
  49888. this.min.x = CMGBoundinBox.MAX;
  49889. this.min.y = CMGBoundinBox.MAX;
  49890. this.min.z = CMGBoundinBox.MAX;
  49891. this.max.x = CMGBoundinBox.MIN;
  49892. this.max.y = CMGBoundinBox.MIN;
  49893. this.max.z = CMGBoundinBox.MIN;
  49894. };
  49895. CMGBoundinBox.prototype.augment = function (x, y, z) {
  49896. this.min.x = Math.min(this.min.x, x);
  49897. this.min.y = Math.min(this.min.y, y);
  49898. this.min.z = Math.min(this.min.z, z);
  49899. this.max.x = Math.max(this.max.x, x);
  49900. this.max.y = Math.max(this.max.y, y);
  49901. this.max.z = Math.max(this.max.z, z);
  49902. };
  49903. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  49904. this.min.x = Math.max(this.min.x, x);
  49905. this.min.y = Math.max(this.min.y, y);
  49906. this.min.z = Math.max(this.min.z, z);
  49907. };
  49908. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  49909. this.max.x = Math.min(this.max.x, x);
  49910. this.max.y = Math.min(this.max.y, y);
  49911. this.max.z = Math.min(this.max.z, z);
  49912. };
  49913. CMGBoundinBox.prototype.empty = function () {
  49914. if ((this.min.x > this.max.y) ||
  49915. (this.min.y > this.max.y) ||
  49916. (this.min.z > this.max.y)) {
  49917. return true;
  49918. }
  49919. else {
  49920. return false;
  49921. }
  49922. };
  49923. CMGBoundinBox.MAX = Number.MAX_VALUE;
  49924. CMGBoundinBox.MIN = Number.MIN_VALUE;
  49925. return CMGBoundinBox;
  49926. }());
  49927. /**
  49928. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  49929. * required by the glossinees of a material.
  49930. *
  49931. * This only supports the cosine drop power as well as Warp fixup generation method.
  49932. *
  49933. * This is using the process from CubeMapGen described here:
  49934. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  49935. */
  49936. var PMREMGenerator = (function () {
  49937. /**
  49938. * Constructor of the generator.
  49939. *
  49940. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  49941. * @param inputSize The size of the cubemap faces
  49942. * @param outputSize The size of the output cubemap faces
  49943. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  49944. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  49945. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  49946. * @param specularPower The max specular level of the desired cubemap
  49947. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  49948. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  49949. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  49950. */
  49951. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  49952. this.input = input;
  49953. this.inputSize = inputSize;
  49954. this.outputSize = outputSize;
  49955. this.maxNumMipLevels = maxNumMipLevels;
  49956. this.numChannels = numChannels;
  49957. this.isFloat = isFloat;
  49958. this.specularPower = specularPower;
  49959. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  49960. this.excludeBase = excludeBase;
  49961. this.fixup = fixup;
  49962. this._outputSurface = [];
  49963. this._numMipLevels = 0;
  49964. }
  49965. /**
  49966. * Launches the filter process and return the result.
  49967. *
  49968. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  49969. */
  49970. PMREMGenerator.prototype.filterCubeMap = function () {
  49971. // Init cubemap processor
  49972. this.init();
  49973. // Filters the cubemap
  49974. this.filterCubeMapMipChain();
  49975. // Returns the filtered mips.
  49976. return this._outputSurface;
  49977. };
  49978. PMREMGenerator.prototype.init = function () {
  49979. var i;
  49980. var j;
  49981. var mipLevelSize;
  49982. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  49983. if (this.maxNumMipLevels == 0) {
  49984. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  49985. }
  49986. //first miplevel size
  49987. mipLevelSize = this.outputSize;
  49988. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  49989. for (j = 0; j < this.maxNumMipLevels; j++) {
  49990. this._outputSurface.length++;
  49991. this._outputSurface[j] = [];
  49992. //Iterate over faces for output images
  49993. for (i = 0; i < 6; i++) {
  49994. this._outputSurface[j].length++;
  49995. // Initializes a new array for the output.
  49996. if (this.isFloat) {
  49997. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  49998. }
  49999. else {
  50000. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50001. }
  50002. }
  50003. //next mip level is half size
  50004. mipLevelSize >>= 1;
  50005. this._numMipLevels++;
  50006. //terminate if mip chain becomes too small
  50007. if (mipLevelSize == 0) {
  50008. this.maxNumMipLevels = j;
  50009. return;
  50010. }
  50011. }
  50012. };
  50013. //--------------------------------------------------------------------------------------
  50014. //Cube map filtering and mip chain generation.
  50015. // the cube map filtereing is specified using a number of parameters:
  50016. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  50017. // indicates the region of the hemisphere to filter over for each tap.
  50018. //
  50019. // Note that the top mip level is also a filtered version of the original input images
  50020. // as well in order to create mip chains for diffuse environment illumination.
  50021. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  50022. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  50023. //
  50024. // Then the mip angle used to genreate the next level of the mip chain from the first level
  50025. // is a_InitialMipAngle
  50026. //
  50027. // The angle for the subsequent levels of the mip chain are specified by their parents
  50028. // filtering angle and a per-level scale and bias
  50029. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  50030. //
  50031. //--------------------------------------------------------------------------------------
  50032. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  50033. // First, take count of the lighting model to modify SpecularPower
  50034. // 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;
  50035. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  50036. //Cone angle start (for generating subsequent mip levels)
  50037. var currentSpecularPower = this.specularPower;
  50038. //Build filter lookup tables based on the source miplevel size
  50039. this.precomputeFilterLookupTables(this.inputSize);
  50040. // Note that we need to filter the first level before generating mipmap
  50041. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  50042. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  50043. // TODO : Write a function to copy and scale the base mipmap in output
  50044. // I am just lazy here and just put a high specular power value, and do some if.
  50045. if (this.excludeBase && (levelIndex == 0)) {
  50046. // 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).
  50047. currentSpecularPower = 100000.0;
  50048. }
  50049. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  50050. var srcCubeImage = this.input;
  50051. var dstCubeImage = this._outputSurface[levelIndex];
  50052. var dstSize = this.outputSize >> levelIndex;
  50053. // Compute required angle.
  50054. var angle = this.getBaseFilterAngle(currentSpecularPower);
  50055. // filter cube surfaces
  50056. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  50057. // fix seams
  50058. if (this.fixup) {
  50059. this.fixupCubeEdges(dstCubeImage, dstSize);
  50060. }
  50061. // Decrease the specular power to generate the mipmap chain
  50062. // TODO : Use another method for Exclude (see first comment at start of the function
  50063. if (this.excludeBase && (levelIndex == 0)) {
  50064. currentSpecularPower = this.specularPower;
  50065. }
  50066. currentSpecularPower *= this.cosinePowerDropPerMip;
  50067. }
  50068. };
  50069. //--------------------------------------------------------------------------------------
  50070. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  50071. // It allow to optimize the texel to access base on the specular power.
  50072. //--------------------------------------------------------------------------------------
  50073. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  50074. // We want to find the alpha such that:
  50075. // cos(alpha)^cosinePower = epsilon
  50076. // That's: acos(epsilon^(1/cosinePower))
  50077. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  50078. var angle = 180.0;
  50079. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  50080. angle *= 180.0 / Math.PI; // Convert to degree
  50081. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  50082. return angle;
  50083. };
  50084. //--------------------------------------------------------------------------------------
  50085. //Builds the following lookup tables prior to filtering:
  50086. // -normalizer cube map
  50087. // -tap weight lookup table
  50088. //
  50089. //--------------------------------------------------------------------------------------
  50090. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  50091. var srcTexelAngle;
  50092. var iCubeFace;
  50093. //clear pre-existing normalizer cube map
  50094. this._normCubeMap = [];
  50095. //Normalized vectors per cubeface and per-texel solid angle
  50096. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  50097. };
  50098. //--------------------------------------------------------------------------------------
  50099. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  50100. //
  50101. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  50102. //
  50103. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  50104. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  50105. // below
  50106. //--------------------------------------------------------------------------------------
  50107. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  50108. var iCubeFace;
  50109. var u;
  50110. var v;
  50111. //iterate over cube faces
  50112. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50113. //First three channels for norm cube, and last channel for solid angle
  50114. this._normCubeMap.push(new Float32Array(size * size * 4));
  50115. //fast texture walk, build normalizer cube map
  50116. var facesData = this.input[iCubeFace];
  50117. for (v = 0; v < size; v++) {
  50118. for (u = 0; u < size; u++) {
  50119. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  50120. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  50121. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  50122. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  50123. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  50124. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  50125. }
  50126. }
  50127. }
  50128. };
  50129. //--------------------------------------------------------------------------------------
  50130. // Convert cubemap face texel coordinates and face idx to 3D vector
  50131. // note the U and V coords are integer coords and range from 0 to size-1
  50132. // this routine can be used to generate a normalizer cube map
  50133. //--------------------------------------------------------------------------------------
  50134. // SL BEGIN
  50135. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  50136. var nvcU;
  50137. var nvcV;
  50138. var tempVec;
  50139. // Change from original AMD code
  50140. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50141. // + 0.5f is for texel center addressing
  50142. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  50143. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  50144. // warp fixup
  50145. if (fixup && size > 1) {
  50146. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  50147. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  50148. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  50149. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  50150. }
  50151. // Get current vector
  50152. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  50153. // U contribution
  50154. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50155. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  50156. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  50157. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  50158. // V contribution and Sum
  50159. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50160. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  50161. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  50162. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  50163. //add face axis
  50164. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  50165. PMREMGenerator._vectorTemp.x += faceAxis[0];
  50166. PMREMGenerator._vectorTemp.y += faceAxis[1];
  50167. PMREMGenerator._vectorTemp.z += faceAxis[2];
  50168. //normalize vector
  50169. PMREMGenerator._vectorTemp.normalize();
  50170. return PMREMGenerator._vectorTemp;
  50171. };
  50172. //--------------------------------------------------------------------------------------
  50173. // Convert 3D vector to cubemap face texel coordinates and face idx
  50174. // note the U and V coords are integer coords and range from 0 to size-1
  50175. // this routine can be used to generate a normalizer cube map
  50176. //
  50177. // returns face IDX and texel coords
  50178. //--------------------------------------------------------------------------------------
  50179. // SL BEGIN
  50180. /*
  50181. Mapping Texture Coordinates to Cube Map Faces
  50182. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  50183. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  50184. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  50185. map arrangement in Pixar's RenderMan package.
  50186. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  50187. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  50188. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  50189. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  50190. the major axis direction). The target column in the table below explains how the major axis direction
  50191. maps to the 2D image of a particular cube map target.
  50192. major axis
  50193. direction target sc tc ma
  50194. ---------- --------------------------------- --- --- ---
  50195. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  50196. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  50197. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  50198. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  50199. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  50200. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  50201. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  50202. an updated (s,t) is calculated as follows
  50203. s = ( sc/|ma| + 1 ) / 2
  50204. t = ( tc/|ma| + 1 ) / 2
  50205. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  50206. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  50207. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  50208. */
  50209. // Note this method return U and V in range from 0 to size-1
  50210. // SL END
  50211. // Store the information in vector3 for convenience (faceindex, u, v)
  50212. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  50213. var maxCoord;
  50214. var faceIdx;
  50215. //absolute value 3
  50216. var absX = Math.abs(x);
  50217. var absY = Math.abs(y);
  50218. var absZ = Math.abs(z);
  50219. if (absX >= absY && absX >= absZ) {
  50220. maxCoord = absX;
  50221. if (x >= 0) {
  50222. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  50223. }
  50224. else {
  50225. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  50226. }
  50227. }
  50228. else if (absY >= absX && absY >= absZ) {
  50229. maxCoord = absY;
  50230. if (y >= 0) {
  50231. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  50232. }
  50233. else {
  50234. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  50235. }
  50236. }
  50237. else {
  50238. maxCoord = absZ;
  50239. if (z >= 0) {
  50240. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  50241. }
  50242. else {
  50243. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  50244. }
  50245. }
  50246. //divide through by max coord so face vector lies on cube face
  50247. var scale = 1 / maxCoord;
  50248. x *= scale;
  50249. y *= scale;
  50250. z *= scale;
  50251. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50252. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  50253. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50254. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  50255. // Modify original AMD code to return value from 0 to Size - 1
  50256. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  50257. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  50258. PMREMGenerator._vectorTemp.x = faceIdx;
  50259. PMREMGenerator._vectorTemp.y = u;
  50260. PMREMGenerator._vectorTemp.z = v;
  50261. return PMREMGenerator._vectorTemp;
  50262. };
  50263. //--------------------------------------------------------------------------------------
  50264. //Original code from Ignacio CastaÒo
  50265. // This formula is from Manne ÷hrstrˆm's thesis.
  50266. // Take two coordiantes in the range [-1, 1] that define a portion of a
  50267. // cube face and return the area of the projection of that portion on the
  50268. // surface of the sphere.
  50269. //--------------------------------------------------------------------------------------
  50270. PMREMGenerator.prototype.areaElement = function (x, y) {
  50271. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  50272. };
  50273. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  50274. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50275. // (+ 0.5f is for texel center addressing)
  50276. u = (2.0 * (u + 0.5) / size) - 1.0;
  50277. v = (2.0 * (v + 0.5) / size) - 1.0;
  50278. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  50279. var invResolution = 1.0 / size;
  50280. // U and V are the -1..1 texture coordinate on the current face.
  50281. // Get projected area for this texel
  50282. var x0 = u - invResolution;
  50283. var y0 = v - invResolution;
  50284. var x1 = u + invResolution;
  50285. var y1 = v + invResolution;
  50286. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  50287. return solidAngle;
  50288. };
  50289. //--------------------------------------------------------------------------------------
  50290. //The key to the speed of these filtering routines is to quickly define a per-face
  50291. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  50292. // Later these pixels are selectively processed based on their dot products to see if
  50293. // they reside within the filtering cone.
  50294. //
  50295. //This is done by computing the smallest per-texel angle to get a conservative estimate
  50296. // of the number of texels needed to be covered in width and height order to filter the
  50297. // region. the bounding box for the center taps face is defined first, and if the
  50298. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  50299. // defined next
  50300. //--------------------------------------------------------------------------------------
  50301. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  50302. // note that pixels within these regions may be rejected
  50303. // based on the anlge
  50304. var iCubeFace;
  50305. var u;
  50306. var v;
  50307. // bounding box per face to specify region to process
  50308. var filterExtents = [];
  50309. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50310. filterExtents.push(new CMGBoundinBox());
  50311. }
  50312. // min angle a src texel can cover (in degrees)
  50313. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  50314. // angle about center tap to define filter cone
  50315. // filter angle is 1/2 the cone angle
  50316. var filterAngle = filterConeAngle / 2.0;
  50317. //ensure filter angle is larger than a texel
  50318. if (filterAngle < srcTexelAngle) {
  50319. filterAngle = srcTexelAngle;
  50320. }
  50321. //ensure filter cone is always smaller than the hemisphere
  50322. if (filterAngle > 90.0) {
  50323. filterAngle = 90.0;
  50324. }
  50325. // the maximum number of texels in 1D the filter cone angle will cover
  50326. // used to determine bounding box size for filter extents
  50327. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  50328. // ensure conservative region always covers at least one texel
  50329. if (filterSize < 1) {
  50330. filterSize = 1;
  50331. }
  50332. // dotProdThresh threshold based on cone angle to determine whether or not taps
  50333. // reside within the cone angle
  50334. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  50335. // process required faces
  50336. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50337. //iterate over dst cube map face texel
  50338. for (v = 0; v < dstSize; v++) {
  50339. for (u = 0; u < dstSize; u++) {
  50340. //get center tap direction
  50341. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  50342. //clear old per-face filter extents
  50343. this.clearFilterExtents(filterExtents);
  50344. //define per-face filter extents
  50345. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  50346. //perform filtering of src faces using filter extents
  50347. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  50348. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  50349. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  50350. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  50351. }
  50352. }
  50353. }
  50354. };
  50355. //--------------------------------------------------------------------------------------
  50356. //Clear filter extents for the 6 cube map faces
  50357. //--------------------------------------------------------------------------------------
  50358. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  50359. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  50360. filterExtents[iCubeFaces].clear();
  50361. }
  50362. };
  50363. //--------------------------------------------------------------------------------------
  50364. //Define per-face bounding box filter extents
  50365. //
  50366. // These define conservative texel regions in each of the faces the filter can possibly
  50367. // process. When the pixels in the regions are actually processed, the dot product
  50368. // between the tap vector and the center tap vector is used to determine the weight of
  50369. // the tap and whether or not the tap is within the cone.
  50370. //
  50371. //--------------------------------------------------------------------------------------
  50372. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  50373. //neighboring face and bleed over amount, and width of BBOX for
  50374. // left, right, top, and bottom edges of this face
  50375. var bleedOverAmount = [0, 0, 0, 0];
  50376. var bleedOverBBoxMin = [0, 0, 0, 0];
  50377. var bleedOverBBoxMax = [0, 0, 0, 0];
  50378. var neighborFace;
  50379. var neighborEdge;
  50380. var oppositeFaceIdx;
  50381. //get face idx, and u, v info from center tap dir
  50382. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  50383. var faceIdx = result.x;
  50384. var u = result.y;
  50385. var v = result.z;
  50386. //define bbox size within face
  50387. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  50388. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  50389. filterExtents[faceIdx].clampMin(0, 0, 0);
  50390. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  50391. //u and v extent in face corresponding to center tap
  50392. var minU = filterExtents[faceIdx].min.x;
  50393. var minV = filterExtents[faceIdx].min.y;
  50394. var maxU = filterExtents[faceIdx].max.x;
  50395. var maxV = filterExtents[faceIdx].max.y;
  50396. //bleed over amounts for face across u=0 edge (left)
  50397. bleedOverAmount[0] = (bboxSize - u);
  50398. bleedOverBBoxMin[0] = minV;
  50399. bleedOverBBoxMax[0] = maxV;
  50400. //bleed over amounts for face across u=1 edge (right)
  50401. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  50402. bleedOverBBoxMin[1] = minV;
  50403. bleedOverBBoxMax[1] = maxV;
  50404. //bleed over to face across v=0 edge (up)
  50405. bleedOverAmount[2] = (bboxSize - v);
  50406. bleedOverBBoxMin[2] = minU;
  50407. bleedOverBBoxMax[2] = maxU;
  50408. //bleed over to face across v=1 edge (down)
  50409. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  50410. bleedOverBBoxMin[3] = minU;
  50411. bleedOverBBoxMax[3] = maxU;
  50412. //compute bleed over regions in neighboring faces
  50413. for (var i = 0; i < 4; i++) {
  50414. if (bleedOverAmount[i] > 0) {
  50415. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  50416. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  50417. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  50418. // be flipped: the cases are
  50419. // if a left edge mates with a left or bottom edge on the neighbor
  50420. // if a top edge mates with a top or right edge on the neighbor
  50421. // if a right edge mates with a right or top edge on the neighbor
  50422. // if a bottom edge mates with a bottom or left edge on the neighbor
  50423. //Seeing as the edges are enumerated as follows
  50424. // left =0
  50425. // right =1
  50426. // top =2
  50427. // bottom =3
  50428. //
  50429. // so if the edge enums are the same, or the sum of the enums == 3,
  50430. // the bbox needs to be flipped
  50431. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  50432. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  50433. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  50434. }
  50435. //The way the bounding box is extended onto the neighboring face
  50436. // depends on which edge of neighboring face abuts with this one
  50437. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  50438. case PMREMGenerator.CP_EDGE_LEFT:
  50439. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  50440. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  50441. break;
  50442. case PMREMGenerator.CP_EDGE_RIGHT:
  50443. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  50444. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  50445. break;
  50446. case PMREMGenerator.CP_EDGE_TOP:
  50447. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  50448. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  50449. break;
  50450. case PMREMGenerator.CP_EDGE_BOTTOM:
  50451. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  50452. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  50453. break;
  50454. }
  50455. //clamp filter extents in non-center tap faces to remain within surface
  50456. filterExtents[neighborFace].clampMin(0, 0, 0);
  50457. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  50458. }
  50459. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  50460. // from the center tap face, then process the opposite face entirely for now.
  50461. //Note that the cases in which this happens, what usually happens is that
  50462. // more than one edge bleeds onto the opposite face, and the bounding box
  50463. // encompasses the entire cube map face.
  50464. if (bleedOverAmount[i] > srcSize) {
  50465. //determine opposite face
  50466. switch (faceIdx) {
  50467. case PMREMGenerator.CP_FACE_X_POS:
  50468. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  50469. break;
  50470. case PMREMGenerator.CP_FACE_X_NEG:
  50471. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  50472. break;
  50473. case PMREMGenerator.CP_FACE_Y_POS:
  50474. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  50475. break;
  50476. case PMREMGenerator.CP_FACE_Y_NEG:
  50477. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  50478. break;
  50479. case PMREMGenerator.CP_FACE_Z_POS:
  50480. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  50481. break;
  50482. case PMREMGenerator.CP_FACE_Z_NEG:
  50483. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  50484. break;
  50485. default:
  50486. break;
  50487. }
  50488. //just encompass entire face for now
  50489. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  50490. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  50491. }
  50492. }
  50493. };
  50494. //--------------------------------------------------------------------------------------
  50495. //ProcessFilterExtents
  50496. // Process bounding box in each cube face
  50497. //
  50498. //--------------------------------------------------------------------------------------
  50499. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  50500. //accumulators are 64-bit floats in order to have the precision needed
  50501. // over a summation of a large number of pixels
  50502. var dstAccum = [0, 0, 0, 0];
  50503. var weightAccum = 0;
  50504. var k = 0;
  50505. var nSrcChannels = this.numChannels;
  50506. // norm cube map and srcCubeMap have same face width
  50507. var faceWidth = srcSize;
  50508. //amount to add to pointer to move to next scanline in images
  50509. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  50510. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  50511. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  50512. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  50513. // iterate over cubefaces
  50514. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  50515. //if bbox is non empty
  50516. if (!filterExtents[iFaceIdx].empty()) {
  50517. var uStart = filterExtents[iFaceIdx].min.x;
  50518. var vStart = filterExtents[iFaceIdx].min.y;
  50519. var uEnd = filterExtents[iFaceIdx].max.x;
  50520. var vEnd = filterExtents[iFaceIdx].max.y;
  50521. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  50522. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  50523. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  50524. for (var v = vStart; v <= vEnd; v++) {
  50525. var normCubeRowWalk = 0;
  50526. var srcCubeRowWalk = 0;
  50527. for (var u = uStart; u <= uEnd; u++) {
  50528. //pointer to direction in cube map associated with texel
  50529. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  50530. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  50531. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  50532. //check dot product to see if texel is within cone
  50533. var tapDotProd = texelVectX * centerTapDir.x +
  50534. texelVectY * centerTapDir.y +
  50535. texelVectZ * centerTapDir.z;
  50536. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  50537. //solid angle stored in 4th channel of normalizer/solid angle cube map
  50538. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  50539. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  50540. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  50541. // so just adding one to specularpower do the trick.
  50542. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  50543. //iterate over channels
  50544. for (k = 0; k < nSrcChannels; k++) {
  50545. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  50546. srcCubeRowWalk++;
  50547. }
  50548. weightAccum += weight; //accumulate weight
  50549. }
  50550. else {
  50551. //step across source pixel
  50552. srcCubeRowWalk += nSrcChannels;
  50553. }
  50554. normCubeRowWalk += 4; // 4 channels per norm cube map.
  50555. }
  50556. startIndexNormCubeMap += normCubePitch;
  50557. startIndexSrcCubeMap += srcCubePitch;
  50558. }
  50559. }
  50560. }
  50561. //divide through by weights if weight is non zero
  50562. if (weightAccum != 0.0) {
  50563. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  50564. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  50565. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  50566. if (this.numChannels > 3) {
  50567. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  50568. }
  50569. }
  50570. else {
  50571. // otherwise sample nearest
  50572. // get face idx and u, v texel coordinate in face
  50573. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  50574. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  50575. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  50576. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  50577. if (this.numChannels > 3) {
  50578. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  50579. }
  50580. }
  50581. return PMREMGenerator._vectorTemp;
  50582. };
  50583. //--------------------------------------------------------------------------------------
  50584. // Fixup cube edges
  50585. //
  50586. // average texels on cube map faces across the edges
  50587. // WARP/BENT Method Only.
  50588. //--------------------------------------------------------------------------------------
  50589. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  50590. var k;
  50591. var j;
  50592. var i;
  50593. var iFace;
  50594. var iCorner = 0;
  50595. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  50596. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  50597. // note that if functionality to filter across the three texels for each corner, then
  50598. //indexed by corner and face idx. the array contains the face the start points belongs to.
  50599. var cornerPtr = [
  50600. [[], [], []],
  50601. [[], [], []],
  50602. [[], [], []],
  50603. [[], [], []],
  50604. [[], [], []],
  50605. [[], [], []],
  50606. [[], [], []],
  50607. [[], [], []]
  50608. ];
  50609. //if there is no fixup, or fixup width = 0, do nothing
  50610. if (cubeMapSize < 1) {
  50611. return;
  50612. }
  50613. //special case 1x1 cubemap, average face colors
  50614. if (cubeMapSize == 1) {
  50615. //iterate over channels
  50616. for (k = 0; k < this.numChannels; k++) {
  50617. var accum = 0.0;
  50618. //iterate over faces to accumulate face colors
  50619. for (iFace = 0; iFace < 6; iFace++) {
  50620. accum += cubeMap[iFace][k];
  50621. }
  50622. //compute average over 6 face colors
  50623. accum /= 6.0;
  50624. //iterate over faces to distribute face colors
  50625. for (iFace = 0; iFace < 6; iFace++) {
  50626. cubeMap[iFace][k] = accum;
  50627. }
  50628. }
  50629. return;
  50630. }
  50631. //iterate over faces to collect list of corner texel pointers
  50632. for (iFace = 0; iFace < 6; iFace++) {
  50633. //the 4 corner pointers for this face
  50634. faceCornerStartIndicies[0] = [iFace, 0];
  50635. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  50636. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  50637. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  50638. //iterate over face corners to collect cube corner pointers
  50639. for (iCorner = 0; iCorner < 4; iCorner++) {
  50640. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  50641. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  50642. cornerNumPtrs[corner]++;
  50643. }
  50644. }
  50645. //iterate over corners to average across corner tap values
  50646. for (iCorner = 0; iCorner < 8; iCorner++) {
  50647. for (k = 0; k < this.numChannels; k++) {
  50648. var cornerTapAccum = 0.0;
  50649. //iterate over corner texels and average results
  50650. for (i = 0; i < 3; i++) {
  50651. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  50652. }
  50653. //divide by 3 to compute average of corner tap values
  50654. cornerTapAccum *= (1.0 / 3.0);
  50655. //iterate over corner texels and average results
  50656. for (i = 0; i < 3; i++) {
  50657. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  50658. }
  50659. }
  50660. }
  50661. //iterate over the twelve edges of the cube to average across edges
  50662. for (i = 0; i < 12; i++) {
  50663. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  50664. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  50665. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  50666. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  50667. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  50668. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  50669. var edgeWalk = 0;
  50670. var neighborEdgeWalk = 0;
  50671. //Determine walking pointers based on edge type
  50672. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  50673. switch (edge) {
  50674. case PMREMGenerator.CP_EDGE_LEFT:
  50675. // no change to faceEdgeStartPtr
  50676. edgeWalk = this.numChannels * cubeMapSize;
  50677. break;
  50678. case PMREMGenerator.CP_EDGE_RIGHT:
  50679. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  50680. edgeWalk = this.numChannels * cubeMapSize;
  50681. break;
  50682. case PMREMGenerator.CP_EDGE_TOP:
  50683. // no change to faceEdgeStartPtr
  50684. edgeWalk = this.numChannels;
  50685. break;
  50686. case PMREMGenerator.CP_EDGE_BOTTOM:
  50687. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  50688. edgeWalk = this.numChannels;
  50689. break;
  50690. }
  50691. //For certain types of edge abutments, the neighbor edge walk needs to
  50692. // be flipped: the cases are
  50693. // if a left edge mates with a left or bottom edge on the neighbor
  50694. // if a top edge mates with a top or right edge on the neighbor
  50695. // if a right edge mates with a right or top edge on the neighbor
  50696. // if a bottom edge mates with a bottom or left edge on the neighbor
  50697. //Seeing as the edges are enumerated as follows
  50698. // left =0
  50699. // right =1
  50700. // top =2
  50701. // bottom =3
  50702. //
  50703. //If the edge enums are the same, or the sum of the enums == 3,
  50704. // the neighbor edge walk needs to be flipped
  50705. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  50706. switch (neighborEdge) {
  50707. case PMREMGenerator.CP_EDGE_LEFT:
  50708. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  50709. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  50710. break;
  50711. case PMREMGenerator.CP_EDGE_RIGHT:
  50712. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  50713. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  50714. break;
  50715. case PMREMGenerator.CP_EDGE_TOP:
  50716. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  50717. neighborEdgeWalk = -this.numChannels;
  50718. break;
  50719. case PMREMGenerator.CP_EDGE_BOTTOM:
  50720. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  50721. neighborEdgeWalk = -this.numChannels;
  50722. break;
  50723. }
  50724. }
  50725. else {
  50726. //swapped direction neighbor edge walk
  50727. switch (neighborEdge) {
  50728. case PMREMGenerator.CP_EDGE_LEFT:
  50729. //no change to neighborEdgeStartPtr for this case since it points
  50730. // to the upper left corner already
  50731. neighborEdgeWalk = this.numChannels * cubeMapSize;
  50732. break;
  50733. case PMREMGenerator.CP_EDGE_RIGHT:
  50734. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  50735. neighborEdgeWalk = this.numChannels * cubeMapSize;
  50736. break;
  50737. case PMREMGenerator.CP_EDGE_TOP:
  50738. //no change to neighborEdgeStartPtr for this case since it points
  50739. // to the upper left corner already
  50740. neighborEdgeWalk = this.numChannels;
  50741. break;
  50742. case PMREMGenerator.CP_EDGE_BOTTOM:
  50743. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  50744. neighborEdgeWalk = this.numChannels;
  50745. break;
  50746. }
  50747. }
  50748. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  50749. //nearby neighborhood
  50750. //step ahead one texel on edge
  50751. edgeStartIndex += edgeWalk;
  50752. neighborEdgeStartIndex += neighborEdgeWalk;
  50753. // note that this loop does not process the corner texels, since they have already been
  50754. // averaged across faces across earlier
  50755. for (j = 1; j < (cubeMapSize - 1); j++) {
  50756. //for each set of taps along edge, average them
  50757. // and rewrite the results into the edges
  50758. for (k = 0; k < this.numChannels; k++) {
  50759. var edgeTap = cubeMap[face][edgeStartIndex + k];
  50760. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  50761. //compute average of tap intensity values
  50762. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  50763. //propagate average of taps to edge taps
  50764. cubeMap[face][edgeStartIndex + k] = avgTap;
  50765. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  50766. }
  50767. edgeStartIndex += edgeWalk;
  50768. neighborEdgeStartIndex += neighborEdgeWalk;
  50769. }
  50770. }
  50771. };
  50772. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  50773. PMREMGenerator.CP_UDIR = 0;
  50774. PMREMGenerator.CP_VDIR = 1;
  50775. PMREMGenerator.CP_FACEAXIS = 2;
  50776. //used to index cube faces
  50777. PMREMGenerator.CP_FACE_X_POS = 0;
  50778. PMREMGenerator.CP_FACE_X_NEG = 1;
  50779. PMREMGenerator.CP_FACE_Y_POS = 2;
  50780. PMREMGenerator.CP_FACE_Y_NEG = 3;
  50781. PMREMGenerator.CP_FACE_Z_POS = 4;
  50782. PMREMGenerator.CP_FACE_Z_NEG = 5;
  50783. //used to index image edges
  50784. // NOTE.. the actual number corresponding to the edge is important
  50785. // do not change these, or the code will break
  50786. //
  50787. // CP_EDGE_LEFT is u = 0
  50788. // CP_EDGE_RIGHT is u = width-1
  50789. // CP_EDGE_TOP is v = 0
  50790. // CP_EDGE_BOTTOM is v = height-1
  50791. PMREMGenerator.CP_EDGE_LEFT = 0;
  50792. PMREMGenerator.CP_EDGE_RIGHT = 1;
  50793. PMREMGenerator.CP_EDGE_TOP = 2;
  50794. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  50795. //corners of CUBE map (P or N specifys if it corresponds to the
  50796. // positive or negative direction each of X, Y, and Z
  50797. PMREMGenerator.CP_CORNER_NNN = 0;
  50798. PMREMGenerator.CP_CORNER_NNP = 1;
  50799. PMREMGenerator.CP_CORNER_NPN = 2;
  50800. PMREMGenerator.CP_CORNER_NPP = 3;
  50801. PMREMGenerator.CP_CORNER_PNN = 4;
  50802. PMREMGenerator.CP_CORNER_PNP = 5;
  50803. PMREMGenerator.CP_CORNER_PPN = 6;
  50804. PMREMGenerator.CP_CORNER_PPP = 7;
  50805. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  50806. //3x2 matrices that map cube map indexing vectors in 3d
  50807. // (after face selection and divide through by the
  50808. // _ABSOLUTE VALUE_ of the max coord)
  50809. // into NVC space
  50810. //Note this currently assumes the D3D cube face ordering and orientation
  50811. PMREMGenerator._sgFace2DMapping = [
  50812. //XPOS face
  50813. [[0, 0, -1],
  50814. [0, -1, 0],
  50815. [1, 0, 0]],
  50816. //XNEG face
  50817. [[0, 0, 1],
  50818. [0, -1, 0],
  50819. [-1, 0, 0]],
  50820. //YPOS face
  50821. [[1, 0, 0],
  50822. [0, 0, 1],
  50823. [0, 1, 0]],
  50824. //YNEG face
  50825. [[1, 0, 0],
  50826. [0, 0, -1],
  50827. [0, -1, 0]],
  50828. //ZPOS face
  50829. [[1, 0, 0],
  50830. [0, -1, 0],
  50831. [0, 0, 1]],
  50832. //ZNEG face
  50833. [[-1, 0, 0],
  50834. [0, -1, 0],
  50835. [0, 0, -1]],
  50836. ];
  50837. //------------------------------------------------------------------------------
  50838. // D3D cube map face specification
  50839. // mapping from 3D x,y,z cube map lookup coordinates
  50840. // to 2D within face u,v coordinates
  50841. //
  50842. // --------------------> U direction
  50843. // | (within-face texture space)
  50844. // | _____
  50845. // | | |
  50846. // | | +Y |
  50847. // | _____|_____|_____ _____
  50848. // | | | | | |
  50849. // | | -X | +Z | +X | -Z |
  50850. // | |_____|_____|_____|_____|
  50851. // | | |
  50852. // | | -Y |
  50853. // | |_____|
  50854. // |
  50855. // v V direction
  50856. // (within-face texture space)
  50857. //------------------------------------------------------------------------------
  50858. //Information about neighbors and how texture coorrdinates change across faces
  50859. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  50860. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  50861. //Note this currently assumes the D3D cube face ordering and orientation
  50862. PMREMGenerator._sgCubeNgh = [
  50863. //XPOS face
  50864. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  50865. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  50866. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  50867. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  50868. //XNEG face
  50869. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  50870. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  50871. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  50872. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  50873. //YPOS face
  50874. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  50875. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  50876. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  50877. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  50878. //YNEG face
  50879. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  50880. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  50881. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  50882. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  50883. //ZPOS face
  50884. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  50885. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  50886. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  50887. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  50888. //ZNEG face
  50889. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  50890. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  50891. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  50892. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  50893. ];
  50894. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  50895. // this table is used to average over the edges.
  50896. PMREMGenerator._sgCubeEdgeList = [
  50897. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  50898. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  50899. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  50900. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  50901. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  50902. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  50903. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  50904. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  50905. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  50906. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  50907. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  50908. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  50909. ];
  50910. //Information about which of the 8 cube corners are correspond to the
  50911. // the 4 corners in each cube face
  50912. // the order is upper left, upper right, lower left, lower right
  50913. PMREMGenerator._sgCubeCornerList = [
  50914. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  50915. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  50916. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  50917. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  50918. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  50919. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  50920. ];
  50921. return PMREMGenerator;
  50922. }());
  50923. Internals.PMREMGenerator = PMREMGenerator;
  50924. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50925. })(BABYLON || (BABYLON = {}));
  50926. //# sourceMappingURL=../../Tools/HDR/babylon.tools.pmremGenerator.js.map
  50927. var BABYLON;
  50928. (function (BABYLON) {
  50929. /**
  50930. * This represents a texture coming from an HDR input.
  50931. *
  50932. * The only supported format is currently panorama picture stored in RGBE format.
  50933. * Example of such files can be found on HDRLib: http://hdrlib.com/
  50934. */
  50935. var HDRCubeTexture = (function (_super) {
  50936. __extends(HDRCubeTexture, _super);
  50937. /**
  50938. * Instantiates an HDRTexture from the following parameters.
  50939. *
  50940. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  50941. * @param scene The scene the texture will be used in
  50942. * @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.
  50943. * @param noMipmap Forces to not generate the mipmap if true
  50944. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  50945. * @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)
  50946. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  50947. */
  50948. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  50949. if (noMipmap === void 0) { noMipmap = false; }
  50950. if (generateHarmonics === void 0) { generateHarmonics = true; }
  50951. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  50952. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  50953. _super.call(this, scene);
  50954. this._useInGammaSpace = false;
  50955. this._generateHarmonics = true;
  50956. this._isBABYLONPreprocessed = false;
  50957. /**
  50958. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  50959. */
  50960. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  50961. /**
  50962. * The spherical polynomial data extracted from the texture.
  50963. */
  50964. this.sphericalPolynomial = null;
  50965. /**
  50966. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  50967. * This is usefull at run time to apply the good shader.
  50968. */
  50969. this.isPMREM = false;
  50970. if (!url) {
  50971. return;
  50972. }
  50973. this.name = url;
  50974. this.url = url;
  50975. this.hasAlpha = false;
  50976. this.isCube = true;
  50977. this._textureMatrix = BABYLON.Matrix.Identity();
  50978. if (size) {
  50979. this._isBABYLONPreprocessed = false;
  50980. this._noMipmap = noMipmap;
  50981. this._size = size;
  50982. this._useInGammaSpace = useInGammaSpace;
  50983. this._usePMREMGenerator = usePMREMGenerator &&
  50984. scene.getEngine().getCaps().textureLOD &&
  50985. this.getScene().getEngine().getCaps().textureFloat &&
  50986. !this._useInGammaSpace;
  50987. }
  50988. else {
  50989. this._isBABYLONPreprocessed = true;
  50990. this._noMipmap = false;
  50991. this._useInGammaSpace = false;
  50992. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  50993. this.getScene().getEngine().getCaps().textureFloat &&
  50994. !this._useInGammaSpace;
  50995. }
  50996. this.isPMREM = this._usePMREMGenerator;
  50997. this._texture = this._getFromCache(url, this._noMipmap);
  50998. if (!this._texture) {
  50999. if (!scene.useDelayedTextureLoading) {
  51000. this.loadTexture();
  51001. }
  51002. else {
  51003. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51004. }
  51005. }
  51006. }
  51007. /**
  51008. * Occurs when the file is a preprocessed .babylon.hdr file.
  51009. */
  51010. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  51011. var _this = this;
  51012. var mipLevels = 0;
  51013. var floatArrayView = null;
  51014. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  51015. var mips = [];
  51016. var startIndex = 30;
  51017. for (var level = 0; level < mipLevels; level++) {
  51018. mips.push([]);
  51019. // Fill each pixel of the mip level.
  51020. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  51021. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51022. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  51023. mips[level].push(faceData);
  51024. startIndex += faceSize;
  51025. }
  51026. }
  51027. return mips;
  51028. } : null;
  51029. var callback = function (buffer) {
  51030. // Create Native Array Views
  51031. var intArrayView = new Int32Array(buffer);
  51032. floatArrayView = new Float32Array(buffer);
  51033. // Fill header.
  51034. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  51035. _this._size = intArrayView[1]; // CubeMap max mip face size.
  51036. // Update Texture Information.
  51037. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  51038. // Fill polynomial information.
  51039. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  51040. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  51041. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  51042. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  51043. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  51044. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  51045. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  51046. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  51047. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  51048. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  51049. // Fill pixel data.
  51050. mipLevels = intArrayView[29]; // Number of mip levels.
  51051. var startIndex = 30;
  51052. var data = [];
  51053. var faceSize = Math.pow(_this._size, 2) * 3;
  51054. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51055. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  51056. startIndex += faceSize;
  51057. }
  51058. var results = [];
  51059. var byteArray = null;
  51060. // Push each faces.
  51061. for (var k = 0; k < 6; k++) {
  51062. var dataFace = null;
  51063. // If special cases.
  51064. if (!mipmapGenerator) {
  51065. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  51066. dataFace = data[j];
  51067. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51068. // 3 channels of 1 bytes per pixel in bytes.
  51069. var byteBuffer = new ArrayBuffer(faceSize);
  51070. byteArray = new Uint8Array(byteBuffer);
  51071. }
  51072. for (var i = 0; i < _this._size * _this._size; i++) {
  51073. // Put in gamma space if requested.
  51074. if (_this._useInGammaSpace) {
  51075. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51076. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51077. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51078. }
  51079. // Convert to int texture for fallback.
  51080. if (byteArray) {
  51081. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51082. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51083. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51084. // May use luminance instead if the result is not accurate.
  51085. var max = Math.max(Math.max(r, g), b);
  51086. if (max > 255) {
  51087. var scale = 255 / max;
  51088. r *= scale;
  51089. g *= scale;
  51090. b *= scale;
  51091. }
  51092. byteArray[(i * 3) + 0] = r;
  51093. byteArray[(i * 3) + 1] = g;
  51094. byteArray[(i * 3) + 2] = b;
  51095. }
  51096. }
  51097. }
  51098. else {
  51099. dataFace = data[k];
  51100. }
  51101. // Fill the array accordingly.
  51102. if (byteArray) {
  51103. results.push(byteArray);
  51104. }
  51105. else {
  51106. results.push(dataFace);
  51107. }
  51108. }
  51109. return results;
  51110. };
  51111. 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);
  51112. };
  51113. /**
  51114. * Occurs when the file is raw .hdr file.
  51115. */
  51116. HDRCubeTexture.prototype.loadHDRTexture = function () {
  51117. var _this = this;
  51118. var callback = function (buffer) {
  51119. // Extract the raw linear data.
  51120. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  51121. // Generate harmonics if needed.
  51122. if (_this._generateHarmonics) {
  51123. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  51124. }
  51125. var results = [];
  51126. var byteArray = null;
  51127. // Push each faces.
  51128. for (var j = 0; j < 6; j++) {
  51129. // Create uintarray fallback.
  51130. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51131. // 3 channels of 1 bytes per pixel in bytes.
  51132. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  51133. byteArray = new Uint8Array(byteBuffer);
  51134. }
  51135. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  51136. // If special cases.
  51137. if (_this._useInGammaSpace || byteArray) {
  51138. for (var i = 0; i < _this._size * _this._size; i++) {
  51139. // Put in gamma space if requested.
  51140. if (_this._useInGammaSpace) {
  51141. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51142. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51143. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51144. }
  51145. // Convert to int texture for fallback.
  51146. if (byteArray) {
  51147. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51148. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51149. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51150. // May use luminance instead if the result is not accurate.
  51151. var max = Math.max(Math.max(r, g), b);
  51152. if (max > 255) {
  51153. var scale = 255 / max;
  51154. r *= scale;
  51155. g *= scale;
  51156. b *= scale;
  51157. }
  51158. byteArray[(i * 3) + 0] = r;
  51159. byteArray[(i * 3) + 1] = g;
  51160. byteArray[(i * 3) + 2] = b;
  51161. }
  51162. }
  51163. }
  51164. if (byteArray) {
  51165. results.push(byteArray);
  51166. }
  51167. else {
  51168. results.push(dataFace);
  51169. }
  51170. }
  51171. return results;
  51172. };
  51173. var mipmapGenerator = null;
  51174. if (!this._noMipmap &&
  51175. this._usePMREMGenerator) {
  51176. mipmapGenerator = function (data) {
  51177. // Custom setup of the generator matching with the PBR shader values.
  51178. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  51179. return generator.filterCubeMap();
  51180. };
  51181. }
  51182. 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);
  51183. };
  51184. /**
  51185. * Starts the loading process of the texture.
  51186. */
  51187. HDRCubeTexture.prototype.loadTexture = function () {
  51188. if (this._isBABYLONPreprocessed) {
  51189. this.loadBabylonTexture();
  51190. }
  51191. else {
  51192. this.loadHDRTexture();
  51193. }
  51194. };
  51195. HDRCubeTexture.prototype.clone = function () {
  51196. var size = this._isBABYLONPreprocessed ? null : this._size;
  51197. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  51198. // Base texture
  51199. newTexture.level = this.level;
  51200. newTexture.wrapU = this.wrapU;
  51201. newTexture.wrapV = this.wrapV;
  51202. newTexture.coordinatesIndex = this.coordinatesIndex;
  51203. newTexture.coordinatesMode = this.coordinatesMode;
  51204. return newTexture;
  51205. };
  51206. // Methods
  51207. HDRCubeTexture.prototype.delayLoad = function () {
  51208. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51209. return;
  51210. }
  51211. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51212. this._texture = this._getFromCache(this.url, this._noMipmap);
  51213. if (!this._texture) {
  51214. this.loadTexture();
  51215. }
  51216. };
  51217. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  51218. return this._textureMatrix;
  51219. };
  51220. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51221. var texture = null;
  51222. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  51223. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  51224. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  51225. texture.name = parsedTexture.name;
  51226. texture.hasAlpha = parsedTexture.hasAlpha;
  51227. texture.level = parsedTexture.level;
  51228. texture.coordinatesMode = parsedTexture.coordinatesMode;
  51229. }
  51230. return texture;
  51231. };
  51232. HDRCubeTexture.prototype.serialize = function () {
  51233. if (!this.name) {
  51234. return null;
  51235. }
  51236. var serializationObject = {};
  51237. serializationObject.name = this.name;
  51238. serializationObject.hasAlpha = this.hasAlpha;
  51239. serializationObject.isCube = true;
  51240. serializationObject.level = this.level;
  51241. serializationObject.size = this._size;
  51242. serializationObject.coordinatesMode = this.coordinatesMode;
  51243. serializationObject.useInGammaSpace = this._useInGammaSpace;
  51244. serializationObject.generateHarmonics = this._generateHarmonics;
  51245. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  51246. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  51247. serializationObject.customType = "BABYLON.HDRCubeTexture";
  51248. return serializationObject;
  51249. };
  51250. /**
  51251. * Saves as a file the data contained in the texture in a binary format.
  51252. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51253. * as the spherical used in the lighting.
  51254. * @param url The HDR file url.
  51255. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51256. * @param onError Method called if any error happens during download.
  51257. * @return The packed binary data.
  51258. */
  51259. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  51260. if (onError === void 0) { onError = null; }
  51261. var callback = function (buffer) {
  51262. var data = new Blob([buffer], { type: 'application/octet-stream' });
  51263. // Returns a URL you can use as a href.
  51264. var objUrl = window.URL.createObjectURL(data);
  51265. // Simulates a link to it and click to dowload.
  51266. var a = document.createElement("a");
  51267. document.body.appendChild(a);
  51268. a.style.display = "none";
  51269. a.href = objUrl;
  51270. a.download = "envmap.babylon.hdr";
  51271. a.click();
  51272. };
  51273. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  51274. };
  51275. /**
  51276. * Serializes the data contained in the texture in a binary format.
  51277. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51278. * as the spherical used in the lighting.
  51279. * @param url The HDR file url.
  51280. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51281. * @param onError Method called if any error happens during download.
  51282. * @return The packed binary data.
  51283. */
  51284. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  51285. if (onError === void 0) { onError = null; }
  51286. // Needs the url tho create the texture.
  51287. if (!url) {
  51288. return null;
  51289. }
  51290. // Check Power of two size.
  51291. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  51292. return null;
  51293. }
  51294. var getDataCallback = function (dataBuffer) {
  51295. // Extract the raw linear data.
  51296. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  51297. // Generate harmonics if needed.
  51298. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  51299. // Generate seamless faces
  51300. var mipGeneratorArray = [];
  51301. // Data are known to be in +X +Y +Z -X -Y -Z
  51302. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  51303. mipGeneratorArray.push(cubeData.right); // +X
  51304. mipGeneratorArray.push(cubeData.left); // -X
  51305. mipGeneratorArray.push(cubeData.up); // +Y
  51306. mipGeneratorArray.push(cubeData.down); // -Y
  51307. mipGeneratorArray.push(cubeData.front); // +Z
  51308. mipGeneratorArray.push(cubeData.back); // -Z
  51309. // Custom setup of the generator matching with the PBR shader values.
  51310. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  51311. var mippedData = generator.filterCubeMap();
  51312. // Compute required byte length.
  51313. var byteLength = 1 * 4; // Raw Data Version int32.
  51314. byteLength += 4; // CubeMap max mip face size int32.
  51315. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  51316. // Add data size.
  51317. byteLength += 4; // Number of mip levels int32.
  51318. for (var level = 0; level < mippedData.length; level++) {
  51319. var mipSize = size >> level;
  51320. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  51321. }
  51322. // Prepare binary structure.
  51323. var buffer = new ArrayBuffer(byteLength);
  51324. var intArrayView = new Int32Array(buffer);
  51325. var floatArrayView = new Float32Array(buffer);
  51326. // Fill header.
  51327. intArrayView[0] = 1; // Version 1.
  51328. intArrayView[1] = size; // CubeMap max mip face size.
  51329. // Fill polynomial information.
  51330. sphericalPolynomial.x.toArray(floatArrayView, 2);
  51331. sphericalPolynomial.y.toArray(floatArrayView, 5);
  51332. sphericalPolynomial.z.toArray(floatArrayView, 8);
  51333. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  51334. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  51335. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  51336. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  51337. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  51338. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  51339. // Fill pixel data.
  51340. intArrayView[29] = mippedData.length; // Number of mip levels.
  51341. var startIndex = 30;
  51342. for (var level = 0; level < mippedData.length; level++) {
  51343. // Fill each pixel of the mip level.
  51344. var faceSize = Math.pow(size >> level, 2) * 3;
  51345. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51346. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  51347. startIndex += faceSize;
  51348. }
  51349. }
  51350. // Callback.
  51351. callback(buffer);
  51352. };
  51353. // Download and process.
  51354. BABYLON.Tools.LoadFile(url, function (data) {
  51355. getDataCallback(data);
  51356. }, null, null, true, onError);
  51357. };
  51358. HDRCubeTexture._facesMapping = [
  51359. "right",
  51360. "up",
  51361. "front",
  51362. "left",
  51363. "down",
  51364. "back"
  51365. ];
  51366. return HDRCubeTexture;
  51367. }(BABYLON.BaseTexture));
  51368. BABYLON.HDRCubeTexture = HDRCubeTexture;
  51369. })(BABYLON || (BABYLON = {}));
  51370. //# sourceMappingURL=../../Materials/Textures/babylon.hdrCubeTexture.js.map
  51371. var BABYLON;
  51372. (function (BABYLON) {
  51373. var Debug;
  51374. (function (Debug) {
  51375. /**
  51376. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  51377. */
  51378. var SkeletonViewer = (function () {
  51379. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  51380. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  51381. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  51382. this.skeleton = skeleton;
  51383. this.mesh = mesh;
  51384. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  51385. this.renderingGroupId = renderingGroupId;
  51386. this.color = BABYLON.Color3.White();
  51387. this._debugLines = [];
  51388. this._isEnabled = false;
  51389. this._scene = scene;
  51390. this.update();
  51391. this._renderFunction = this.update.bind(this);
  51392. }
  51393. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  51394. get: function () {
  51395. return this._isEnabled;
  51396. },
  51397. set: function (value) {
  51398. if (this._isEnabled === value) {
  51399. return;
  51400. }
  51401. this._isEnabled = value;
  51402. if (value) {
  51403. this._scene.registerBeforeRender(this._renderFunction);
  51404. }
  51405. else {
  51406. this._scene.unregisterBeforeRender(this._renderFunction);
  51407. }
  51408. },
  51409. enumerable: true,
  51410. configurable: true
  51411. });
  51412. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  51413. if (x === void 0) { x = 0; }
  51414. if (y === void 0) { y = 0; }
  51415. if (z === void 0) { z = 0; }
  51416. var tmat = BABYLON.Tmp.Matrix[0];
  51417. var parentBone = bone.getParent();
  51418. tmat.copyFrom(bone.getLocalMatrix());
  51419. if (x !== 0 || y !== 0 || z !== 0) {
  51420. var tmat2 = BABYLON.Tmp.Matrix[1];
  51421. BABYLON.Matrix.IdentityToRef(tmat2);
  51422. tmat2.m[12] = x;
  51423. tmat2.m[13] = y;
  51424. tmat2.m[14] = z;
  51425. tmat2.multiplyToRef(tmat, tmat);
  51426. }
  51427. if (parentBone) {
  51428. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  51429. }
  51430. tmat.multiplyToRef(meshMat, tmat);
  51431. position.x = tmat.m[12];
  51432. position.y = tmat.m[13];
  51433. position.z = tmat.m[14];
  51434. };
  51435. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  51436. var len = bones.length;
  51437. for (var i = 0; i < len; i++) {
  51438. var bone = bones[i];
  51439. var points = this._debugLines[i];
  51440. if (!points) {
  51441. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51442. this._debugLines[i] = points;
  51443. }
  51444. this._getBonePosition(points[0], bone, meshMat);
  51445. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  51446. }
  51447. };
  51448. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  51449. var len = bones.length;
  51450. var boneNum = 0;
  51451. for (var i = len - 1; i >= 0; i--) {
  51452. var childBone = bones[i];
  51453. var parentBone = childBone.getParent();
  51454. if (!parentBone) {
  51455. continue;
  51456. }
  51457. var points = this._debugLines[boneNum];
  51458. if (!points) {
  51459. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51460. this._debugLines[boneNum] = points;
  51461. }
  51462. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  51463. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  51464. boneNum++;
  51465. }
  51466. };
  51467. SkeletonViewer.prototype.update = function () {
  51468. if (this.autoUpdateBonesMatrices) {
  51469. this.skeleton.computeAbsoluteTransforms();
  51470. }
  51471. if (this.skeleton.bones[0].length === undefined) {
  51472. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  51473. }
  51474. else {
  51475. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  51476. }
  51477. if (!this._debugMesh) {
  51478. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  51479. this._debugMesh.renderingGroupId = this.renderingGroupId;
  51480. }
  51481. else {
  51482. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  51483. }
  51484. this._debugMesh.color = this.color;
  51485. };
  51486. SkeletonViewer.prototype.dispose = function () {
  51487. if (this._debugMesh) {
  51488. this.isEnabled = false;
  51489. this._debugMesh.dispose();
  51490. this._debugMesh = null;
  51491. }
  51492. };
  51493. return SkeletonViewer;
  51494. }());
  51495. Debug.SkeletonViewer = SkeletonViewer;
  51496. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  51497. })(BABYLON || (BABYLON = {}));
  51498. //# sourceMappingURL=../Debug/babylon.skeletonViewer.js.map
  51499. var BABYLON;
  51500. (function (BABYLON) {
  51501. var Debug;
  51502. (function (Debug) {
  51503. var AxesViewer = (function () {
  51504. function AxesViewer(scene, scaleLines) {
  51505. if (scaleLines === void 0) { scaleLines = 1; }
  51506. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51507. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51508. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  51509. this.scaleLines = 1;
  51510. this.scaleLines = scaleLines;
  51511. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  51512. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  51513. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  51514. this._xmesh.renderingGroupId = 2;
  51515. this._ymesh.renderingGroupId = 2;
  51516. this._zmesh.renderingGroupId = 2;
  51517. this._xmesh.material.checkReadyOnlyOnce = true;
  51518. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  51519. this._ymesh.material.checkReadyOnlyOnce = true;
  51520. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  51521. this._zmesh.material.checkReadyOnlyOnce = true;
  51522. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  51523. this.scene = scene;
  51524. }
  51525. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  51526. var scaleLines = this.scaleLines;
  51527. var point1 = this._xline[0];
  51528. var point2 = this._xline[1];
  51529. point1.x = position.x;
  51530. point1.y = position.y;
  51531. point1.z = position.z;
  51532. point2.x = point1.x + xaxis.x * scaleLines;
  51533. point2.y = point1.y + xaxis.y * scaleLines;
  51534. point2.z = point1.z + xaxis.z * scaleLines;
  51535. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  51536. point1 = this._yline[0];
  51537. point2 = this._yline[1];
  51538. point1.x = position.x;
  51539. point1.y = position.y;
  51540. point1.z = position.z;
  51541. point2.x = point1.x + yaxis.x * scaleLines;
  51542. point2.y = point1.y + yaxis.y * scaleLines;
  51543. point2.z = point1.z + yaxis.z * scaleLines;
  51544. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  51545. point1 = this._zline[0];
  51546. point2 = this._zline[1];
  51547. point1.x = position.x;
  51548. point1.y = position.y;
  51549. point1.z = position.z;
  51550. point2.x = point1.x + zaxis.x * scaleLines;
  51551. point2.y = point1.y + zaxis.y * scaleLines;
  51552. point2.z = point1.z + zaxis.z * scaleLines;
  51553. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  51554. };
  51555. AxesViewer.prototype.dispose = function () {
  51556. if (this._xmesh) {
  51557. this._xmesh.dispose();
  51558. this._ymesh.dispose();
  51559. this._zmesh.dispose();
  51560. this._xmesh = null;
  51561. this._ymesh = null;
  51562. this._zmesh = null;
  51563. this._xline = null;
  51564. this._yline = null;
  51565. this._zline = null;
  51566. this.scene = null;
  51567. }
  51568. };
  51569. return AxesViewer;
  51570. }());
  51571. Debug.AxesViewer = AxesViewer;
  51572. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  51573. })(BABYLON || (BABYLON = {}));
  51574. //# sourceMappingURL=../Debug/babylon.axesViewer.js.map
  51575. var BABYLON;
  51576. (function (BABYLON) {
  51577. var Debug;
  51578. (function (Debug) {
  51579. var BoneAxesViewer = (function (_super) {
  51580. __extends(BoneAxesViewer, _super);
  51581. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  51582. if (scaleLines === void 0) { scaleLines = 1; }
  51583. _super.call(this, scene, scaleLines);
  51584. this.pos = BABYLON.Vector3.Zero();
  51585. this.xaxis = BABYLON.Vector3.Zero();
  51586. this.yaxis = BABYLON.Vector3.Zero();
  51587. this.zaxis = BABYLON.Vector3.Zero();
  51588. this.mesh = mesh;
  51589. this.bone = bone;
  51590. }
  51591. BoneAxesViewer.prototype.update = function () {
  51592. var bone = this.bone;
  51593. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  51594. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  51595. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  51596. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  51597. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  51598. };
  51599. BoneAxesViewer.prototype.dispose = function () {
  51600. if (this.pos) {
  51601. this.pos = null;
  51602. this.xaxis = null;
  51603. this.yaxis = null;
  51604. this.zaxis = null;
  51605. this.mesh = null;
  51606. this.bone = null;
  51607. _super.prototype.dispose.call(this);
  51608. }
  51609. };
  51610. return BoneAxesViewer;
  51611. }(Debug.AxesViewer));
  51612. Debug.BoneAxesViewer = BoneAxesViewer;
  51613. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  51614. })(BABYLON || (BABYLON = {}));
  51615. //# sourceMappingURL=../Debug/babylon.boneAxesViewer.js.map
  51616. var BABYLON;
  51617. (function (BABYLON) {
  51618. /**
  51619. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  51620. * It can help converting any input color in a desired output one. This can then be used to create effects
  51621. * from sepia, black and white to sixties or futuristic rendering...
  51622. *
  51623. * The only supported format is currently 3dl.
  51624. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  51625. */
  51626. var ColorGradingTexture = (function (_super) {
  51627. __extends(ColorGradingTexture, _super);
  51628. /**
  51629. * Instantiates a ColorGradingTexture from the following parameters.
  51630. *
  51631. * @param url The location of the color gradind data (currently only supporting 3dl)
  51632. * @param scene The scene the texture will be used in
  51633. */
  51634. function ColorGradingTexture(url, scene) {
  51635. _super.call(this, scene);
  51636. if (!url) {
  51637. return;
  51638. }
  51639. this._textureMatrix = BABYLON.Matrix.Identity();
  51640. this.name = url;
  51641. this.url = url;
  51642. this.hasAlpha = false;
  51643. this.isCube = false;
  51644. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51645. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51646. this.anisotropicFilteringLevel = 1;
  51647. this._texture = this._getFromCache(url, true);
  51648. if (!this._texture) {
  51649. if (!scene.useDelayedTextureLoading) {
  51650. this.loadTexture();
  51651. }
  51652. else {
  51653. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51654. }
  51655. }
  51656. }
  51657. /**
  51658. * Returns the texture matrix used in most of the material.
  51659. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  51660. */
  51661. ColorGradingTexture.prototype.getTextureMatrix = function () {
  51662. return this._textureMatrix;
  51663. };
  51664. /**
  51665. * Occurs when the file being loaded is a .3dl LUT file.
  51666. */
  51667. ColorGradingTexture.prototype.load3dlTexture = function () {
  51668. var _this = this;
  51669. var mipLevels = 0;
  51670. var floatArrayView = null;
  51671. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51672. this._texture = texture;
  51673. var callback = function (text) {
  51674. var data;
  51675. var tempData;
  51676. var line;
  51677. var lines = text.split('\n');
  51678. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  51679. var maxColor = 0;
  51680. for (var i = 0; i < lines.length; i++) {
  51681. line = lines[i];
  51682. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  51683. continue;
  51684. if (line.indexOf('#') === 0)
  51685. continue;
  51686. var words = line.split(" ");
  51687. if (size === 0) {
  51688. // Number of space + one
  51689. size = words.length;
  51690. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  51691. tempData = new Float32Array(size * size * size * 4);
  51692. continue;
  51693. }
  51694. if (size != 0) {
  51695. var r = Math.max(parseInt(words[0]), 0);
  51696. var g = Math.max(parseInt(words[1]), 0);
  51697. var b = Math.max(parseInt(words[2]), 0);
  51698. maxColor = Math.max(r, maxColor);
  51699. maxColor = Math.max(g, maxColor);
  51700. maxColor = Math.max(b, maxColor);
  51701. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  51702. tempData[pixelStorageIndex + 0] = r;
  51703. tempData[pixelStorageIndex + 1] = g;
  51704. tempData[pixelStorageIndex + 2] = b;
  51705. tempData[pixelStorageIndex + 3] = 0;
  51706. pixelIndexSlice++;
  51707. if (pixelIndexSlice % size == 0) {
  51708. pixelIndexH++;
  51709. pixelIndexSlice = 0;
  51710. if (pixelIndexH % size == 0) {
  51711. pixelIndexW++;
  51712. pixelIndexH = 0;
  51713. }
  51714. }
  51715. }
  51716. }
  51717. for (var i = 0; i < tempData.length; i++) {
  51718. var value = tempData[i];
  51719. data[i] = (value / maxColor * 255);
  51720. }
  51721. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  51722. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  51723. };
  51724. BABYLON.Tools.LoadFile(this.url, callback);
  51725. return this._texture;
  51726. };
  51727. /**
  51728. * Starts the loading process of the texture.
  51729. */
  51730. ColorGradingTexture.prototype.loadTexture = function () {
  51731. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  51732. this.load3dlTexture();
  51733. }
  51734. };
  51735. /**
  51736. * Clones the color gradind texture.
  51737. */
  51738. ColorGradingTexture.prototype.clone = function () {
  51739. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  51740. // Base texture
  51741. newTexture.level = this.level;
  51742. return newTexture;
  51743. };
  51744. /**
  51745. * Called during delayed load for textures.
  51746. */
  51747. ColorGradingTexture.prototype.delayLoad = function () {
  51748. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51749. return;
  51750. }
  51751. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51752. this._texture = this._getFromCache(this.url, true);
  51753. if (!this._texture) {
  51754. this.loadTexture();
  51755. }
  51756. };
  51757. /**
  51758. * Binds the color grading to the shader.
  51759. * @param colorGrading The texture to bind
  51760. * @param effect The effect to bind to
  51761. */
  51762. ColorGradingTexture.Bind = function (colorGrading, effect) {
  51763. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  51764. var x = colorGrading.level; // Texture Level
  51765. var y = colorGrading.getSize().height; // Texture Size example with 8
  51766. var z = y - 1.0; // SizeMinusOne 8 - 1
  51767. var w = 1 / y; // Space of 1 slice 1 / 8
  51768. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  51769. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  51770. 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
  51771. 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
  51772. 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
  51773. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  51774. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  51775. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  51776. };
  51777. /**
  51778. * Prepare the list of uniforms associated with the ColorGrading effects.
  51779. * @param uniformsList The list of uniforms used in the effect
  51780. * @param samplersList The list of samplers used in the effect
  51781. */
  51782. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  51783. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  51784. samplersList.push("cameraColorGrading2DSampler");
  51785. };
  51786. /**
  51787. * Parses a color grading texture serialized by Babylon.
  51788. * @param parsedTexture The texture information being parsedTexture
  51789. * @param scene The scene to load the texture in
  51790. * @param rootUrl The root url of the data assets to load
  51791. * @return A color gradind texture
  51792. */
  51793. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51794. var texture = null;
  51795. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  51796. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  51797. texture.name = parsedTexture.name;
  51798. texture.level = parsedTexture.level;
  51799. }
  51800. return texture;
  51801. };
  51802. /**
  51803. * Serializes the LUT texture to json format.
  51804. */
  51805. ColorGradingTexture.prototype.serialize = function () {
  51806. if (!this.name) {
  51807. return null;
  51808. }
  51809. var serializationObject = {};
  51810. serializationObject.name = this.name;
  51811. serializationObject.level = this.level;
  51812. serializationObject.customType = "BABYLON.ColorGradingTexture";
  51813. return serializationObject;
  51814. };
  51815. /**
  51816. * Empty line regex stored for GC.
  51817. */
  51818. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  51819. return ColorGradingTexture;
  51820. }(BABYLON.BaseTexture));
  51821. BABYLON.ColorGradingTexture = ColorGradingTexture;
  51822. })(BABYLON || (BABYLON = {}));
  51823. //# sourceMappingURL=../../Materials/Textures/babylon.colorGradingTexture.js.map
  51824. var BABYLON;
  51825. (function (BABYLON) {
  51826. /**
  51827. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  51828. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  51829. * 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;
  51830. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  51831. */
  51832. var ColorCurves = (function () {
  51833. function ColorCurves() {
  51834. this._dirty = true;
  51835. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  51836. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  51837. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  51838. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  51839. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  51840. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  51841. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  51842. this._globalHue = 30;
  51843. this._globalDensity = 0;
  51844. this._globalSaturation = 0;
  51845. this._globalExposure = 0;
  51846. this._highlightsHue = 30;
  51847. this._highlightsDensity = 0;
  51848. this._highlightsSaturation = 0;
  51849. this._highlightsExposure = 0;
  51850. this._midtonesHue = 30;
  51851. this._midtonesDensity = 0;
  51852. this._midtonesSaturation = 0;
  51853. this._midtonesExposure = 0;
  51854. this._shadowsHue = 30;
  51855. this._shadowsDensity = 0;
  51856. this._shadowsSaturation = 0;
  51857. this._shadowsExposure = 0;
  51858. }
  51859. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  51860. /**
  51861. * Gets the global Hue value.
  51862. * 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).
  51863. */
  51864. get: function () {
  51865. return this._globalHue;
  51866. },
  51867. /**
  51868. * Sets the global Hue value.
  51869. * 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).
  51870. */
  51871. set: function (value) {
  51872. this._globalHue = value;
  51873. this._dirty = true;
  51874. },
  51875. enumerable: true,
  51876. configurable: true
  51877. });
  51878. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  51879. /**
  51880. * Gets the global Density value.
  51881. * 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.
  51882. * Values less than zero provide a filter of opposite hue.
  51883. */
  51884. get: function () {
  51885. return this._globalDensity;
  51886. },
  51887. /**
  51888. * Sets the global Density value.
  51889. * 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.
  51890. * Values less than zero provide a filter of opposite hue.
  51891. */
  51892. set: function (value) {
  51893. this._globalDensity = value;
  51894. this._dirty = true;
  51895. },
  51896. enumerable: true,
  51897. configurable: true
  51898. });
  51899. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  51900. /**
  51901. * Gets the global Saturation value.
  51902. * 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.
  51903. */
  51904. get: function () {
  51905. return this._globalSaturation;
  51906. },
  51907. /**
  51908. * Sets the global Saturation value.
  51909. * 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.
  51910. */
  51911. set: function (value) {
  51912. this._globalSaturation = value;
  51913. this._dirty = true;
  51914. },
  51915. enumerable: true,
  51916. configurable: true
  51917. });
  51918. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  51919. /**
  51920. * Gets the highlights Hue value.
  51921. * 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).
  51922. */
  51923. get: function () {
  51924. return this._highlightsHue;
  51925. },
  51926. /**
  51927. * Sets the highlights Hue value.
  51928. * 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).
  51929. */
  51930. set: function (value) {
  51931. this._highlightsHue = value;
  51932. this._dirty = true;
  51933. },
  51934. enumerable: true,
  51935. configurable: true
  51936. });
  51937. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  51938. /**
  51939. * Gets the highlights Density value.
  51940. * 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.
  51941. * Values less than zero provide a filter of opposite hue.
  51942. */
  51943. get: function () {
  51944. return this._highlightsDensity;
  51945. },
  51946. /**
  51947. * Sets the highlights Density value.
  51948. * 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.
  51949. * Values less than zero provide a filter of opposite hue.
  51950. */
  51951. set: function (value) {
  51952. this._highlightsDensity = value;
  51953. this._dirty = true;
  51954. },
  51955. enumerable: true,
  51956. configurable: true
  51957. });
  51958. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  51959. /**
  51960. * Gets the highlights Saturation value.
  51961. * 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.
  51962. */
  51963. get: function () {
  51964. return this._highlightsSaturation;
  51965. },
  51966. /**
  51967. * Sets the highlights Saturation value.
  51968. * 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.
  51969. */
  51970. set: function (value) {
  51971. this._highlightsSaturation = value;
  51972. this._dirty = true;
  51973. },
  51974. enumerable: true,
  51975. configurable: true
  51976. });
  51977. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  51978. /**
  51979. * Gets the highlights Exposure value.
  51980. * 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.
  51981. */
  51982. get: function () {
  51983. return this._highlightsExposure;
  51984. },
  51985. /**
  51986. * Sets the highlights Exposure value.
  51987. * 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.
  51988. */
  51989. set: function (value) {
  51990. this._highlightsExposure = value;
  51991. this._dirty = true;
  51992. },
  51993. enumerable: true,
  51994. configurable: true
  51995. });
  51996. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  51997. /**
  51998. * Gets the midtones Hue value.
  51999. * 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).
  52000. */
  52001. get: function () {
  52002. return this._midtonesHue;
  52003. },
  52004. /**
  52005. * Sets the midtones Hue value.
  52006. * 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).
  52007. */
  52008. set: function (value) {
  52009. this._midtonesHue = value;
  52010. this._dirty = true;
  52011. },
  52012. enumerable: true,
  52013. configurable: true
  52014. });
  52015. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  52016. /**
  52017. * Gets the midtones Density value.
  52018. * 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.
  52019. * Values less than zero provide a filter of opposite hue.
  52020. */
  52021. get: function () {
  52022. return this._midtonesDensity;
  52023. },
  52024. /**
  52025. * Sets the midtones Density value.
  52026. * 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.
  52027. * Values less than zero provide a filter of opposite hue.
  52028. */
  52029. set: function (value) {
  52030. this._midtonesDensity = value;
  52031. this._dirty = true;
  52032. },
  52033. enumerable: true,
  52034. configurable: true
  52035. });
  52036. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  52037. /**
  52038. * Gets the midtones Saturation value.
  52039. * 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.
  52040. */
  52041. get: function () {
  52042. return this._midtonesSaturation;
  52043. },
  52044. /**
  52045. * Sets the midtones Saturation value.
  52046. * 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.
  52047. */
  52048. set: function (value) {
  52049. this._midtonesSaturation = value;
  52050. this._dirty = true;
  52051. },
  52052. enumerable: true,
  52053. configurable: true
  52054. });
  52055. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  52056. /**
  52057. * Gets the midtones Exposure value.
  52058. * 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.
  52059. */
  52060. get: function () {
  52061. return this._midtonesExposure;
  52062. },
  52063. /**
  52064. * Sets the midtones Exposure value.
  52065. * 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.
  52066. */
  52067. set: function (value) {
  52068. this._midtonesExposure = value;
  52069. this._dirty = true;
  52070. },
  52071. enumerable: true,
  52072. configurable: true
  52073. });
  52074. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  52075. /**
  52076. * Gets the shadows Hue value.
  52077. * 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).
  52078. */
  52079. get: function () {
  52080. return this._shadowsHue;
  52081. },
  52082. /**
  52083. * Sets the shadows Hue value.
  52084. * 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).
  52085. */
  52086. set: function (value) {
  52087. this._shadowsHue = value;
  52088. this._dirty = true;
  52089. },
  52090. enumerable: true,
  52091. configurable: true
  52092. });
  52093. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  52094. /**
  52095. * Gets the shadows Density value.
  52096. * 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.
  52097. * Values less than zero provide a filter of opposite hue.
  52098. */
  52099. get: function () {
  52100. return this._shadowsDensity;
  52101. },
  52102. /**
  52103. * Sets the shadows Density value.
  52104. * 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.
  52105. * Values less than zero provide a filter of opposite hue.
  52106. */
  52107. set: function (value) {
  52108. this._shadowsDensity = value;
  52109. this._dirty = true;
  52110. },
  52111. enumerable: true,
  52112. configurable: true
  52113. });
  52114. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  52115. /**
  52116. * Gets the shadows Saturation value.
  52117. * 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.
  52118. */
  52119. get: function () {
  52120. return this._shadowsSaturation;
  52121. },
  52122. /**
  52123. * Sets the shadows Saturation value.
  52124. * 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.
  52125. */
  52126. set: function (value) {
  52127. this._shadowsSaturation = value;
  52128. this._dirty = true;
  52129. },
  52130. enumerable: true,
  52131. configurable: true
  52132. });
  52133. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  52134. /**
  52135. * Gets the shadows Exposure value.
  52136. * 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.
  52137. */
  52138. get: function () {
  52139. return this._shadowsExposure;
  52140. },
  52141. /**
  52142. * Sets the shadows Exposure value.
  52143. * 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.
  52144. */
  52145. set: function (value) {
  52146. this._shadowsExposure = value;
  52147. this._dirty = true;
  52148. },
  52149. enumerable: true,
  52150. configurable: true
  52151. });
  52152. /**
  52153. * Binds the color curves to the shader.
  52154. * @param colorCurves The color curve to bind
  52155. * @param effect The effect to bind to
  52156. */
  52157. ColorCurves.Bind = function (colorCurves, effect) {
  52158. if (colorCurves._dirty) {
  52159. colorCurves._dirty = false;
  52160. // Fill in global info.
  52161. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  52162. // Compute highlights info.
  52163. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  52164. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  52165. // Compute midtones info.
  52166. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  52167. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  52168. // Compute shadows info.
  52169. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  52170. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  52171. // Compute deltas (neutral is midtones).
  52172. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  52173. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  52174. }
  52175. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  52176. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  52177. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  52178. };
  52179. /**
  52180. * Prepare the list of uniforms associated with the ColorCurves effects.
  52181. * @param uniformsList The list of uniforms used in the effect
  52182. */
  52183. ColorCurves.PrepareUniforms = function (uniformsList) {
  52184. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  52185. };
  52186. /**
  52187. * Returns color grading data based on a hue, density, saturation and exposure value.
  52188. * @param filterHue The hue of the color filter.
  52189. * @param filterDensity The density of the color filter.
  52190. * @param saturation The saturation.
  52191. * @param exposure The exposure.
  52192. * @param result The result data container.
  52193. */
  52194. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  52195. if (hue == null) {
  52196. return;
  52197. }
  52198. hue = ColorCurves.clamp(hue, 0, 360);
  52199. density = ColorCurves.clamp(density, -100, 100);
  52200. saturation = ColorCurves.clamp(saturation, -100, 100);
  52201. exposure = ColorCurves.clamp(exposure, -100, 100);
  52202. // Remap the slider/config filter density with non-linear mapping and also scale by half
  52203. // so that the maximum filter density is only 50% control. This provides fine control
  52204. // for small values and reasonable range.
  52205. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  52206. density *= 0.5;
  52207. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  52208. if (density < 0) {
  52209. density *= -1;
  52210. hue = (hue + 180) % 360;
  52211. }
  52212. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  52213. result.scaleToRef(2, result);
  52214. result.a = 1 + 0.01 * saturation;
  52215. };
  52216. /**
  52217. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  52218. * @param value The input slider value in range [-100,100].
  52219. * @returns Adjusted value.
  52220. */
  52221. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  52222. value /= 100;
  52223. var x = Math.abs(value);
  52224. x = Math.pow(x, 2);
  52225. if (value < 0) {
  52226. x *= -1;
  52227. }
  52228. x *= 100;
  52229. return x;
  52230. };
  52231. /**
  52232. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  52233. * @param hue The hue (H) input.
  52234. * @param saturation The saturation (S) input.
  52235. * @param brightness The brightness (B) input.
  52236. * @result An RGBA color represented as Vector4.
  52237. */
  52238. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  52239. var h = ColorCurves.clamp(hue, 0, 360);
  52240. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  52241. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  52242. if (s === 0) {
  52243. result.r = v;
  52244. result.g = v;
  52245. result.b = v;
  52246. }
  52247. else {
  52248. // sector 0 to 5
  52249. h /= 60;
  52250. var i = Math.floor(h);
  52251. // fractional part of h
  52252. var f = h - i;
  52253. var p = v * (1 - s);
  52254. var q = v * (1 - s * f);
  52255. var t = v * (1 - s * (1 - f));
  52256. switch (i) {
  52257. case 0:
  52258. result.r = v;
  52259. result.g = t;
  52260. result.b = p;
  52261. break;
  52262. case 1:
  52263. result.r = q;
  52264. result.g = v;
  52265. result.b = p;
  52266. break;
  52267. case 2:
  52268. result.r = p;
  52269. result.g = v;
  52270. result.b = t;
  52271. break;
  52272. case 3:
  52273. result.r = p;
  52274. result.g = q;
  52275. result.b = v;
  52276. break;
  52277. case 4:
  52278. result.r = t;
  52279. result.g = p;
  52280. result.b = v;
  52281. break;
  52282. default:
  52283. result.r = v;
  52284. result.g = p;
  52285. result.b = q;
  52286. break;
  52287. }
  52288. }
  52289. result.a = 1;
  52290. };
  52291. /**
  52292. * Returns a value clamped between min and max
  52293. * @param value The value to clamp
  52294. * @param min The minimum of value
  52295. * @param max The maximum of value
  52296. * @returns The clamped value.
  52297. */
  52298. ColorCurves.clamp = function (value, min, max) {
  52299. return Math.min(Math.max(value, min), max);
  52300. };
  52301. /**
  52302. * Clones the current color curve instance.
  52303. * @return The cloned curves
  52304. */
  52305. ColorCurves.prototype.clone = function () {
  52306. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  52307. };
  52308. /**
  52309. * Serializes the current color curve instance to a json representation.
  52310. * @return a JSON representation
  52311. */
  52312. ColorCurves.prototype.serialize = function () {
  52313. return BABYLON.SerializationHelper.Serialize(this);
  52314. };
  52315. /**
  52316. * Parses the color curve from a json representation.
  52317. * @param source the JSON source to parse
  52318. * @return The parsed curves
  52319. */
  52320. ColorCurves.Parse = function (source) {
  52321. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  52322. };
  52323. __decorate([
  52324. BABYLON.serialize()
  52325. ], ColorCurves.prototype, "_globalHue", void 0);
  52326. __decorate([
  52327. BABYLON.serialize()
  52328. ], ColorCurves.prototype, "_globalDensity", void 0);
  52329. __decorate([
  52330. BABYLON.serialize()
  52331. ], ColorCurves.prototype, "_globalSaturation", void 0);
  52332. __decorate([
  52333. BABYLON.serialize()
  52334. ], ColorCurves.prototype, "_globalExposure", void 0);
  52335. __decorate([
  52336. BABYLON.serialize()
  52337. ], ColorCurves.prototype, "_highlightsHue", void 0);
  52338. __decorate([
  52339. BABYLON.serialize()
  52340. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  52341. __decorate([
  52342. BABYLON.serialize()
  52343. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  52344. __decorate([
  52345. BABYLON.serialize()
  52346. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  52347. __decorate([
  52348. BABYLON.serialize()
  52349. ], ColorCurves.prototype, "_midtonesHue", void 0);
  52350. __decorate([
  52351. BABYLON.serialize()
  52352. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  52353. __decorate([
  52354. BABYLON.serialize()
  52355. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  52356. __decorate([
  52357. BABYLON.serialize()
  52358. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  52359. return ColorCurves;
  52360. }());
  52361. BABYLON.ColorCurves = ColorCurves;
  52362. })(BABYLON || (BABYLON = {}));
  52363. //# sourceMappingURL=../Materials/babylon.colorCurves.js.map
  52364. var BABYLON;
  52365. (function (BABYLON) {
  52366. var PBRMaterialDefines = (function (_super) {
  52367. __extends(PBRMaterialDefines, _super);
  52368. function PBRMaterialDefines() {
  52369. _super.call(this);
  52370. this.ALBEDO = false;
  52371. this.AMBIENT = false;
  52372. this.OPACITY = false;
  52373. this.OPACITYRGB = false;
  52374. this.REFLECTION = false;
  52375. this.EMISSIVE = false;
  52376. this.REFLECTIVITY = false;
  52377. this.BUMP = false;
  52378. this.PARALLAX = false;
  52379. this.PARALLAXOCCLUSION = false;
  52380. this.SPECULAROVERALPHA = false;
  52381. this.CLIPPLANE = false;
  52382. this.ALPHATEST = false;
  52383. this.ALPHAFROMALBEDO = false;
  52384. this.POINTSIZE = false;
  52385. this.FOG = false;
  52386. this.SPECULARTERM = false;
  52387. this.OPACITYFRESNEL = false;
  52388. this.EMISSIVEFRESNEL = false;
  52389. this.FRESNEL = false;
  52390. this.NORMAL = false;
  52391. this.UV1 = false;
  52392. this.UV2 = false;
  52393. this.VERTEXCOLOR = false;
  52394. this.VERTEXALPHA = false;
  52395. this.NUM_BONE_INFLUENCERS = 0;
  52396. this.BonesPerMesh = 0;
  52397. this.INSTANCES = false;
  52398. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  52399. this.MICROSURFACEAUTOMATIC = false;
  52400. this.EMISSIVEASILLUMINATION = false;
  52401. this.LINKEMISSIVEWITHALBEDO = false;
  52402. this.LIGHTMAP = false;
  52403. this.USELIGHTMAPASSHADOWMAP = false;
  52404. this.REFLECTIONMAP_3D = false;
  52405. this.REFLECTIONMAP_SPHERICAL = false;
  52406. this.REFLECTIONMAP_PLANAR = false;
  52407. this.REFLECTIONMAP_CUBIC = false;
  52408. this.REFLECTIONMAP_PROJECTION = false;
  52409. this.REFLECTIONMAP_SKYBOX = false;
  52410. this.REFLECTIONMAP_EXPLICIT = false;
  52411. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  52412. this.INVERTCUBICMAP = false;
  52413. this.LOGARITHMICDEPTH = false;
  52414. this.CAMERATONEMAP = false;
  52415. this.CAMERACONTRAST = false;
  52416. this.CAMERACOLORGRADING = false;
  52417. this.CAMERACOLORCURVES = false;
  52418. this.OVERLOADEDVALUES = false;
  52419. this.OVERLOADEDSHADOWVALUES = false;
  52420. this.USESPHERICALFROMREFLECTIONMAP = false;
  52421. this.REFRACTION = false;
  52422. this.REFRACTIONMAP_3D = false;
  52423. this.LINKREFRACTIONTOTRANSPARENCY = false;
  52424. this.REFRACTIONMAPINLINEARSPACE = false;
  52425. this.LODBASEDMICROSFURACE = false;
  52426. this.USEPHYSICALLIGHTFALLOFF = false;
  52427. this.RADIANCEOVERALPHA = false;
  52428. this.USEPMREMREFLECTION = false;
  52429. this.USEPMREMREFRACTION = false;
  52430. this.OPENGLNORMALMAP = false;
  52431. this.INVERTNORMALMAPX = false;
  52432. this.INVERTNORMALMAPY = false;
  52433. this.SHADOWFULLFLOAT = false;
  52434. this.rebuild();
  52435. }
  52436. return PBRMaterialDefines;
  52437. }(BABYLON.MaterialDefines));
  52438. /**
  52439. * The Physically based material of BJS.
  52440. *
  52441. * This offers the main features of a standard PBR material.
  52442. * For more information, please refer to the documentation :
  52443. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  52444. */
  52445. var PBRMaterial = (function (_super) {
  52446. __extends(PBRMaterial, _super);
  52447. /**
  52448. * Instantiates a new PBRMaterial instance.
  52449. *
  52450. * @param name The material name
  52451. * @param scene The scene the material will be use in.
  52452. */
  52453. function PBRMaterial(name, scene) {
  52454. var _this = this;
  52455. _super.call(this, name, scene);
  52456. /**
  52457. * Intensity of the direct lights e.g. the four lights available in your scene.
  52458. * This impacts both the direct diffuse and specular highlights.
  52459. */
  52460. this.directIntensity = 1.0;
  52461. /**
  52462. * Intensity of the emissive part of the material.
  52463. * This helps controlling the emissive effect without modifying the emissive color.
  52464. */
  52465. this.emissiveIntensity = 1.0;
  52466. /**
  52467. * Intensity of the environment e.g. how much the environment will light the object
  52468. * either through harmonics for rough material or through the refelction for shiny ones.
  52469. */
  52470. this.environmentIntensity = 1.0;
  52471. /**
  52472. * This is a special control allowing the reduction of the specular highlights coming from the
  52473. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  52474. */
  52475. this.specularIntensity = 1.0;
  52476. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  52477. /**
  52478. * Debug Control allowing disabling the bump map on this material.
  52479. */
  52480. this.disableBumpMap = false;
  52481. /**
  52482. * Debug Control helping enforcing or dropping the darkness of shadows.
  52483. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  52484. */
  52485. this.overloadedShadowIntensity = 1.0;
  52486. /**
  52487. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  52488. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  52489. */
  52490. this.overloadedShadeIntensity = 1.0;
  52491. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  52492. /**
  52493. * The camera exposure used on this material.
  52494. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  52495. * This corresponds to a photographic exposure.
  52496. */
  52497. this.cameraExposure = 1.0;
  52498. /**
  52499. * The camera contrast used on this material.
  52500. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  52501. */
  52502. this.cameraContrast = 1.0;
  52503. /**
  52504. * Color Grading 2D Lookup Texture.
  52505. * This allows special effects like sepia, black and white to sixties rendering style.
  52506. */
  52507. this.cameraColorGradingTexture = null;
  52508. /**
  52509. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  52510. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  52511. * 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;
  52512. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  52513. */
  52514. this.cameraColorCurves = null;
  52515. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  52516. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  52517. /**
  52518. * Debug Control allowing to overload the ambient color.
  52519. * This as to be use with the overloadedAmbientIntensity parameter.
  52520. */
  52521. this.overloadedAmbient = BABYLON.Color3.White();
  52522. /**
  52523. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  52524. */
  52525. this.overloadedAmbientIntensity = 0.0;
  52526. /**
  52527. * Debug Control allowing to overload the albedo color.
  52528. * This as to be use with the overloadedAlbedoIntensity parameter.
  52529. */
  52530. this.overloadedAlbedo = BABYLON.Color3.White();
  52531. /**
  52532. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  52533. */
  52534. this.overloadedAlbedoIntensity = 0.0;
  52535. /**
  52536. * Debug Control allowing to overload the reflectivity color.
  52537. * This as to be use with the overloadedReflectivityIntensity parameter.
  52538. */
  52539. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  52540. /**
  52541. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  52542. */
  52543. this.overloadedReflectivityIntensity = 0.0;
  52544. /**
  52545. * Debug Control allowing to overload the emissive color.
  52546. * This as to be use with the overloadedEmissiveIntensity parameter.
  52547. */
  52548. this.overloadedEmissive = BABYLON.Color3.White();
  52549. /**
  52550. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  52551. */
  52552. this.overloadedEmissiveIntensity = 0.0;
  52553. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  52554. /**
  52555. * Debug Control allowing to overload the reflection color.
  52556. * This as to be use with the overloadedReflectionIntensity parameter.
  52557. */
  52558. this.overloadedReflection = BABYLON.Color3.White();
  52559. /**
  52560. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  52561. */
  52562. this.overloadedReflectionIntensity = 0.0;
  52563. /**
  52564. * Debug Control allowing to overload the microsurface.
  52565. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  52566. */
  52567. this.overloadedMicroSurface = 0.0;
  52568. /**
  52569. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  52570. */
  52571. this.overloadedMicroSurfaceIntensity = 0.0;
  52572. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  52573. /**
  52574. * AKA Occlusion Texture Intensity in other nomenclature.
  52575. */
  52576. this.ambientTextureStrength = 1.0;
  52577. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  52578. /**
  52579. * AKA Diffuse Color in other nomenclature.
  52580. */
  52581. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  52582. /**
  52583. * AKA Specular Color in other nomenclature.
  52584. */
  52585. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  52586. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  52587. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  52588. /**
  52589. * AKA Glossiness in other nomenclature.
  52590. */
  52591. this.microSurface = 0.9;
  52592. /**
  52593. * source material index of refraction (IOR)' / 'destination material IOR.
  52594. */
  52595. this.indexOfRefraction = 0.66;
  52596. /**
  52597. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  52598. */
  52599. this.invertRefractionY = false;
  52600. /**
  52601. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  52602. * Materials half opaque for instance using refraction could benefit from this control.
  52603. */
  52604. this.linkRefractionWithTransparency = false;
  52605. /**
  52606. * The emissive and albedo are linked to never be more than one (Energy conservation).
  52607. */
  52608. this.linkEmissiveWithAlbedo = false;
  52609. this.useLightmapAsShadowmap = false;
  52610. /**
  52611. * In this mode, the emissive informtaion will always be added to the lighting once.
  52612. * A light for instance can be thought as emissive.
  52613. */
  52614. this.useEmissiveAsIllumination = false;
  52615. /**
  52616. * Secifies that the alpha is coming form the albedo channel alpha channel.
  52617. */
  52618. this.useAlphaFromAlbedoTexture = false;
  52619. /**
  52620. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  52621. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  52622. */
  52623. this.useSpecularOverAlpha = true;
  52624. /**
  52625. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  52626. */
  52627. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  52628. /**
  52629. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  52630. * The material will try to infer what glossiness each pixel should be.
  52631. */
  52632. this.useAutoMicroSurfaceFromReflectivityMap = false;
  52633. /**
  52634. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  52635. * the creation of the material.
  52636. */
  52637. this.useScalarInLinearSpace = false;
  52638. /**
  52639. * BJS is using an harcoded light falloff based on a manually sets up range.
  52640. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  52641. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  52642. */
  52643. this.usePhysicalLightFalloff = true;
  52644. /**
  52645. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  52646. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  52647. */
  52648. this.useRadianceOverAlpha = true;
  52649. /**
  52650. * Allows using the bump map in parallax mode.
  52651. */
  52652. this.useParallax = false;
  52653. /**
  52654. * Allows using the bump map in parallax occlusion mode.
  52655. */
  52656. this.useParallaxOcclusion = false;
  52657. /**
  52658. * Controls the scale bias of the parallax mode.
  52659. */
  52660. this.parallaxScaleBias = 0.05;
  52661. /**
  52662. * If sets to true, disables all the lights affecting the material.
  52663. */
  52664. this.disableLighting = false;
  52665. /**
  52666. * Number of Simultaneous lights allowed on the material.
  52667. */
  52668. this.maxSimultaneousLights = 4;
  52669. /**
  52670. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  52671. */
  52672. this.invertNormalMapX = false;
  52673. /**
  52674. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  52675. */
  52676. this.invertNormalMapY = false;
  52677. this._renderTargets = new BABYLON.SmartArray(16);
  52678. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  52679. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  52680. this._tempColor = new BABYLON.Color3();
  52681. this._defines = new PBRMaterialDefines();
  52682. this._cachedDefines = new PBRMaterialDefines();
  52683. this._myScene = null;
  52684. this._myShadowGenerator = null;
  52685. this._cachedDefines.BonesPerMesh = -1;
  52686. this.getRenderTargetTextures = function () {
  52687. _this._renderTargets.reset();
  52688. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  52689. _this._renderTargets.push(_this.reflectionTexture);
  52690. }
  52691. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  52692. _this._renderTargets.push(_this.refractionTexture);
  52693. }
  52694. return _this._renderTargets;
  52695. };
  52696. }
  52697. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  52698. get: function () {
  52699. return this._useLogarithmicDepth;
  52700. },
  52701. set: function (value) {
  52702. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  52703. },
  52704. enumerable: true,
  52705. configurable: true
  52706. });
  52707. PBRMaterial.prototype.needAlphaBlending = function () {
  52708. if (this.linkRefractionWithTransparency) {
  52709. return false;
  52710. }
  52711. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  52712. };
  52713. PBRMaterial.prototype.needAlphaTesting = function () {
  52714. if (this.linkRefractionWithTransparency) {
  52715. return false;
  52716. }
  52717. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  52718. };
  52719. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  52720. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  52721. };
  52722. PBRMaterial.prototype.getAlphaTestTexture = function () {
  52723. return this.albedoTexture;
  52724. };
  52725. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  52726. if (!mesh) {
  52727. return true;
  52728. }
  52729. if (this._defines.INSTANCES !== useInstances) {
  52730. return false;
  52731. }
  52732. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  52733. return true;
  52734. }
  52735. return false;
  52736. };
  52737. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  52738. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  52739. };
  52740. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  52741. if (!useScalarInLinear) {
  52742. color.toLinearSpaceToRef(ref);
  52743. }
  52744. else {
  52745. ref.r = color.r;
  52746. ref.g = color.g;
  52747. ref.b = color.b;
  52748. }
  52749. };
  52750. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  52751. var lightIndex = 0;
  52752. var depthValuesAlreadySet = false;
  52753. for (var index = 0; index < scene.lights.length; index++) {
  52754. var light = scene.lights[index];
  52755. if (!light.isEnabled()) {
  52756. continue;
  52757. }
  52758. if (!light.canAffectMesh(mesh)) {
  52759. continue;
  52760. }
  52761. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  52762. // GAMMA CORRECTION.
  52763. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  52764. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  52765. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  52766. if (defines["SPECULARTERM"]) {
  52767. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  52768. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  52769. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  52770. }
  52771. // Shadows
  52772. if (scene.shadowsEnabled) {
  52773. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  52774. }
  52775. lightIndex++;
  52776. if (lightIndex === maxSimultaneousLights)
  52777. break;
  52778. }
  52779. };
  52780. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  52781. if (this.checkReadyOnlyOnce) {
  52782. if (this._wasPreviouslyReady) {
  52783. return true;
  52784. }
  52785. }
  52786. var scene = this.getScene();
  52787. var engine = scene.getEngine();
  52788. var needNormals = false;
  52789. var needUVs = false;
  52790. this._defines.reset();
  52791. if (scene.lightsEnabled && !this.disableLighting) {
  52792. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  52793. }
  52794. if (!this.checkReadyOnEveryCall) {
  52795. if (this._renderId === scene.getRenderId()) {
  52796. if (this._checkCache(scene, mesh, useInstances)) {
  52797. return true;
  52798. }
  52799. }
  52800. }
  52801. if (scene.texturesEnabled) {
  52802. if (scene.getEngine().getCaps().textureLOD) {
  52803. this._defines.LODBASEDMICROSFURACE = true;
  52804. }
  52805. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  52806. if (!this.albedoTexture.isReady()) {
  52807. return false;
  52808. }
  52809. else {
  52810. needUVs = true;
  52811. this._defines.ALBEDO = true;
  52812. }
  52813. }
  52814. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  52815. if (!this.ambientTexture.isReady()) {
  52816. return false;
  52817. }
  52818. else {
  52819. needUVs = true;
  52820. this._defines.AMBIENT = true;
  52821. }
  52822. }
  52823. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  52824. if (!this.opacityTexture.isReady()) {
  52825. return false;
  52826. }
  52827. else {
  52828. needUVs = true;
  52829. this._defines.OPACITY = true;
  52830. if (this.opacityTexture.getAlphaFromRGB) {
  52831. this._defines.OPACITYRGB = true;
  52832. }
  52833. }
  52834. }
  52835. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  52836. if (!this.reflectionTexture.isReady()) {
  52837. return false;
  52838. }
  52839. else {
  52840. needNormals = true;
  52841. this._defines.REFLECTION = true;
  52842. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  52843. this._defines.INVERTCUBICMAP = true;
  52844. }
  52845. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  52846. switch (this.reflectionTexture.coordinatesMode) {
  52847. case BABYLON.Texture.CUBIC_MODE:
  52848. case BABYLON.Texture.INVCUBIC_MODE:
  52849. this._defines.REFLECTIONMAP_CUBIC = true;
  52850. break;
  52851. case BABYLON.Texture.EXPLICIT_MODE:
  52852. this._defines.REFLECTIONMAP_EXPLICIT = true;
  52853. break;
  52854. case BABYLON.Texture.PLANAR_MODE:
  52855. this._defines.REFLECTIONMAP_PLANAR = true;
  52856. break;
  52857. case BABYLON.Texture.PROJECTION_MODE:
  52858. this._defines.REFLECTIONMAP_PROJECTION = true;
  52859. break;
  52860. case BABYLON.Texture.SKYBOX_MODE:
  52861. this._defines.REFLECTIONMAP_SKYBOX = true;
  52862. break;
  52863. case BABYLON.Texture.SPHERICAL_MODE:
  52864. this._defines.REFLECTIONMAP_SPHERICAL = true;
  52865. break;
  52866. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  52867. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  52868. break;
  52869. }
  52870. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  52871. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  52872. needNormals = true;
  52873. if (this.reflectionTexture.isPMREM) {
  52874. this._defines.USEPMREMREFLECTION = true;
  52875. }
  52876. }
  52877. }
  52878. }
  52879. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  52880. if (!this.lightmapTexture.isReady()) {
  52881. return false;
  52882. }
  52883. else {
  52884. needUVs = true;
  52885. this._defines.LIGHTMAP = true;
  52886. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  52887. }
  52888. }
  52889. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  52890. if (!this.emissiveTexture.isReady()) {
  52891. return false;
  52892. }
  52893. else {
  52894. needUVs = true;
  52895. this._defines.EMISSIVE = true;
  52896. }
  52897. }
  52898. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  52899. if (!this.reflectivityTexture.isReady()) {
  52900. return false;
  52901. }
  52902. else {
  52903. needUVs = true;
  52904. this._defines.REFLECTIVITY = true;
  52905. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  52906. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  52907. }
  52908. }
  52909. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  52910. if (!this.bumpTexture.isReady()) {
  52911. return false;
  52912. }
  52913. else {
  52914. needUVs = true;
  52915. this._defines.BUMP = true;
  52916. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  52917. this._defines.PARALLAX = true;
  52918. if (this.useParallaxOcclusion) {
  52919. this._defines.PARALLAXOCCLUSION = true;
  52920. }
  52921. }
  52922. if (this.invertNormalMapX) {
  52923. this._defines.INVERTNORMALMAPX = true;
  52924. }
  52925. if (this.invertNormalMapY) {
  52926. this._defines.INVERTNORMALMAPY = true;
  52927. }
  52928. }
  52929. }
  52930. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  52931. if (!this.refractionTexture.isReady()) {
  52932. return false;
  52933. }
  52934. else {
  52935. needUVs = true;
  52936. this._defines.REFRACTION = true;
  52937. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  52938. if (this.linkRefractionWithTransparency) {
  52939. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  52940. }
  52941. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  52942. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  52943. if (this.refractionTexture.isPMREM) {
  52944. this._defines.USEPMREMREFRACTION = true;
  52945. }
  52946. }
  52947. }
  52948. }
  52949. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  52950. if (!this.cameraColorGradingTexture.isReady()) {
  52951. return false;
  52952. }
  52953. else {
  52954. this._defines.CAMERACOLORGRADING = true;
  52955. }
  52956. }
  52957. }
  52958. // Effect
  52959. if (scene.clipPlane) {
  52960. this._defines.CLIPPLANE = true;
  52961. }
  52962. if (engine.getAlphaTesting()) {
  52963. this._defines.ALPHATEST = true;
  52964. }
  52965. if (this._shouldUseAlphaFromAlbedoTexture()) {
  52966. this._defines.ALPHAFROMALBEDO = true;
  52967. }
  52968. if (this.useEmissiveAsIllumination) {
  52969. this._defines.EMISSIVEASILLUMINATION = true;
  52970. }
  52971. if (this.linkEmissiveWithAlbedo) {
  52972. this._defines.LINKEMISSIVEWITHALBEDO = true;
  52973. }
  52974. if (this.useLogarithmicDepth) {
  52975. this._defines.LOGARITHMICDEPTH = true;
  52976. }
  52977. if (this.cameraContrast != 1) {
  52978. this._defines.CAMERACONTRAST = true;
  52979. }
  52980. if (this.cameraExposure != 1) {
  52981. this._defines.CAMERATONEMAP = true;
  52982. }
  52983. if (this.cameraColorCurves) {
  52984. this._defines.CAMERACOLORCURVES = true;
  52985. }
  52986. if (this.overloadedShadeIntensity != 1 ||
  52987. this.overloadedShadowIntensity != 1) {
  52988. this._defines.OVERLOADEDSHADOWVALUES = true;
  52989. }
  52990. if (this.overloadedMicroSurfaceIntensity > 0 ||
  52991. this.overloadedEmissiveIntensity > 0 ||
  52992. this.overloadedReflectivityIntensity > 0 ||
  52993. this.overloadedAlbedoIntensity > 0 ||
  52994. this.overloadedAmbientIntensity > 0 ||
  52995. this.overloadedReflectionIntensity > 0) {
  52996. this._defines.OVERLOADEDVALUES = true;
  52997. }
  52998. // Point size
  52999. if (this.pointsCloud || scene.forcePointsCloud) {
  53000. this._defines.POINTSIZE = true;
  53001. }
  53002. // Fog
  53003. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53004. this._defines.FOG = true;
  53005. }
  53006. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53007. // Fresnel
  53008. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  53009. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53010. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53011. this._defines.OPACITYFRESNEL = true;
  53012. }
  53013. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53014. this._defines.EMISSIVEFRESNEL = true;
  53015. }
  53016. needNormals = true;
  53017. this._defines.FRESNEL = true;
  53018. }
  53019. }
  53020. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  53021. this._defines.SPECULAROVERALPHA = true;
  53022. }
  53023. if (this.usePhysicalLightFalloff) {
  53024. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  53025. }
  53026. if (this.useRadianceOverAlpha) {
  53027. this._defines.RADIANCEOVERALPHA = true;
  53028. }
  53029. // Attribs
  53030. if (mesh) {
  53031. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53032. this._defines.NORMAL = true;
  53033. }
  53034. if (needUVs) {
  53035. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53036. this._defines.UV1 = true;
  53037. }
  53038. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53039. this._defines.UV2 = true;
  53040. }
  53041. }
  53042. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53043. this._defines.VERTEXCOLOR = true;
  53044. if (mesh.hasVertexAlpha) {
  53045. this._defines.VERTEXALPHA = true;
  53046. }
  53047. }
  53048. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53049. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  53050. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  53051. }
  53052. // Instances
  53053. if (useInstances) {
  53054. this._defines.INSTANCES = true;
  53055. }
  53056. }
  53057. // Get correct effect
  53058. if (!this._defines.isEqual(this._cachedDefines)) {
  53059. this._defines.cloneTo(this._cachedDefines);
  53060. scene.resetCachedMaterial();
  53061. // Fallbacks
  53062. var fallbacks = new BABYLON.EffectFallbacks();
  53063. if (this._defines.REFLECTION) {
  53064. fallbacks.addFallback(0, "REFLECTION");
  53065. }
  53066. if (this._defines.REFRACTION) {
  53067. fallbacks.addFallback(0, "REFRACTION");
  53068. }
  53069. if (this._defines.REFLECTIVITY) {
  53070. fallbacks.addFallback(0, "REFLECTIVITY");
  53071. }
  53072. if (this._defines.BUMP) {
  53073. fallbacks.addFallback(0, "BUMP");
  53074. }
  53075. if (this._defines.PARALLAX) {
  53076. fallbacks.addFallback(1, "PARALLAX");
  53077. }
  53078. if (this._defines.PARALLAXOCCLUSION) {
  53079. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  53080. }
  53081. if (this._defines.SPECULAROVERALPHA) {
  53082. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  53083. }
  53084. if (this._defines.FOG) {
  53085. fallbacks.addFallback(1, "FOG");
  53086. }
  53087. if (this._defines.POINTSIZE) {
  53088. fallbacks.addFallback(0, "POINTSIZE");
  53089. }
  53090. if (this._defines.LOGARITHMICDEPTH) {
  53091. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  53092. }
  53093. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  53094. if (this._defines.SPECULARTERM) {
  53095. fallbacks.addFallback(0, "SPECULARTERM");
  53096. }
  53097. if (this._defines.OPACITYFRESNEL) {
  53098. fallbacks.addFallback(1, "OPACITYFRESNEL");
  53099. }
  53100. if (this._defines.EMISSIVEFRESNEL) {
  53101. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  53102. }
  53103. if (this._defines.FRESNEL) {
  53104. fallbacks.addFallback(3, "FRESNEL");
  53105. }
  53106. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  53107. fallbacks.addCPUSkinningFallback(0, mesh);
  53108. }
  53109. //Attributes
  53110. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53111. if (this._defines.NORMAL) {
  53112. attribs.push(BABYLON.VertexBuffer.NormalKind);
  53113. }
  53114. if (this._defines.UV1) {
  53115. attribs.push(BABYLON.VertexBuffer.UVKind);
  53116. }
  53117. if (this._defines.UV2) {
  53118. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53119. }
  53120. if (this._defines.VERTEXCOLOR) {
  53121. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53122. }
  53123. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  53124. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  53125. // Legacy browser patch
  53126. var join = this._defines.toString();
  53127. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  53128. "vFogInfos", "vFogColor", "pointSize",
  53129. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  53130. "mBones",
  53131. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  53132. "depthValues",
  53133. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  53134. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  53135. "logarithmicDepthConstant",
  53136. "vSphericalX", "vSphericalY", "vSphericalZ",
  53137. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  53138. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  53139. "vMicrosurfaceTextureLods",
  53140. "vCameraInfos"
  53141. ];
  53142. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  53143. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  53144. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  53145. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  53146. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  53147. }
  53148. if (!this._effect.isReady()) {
  53149. return false;
  53150. }
  53151. this._renderId = scene.getRenderId();
  53152. this._wasPreviouslyReady = true;
  53153. if (mesh) {
  53154. if (!mesh._materialDefines) {
  53155. mesh._materialDefines = new PBRMaterialDefines();
  53156. }
  53157. this._defines.cloneTo(mesh._materialDefines);
  53158. }
  53159. return true;
  53160. };
  53161. PBRMaterial.prototype.unbind = function () {
  53162. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  53163. this._effect.setTexture("reflection2DSampler", null);
  53164. }
  53165. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  53166. this._effect.setTexture("refraction2DSampler", null);
  53167. }
  53168. _super.prototype.unbind.call(this);
  53169. };
  53170. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53171. this._effect.setMatrix("world", world);
  53172. };
  53173. PBRMaterial.prototype.bind = function (world, mesh) {
  53174. this._myScene = this.getScene();
  53175. // Matrices
  53176. this.bindOnlyWorldMatrix(world);
  53177. // Bones
  53178. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53179. if (this._myScene.getCachedMaterial() !== this) {
  53180. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  53181. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53182. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53183. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  53184. }
  53185. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53186. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  53187. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  53188. }
  53189. }
  53190. // Textures
  53191. if (this._myScene.texturesEnabled) {
  53192. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53193. this._effect.setTexture("albedoSampler", this.albedoTexture);
  53194. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  53195. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  53196. }
  53197. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  53198. this._effect.setTexture("ambientSampler", this.ambientTexture);
  53199. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  53200. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  53201. }
  53202. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  53203. this._effect.setTexture("opacitySampler", this.opacityTexture);
  53204. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  53205. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  53206. }
  53207. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  53208. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  53209. if (this.reflectionTexture.isCube) {
  53210. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  53211. }
  53212. else {
  53213. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  53214. }
  53215. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  53216. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  53217. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  53218. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  53219. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  53220. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  53221. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  53222. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  53223. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  53224. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  53225. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  53226. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  53227. }
  53228. }
  53229. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  53230. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  53231. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  53232. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  53233. }
  53234. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  53235. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  53236. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  53237. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  53238. }
  53239. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  53240. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  53241. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  53242. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  53243. }
  53244. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  53245. this._effect.setTexture("bumpSampler", this.bumpTexture);
  53246. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  53247. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  53248. }
  53249. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  53250. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  53251. var depth = 1.0;
  53252. if (this.refractionTexture.isCube) {
  53253. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  53254. }
  53255. else {
  53256. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  53257. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  53258. if (this.refractionTexture.depth) {
  53259. depth = this.refractionTexture.depth;
  53260. }
  53261. }
  53262. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  53263. }
  53264. if ((this.reflectionTexture || this.refractionTexture)) {
  53265. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  53266. }
  53267. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  53268. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  53269. }
  53270. }
  53271. // Clip plane
  53272. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  53273. // Point size
  53274. if (this.pointsCloud) {
  53275. this._effect.setFloat("pointSize", this.pointSize);
  53276. }
  53277. // Colors
  53278. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  53279. // GAMMA CORRECTION.
  53280. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  53281. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  53282. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  53283. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  53284. // GAMMA CORRECTION.
  53285. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  53286. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  53287. // GAMMA CORRECTION.
  53288. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  53289. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  53290. }
  53291. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  53292. // GAMMA CORRECTION.
  53293. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  53294. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  53295. // Lights
  53296. if (this._myScene.lightsEnabled && !this.disableLighting) {
  53297. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  53298. }
  53299. // View
  53300. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  53301. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  53302. }
  53303. // Fog
  53304. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  53305. this._lightingInfos.x = this.directIntensity;
  53306. this._lightingInfos.y = this.emissiveIntensity;
  53307. this._lightingInfos.z = this.environmentIntensity;
  53308. this._lightingInfos.w = this.specularIntensity;
  53309. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  53310. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  53311. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  53312. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  53313. this._cameraInfos.x = this.cameraExposure;
  53314. this._cameraInfos.y = this.cameraContrast;
  53315. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  53316. if (this.cameraColorCurves) {
  53317. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  53318. }
  53319. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  53320. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  53321. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  53322. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  53323. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  53324. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  53325. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  53326. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  53327. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  53328. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  53329. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  53330. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  53331. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  53332. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  53333. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  53334. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  53335. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  53336. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  53337. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  53338. // Log. depth
  53339. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  53340. }
  53341. _super.prototype.bind.call(this, world, mesh);
  53342. this._myScene = null;
  53343. };
  53344. PBRMaterial.prototype.getAnimatables = function () {
  53345. var results = [];
  53346. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  53347. results.push(this.albedoTexture);
  53348. }
  53349. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  53350. results.push(this.ambientTexture);
  53351. }
  53352. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  53353. results.push(this.opacityTexture);
  53354. }
  53355. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  53356. results.push(this.reflectionTexture);
  53357. }
  53358. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  53359. results.push(this.emissiveTexture);
  53360. }
  53361. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  53362. results.push(this.reflectivityTexture);
  53363. }
  53364. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  53365. results.push(this.bumpTexture);
  53366. }
  53367. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  53368. results.push(this.lightmapTexture);
  53369. }
  53370. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  53371. results.push(this.refractionTexture);
  53372. }
  53373. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  53374. results.push(this.cameraColorGradingTexture);
  53375. }
  53376. return results;
  53377. };
  53378. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53379. if (forceDisposeTextures) {
  53380. if (this.albedoTexture) {
  53381. this.albedoTexture.dispose();
  53382. }
  53383. if (this.ambientTexture) {
  53384. this.ambientTexture.dispose();
  53385. }
  53386. if (this.opacityTexture) {
  53387. this.opacityTexture.dispose();
  53388. }
  53389. if (this.reflectionTexture) {
  53390. this.reflectionTexture.dispose();
  53391. }
  53392. if (this.emissiveTexture) {
  53393. this.emissiveTexture.dispose();
  53394. }
  53395. if (this.reflectivityTexture) {
  53396. this.reflectivityTexture.dispose();
  53397. }
  53398. if (this.bumpTexture) {
  53399. this.bumpTexture.dispose();
  53400. }
  53401. if (this.lightmapTexture) {
  53402. this.lightmapTexture.dispose();
  53403. }
  53404. if (this.refractionTexture) {
  53405. this.refractionTexture.dispose();
  53406. }
  53407. if (this.cameraColorGradingTexture) {
  53408. this.cameraColorGradingTexture.dispose();
  53409. }
  53410. }
  53411. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53412. };
  53413. PBRMaterial.prototype.clone = function (name) {
  53414. var _this = this;
  53415. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  53416. };
  53417. PBRMaterial.prototype.serialize = function () {
  53418. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53419. serializationObject.customType = "BABYLON.PBRMaterial";
  53420. return serializationObject;
  53421. };
  53422. // Statics
  53423. PBRMaterial.Parse = function (source, scene, rootUrl) {
  53424. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  53425. };
  53426. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  53427. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  53428. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  53429. PBRMaterial._scaledReflection = new BABYLON.Color3();
  53430. __decorate([
  53431. BABYLON.serialize()
  53432. ], PBRMaterial.prototype, "directIntensity", void 0);
  53433. __decorate([
  53434. BABYLON.serialize()
  53435. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  53436. __decorate([
  53437. BABYLON.serialize()
  53438. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  53439. __decorate([
  53440. BABYLON.serialize()
  53441. ], PBRMaterial.prototype, "specularIntensity", void 0);
  53442. __decorate([
  53443. BABYLON.serialize()
  53444. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  53445. __decorate([
  53446. BABYLON.serialize()
  53447. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  53448. __decorate([
  53449. BABYLON.serialize()
  53450. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  53451. __decorate([
  53452. BABYLON.serialize()
  53453. ], PBRMaterial.prototype, "cameraExposure", void 0);
  53454. __decorate([
  53455. BABYLON.serialize()
  53456. ], PBRMaterial.prototype, "cameraContrast", void 0);
  53457. __decorate([
  53458. BABYLON.serializeAsTexture()
  53459. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  53460. __decorate([
  53461. BABYLON.serializeAsColorCurves()
  53462. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  53463. __decorate([
  53464. BABYLON.serializeAsColor3()
  53465. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  53466. __decorate([
  53467. BABYLON.serialize()
  53468. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  53469. __decorate([
  53470. BABYLON.serializeAsColor3()
  53471. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  53472. __decorate([
  53473. BABYLON.serialize()
  53474. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  53475. __decorate([
  53476. BABYLON.serializeAsColor3()
  53477. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  53478. __decorate([
  53479. BABYLON.serialize()
  53480. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  53481. __decorate([
  53482. BABYLON.serializeAsColor3()
  53483. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  53484. __decorate([
  53485. BABYLON.serialize()
  53486. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  53487. __decorate([
  53488. BABYLON.serializeAsColor3()
  53489. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  53490. __decorate([
  53491. BABYLON.serialize()
  53492. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  53493. __decorate([
  53494. BABYLON.serialize()
  53495. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  53496. __decorate([
  53497. BABYLON.serialize()
  53498. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  53499. __decorate([
  53500. BABYLON.serializeAsTexture()
  53501. ], PBRMaterial.prototype, "albedoTexture", void 0);
  53502. __decorate([
  53503. BABYLON.serializeAsTexture()
  53504. ], PBRMaterial.prototype, "ambientTexture", void 0);
  53505. __decorate([
  53506. BABYLON.serialize()
  53507. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  53508. __decorate([
  53509. BABYLON.serializeAsTexture()
  53510. ], PBRMaterial.prototype, "opacityTexture", void 0);
  53511. __decorate([
  53512. BABYLON.serializeAsTexture()
  53513. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  53514. __decorate([
  53515. BABYLON.serializeAsTexture()
  53516. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  53517. __decorate([
  53518. BABYLON.serializeAsTexture()
  53519. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  53520. __decorate([
  53521. BABYLON.serializeAsTexture()
  53522. ], PBRMaterial.prototype, "bumpTexture", void 0);
  53523. __decorate([
  53524. BABYLON.serializeAsTexture()
  53525. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  53526. __decorate([
  53527. BABYLON.serializeAsTexture()
  53528. ], PBRMaterial.prototype, "refractionTexture", void 0);
  53529. __decorate([
  53530. BABYLON.serializeAsColor3("ambient")
  53531. ], PBRMaterial.prototype, "ambientColor", void 0);
  53532. __decorate([
  53533. BABYLON.serializeAsColor3("albedo")
  53534. ], PBRMaterial.prototype, "albedoColor", void 0);
  53535. __decorate([
  53536. BABYLON.serializeAsColor3("reflectivity")
  53537. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  53538. __decorate([
  53539. BABYLON.serializeAsColor3("reflection")
  53540. ], PBRMaterial.prototype, "reflectionColor", void 0);
  53541. __decorate([
  53542. BABYLON.serializeAsColor3("emissive")
  53543. ], PBRMaterial.prototype, "emissiveColor", void 0);
  53544. __decorate([
  53545. BABYLON.serialize()
  53546. ], PBRMaterial.prototype, "microSurface", void 0);
  53547. __decorate([
  53548. BABYLON.serialize()
  53549. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  53550. __decorate([
  53551. BABYLON.serialize()
  53552. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  53553. __decorate([
  53554. BABYLON.serializeAsFresnelParameters()
  53555. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  53556. __decorate([
  53557. BABYLON.serializeAsFresnelParameters()
  53558. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  53559. __decorate([
  53560. BABYLON.serialize()
  53561. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  53562. __decorate([
  53563. BABYLON.serialize()
  53564. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  53565. __decorate([
  53566. BABYLON.serialize()
  53567. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  53568. __decorate([
  53569. BABYLON.serialize()
  53570. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  53571. __decorate([
  53572. BABYLON.serialize()
  53573. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  53574. __decorate([
  53575. BABYLON.serialize()
  53576. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  53577. __decorate([
  53578. BABYLON.serialize()
  53579. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  53580. __decorate([
  53581. BABYLON.serialize()
  53582. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  53583. __decorate([
  53584. BABYLON.serialize()
  53585. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  53586. __decorate([
  53587. BABYLON.serialize()
  53588. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  53589. __decorate([
  53590. BABYLON.serialize()
  53591. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  53592. __decorate([
  53593. BABYLON.serialize()
  53594. ], PBRMaterial.prototype, "useParallax", void 0);
  53595. __decorate([
  53596. BABYLON.serialize()
  53597. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  53598. __decorate([
  53599. BABYLON.serialize()
  53600. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  53601. __decorate([
  53602. BABYLON.serialize()
  53603. ], PBRMaterial.prototype, "disableLighting", void 0);
  53604. __decorate([
  53605. BABYLON.serialize()
  53606. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  53607. __decorate([
  53608. BABYLON.serialize()
  53609. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  53610. __decorate([
  53611. BABYLON.serialize()
  53612. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  53613. __decorate([
  53614. BABYLON.serialize()
  53615. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  53616. return PBRMaterial;
  53617. }(BABYLON.Material));
  53618. BABYLON.PBRMaterial = PBRMaterial;
  53619. })(BABYLON || (BABYLON = {}));
  53620. //# sourceMappingURL=../Materials/babylon.pbrMaterial.js.map
  53621. var BABYLON;
  53622. (function (BABYLON) {
  53623. var DebugLayer = (function () {
  53624. function DebugLayer(scene) {
  53625. var _this = this;
  53626. this._transformationMatrix = BABYLON.Matrix.Identity();
  53627. this._enabled = false;
  53628. this._labelsEnabled = false;
  53629. this._displayStatistics = true;
  53630. this._displayTree = false;
  53631. this._displayLogs = false;
  53632. this._skeletonViewers = new Array();
  53633. this._identityMatrix = BABYLON.Matrix.Identity();
  53634. this.axisRatio = 0.02;
  53635. this.accentColor = "orange";
  53636. this._scene = scene;
  53637. this._syncPositions = function () {
  53638. var engine = _this._scene.getEngine();
  53639. var canvasRect = engine.getRenderingCanvasClientRect();
  53640. if (_this._showUI) {
  53641. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  53642. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  53643. _this._statsDiv.style.width = "400px";
  53644. _this._statsDiv.style.height = "auto";
  53645. _this._statsSubsetDiv.style.maxHeight = "240px";
  53646. _this._optionsDiv.style.left = "0px";
  53647. _this._optionsDiv.style.top = "10px";
  53648. _this._optionsDiv.style.width = "200px";
  53649. _this._optionsDiv.style.height = "auto";
  53650. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  53651. _this._logDiv.style.left = "0px";
  53652. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  53653. _this._logDiv.style.width = "600px";
  53654. _this._logDiv.style.height = "160px";
  53655. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  53656. _this._treeDiv.style.top = "10px";
  53657. _this._treeDiv.style.width = "300px";
  53658. _this._treeDiv.style.height = "auto";
  53659. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  53660. }
  53661. _this._globalDiv.style.left = canvasRect.left + "px";
  53662. _this._globalDiv.style.top = canvasRect.top + "px";
  53663. _this._drawingCanvas.style.left = "0px";
  53664. _this._drawingCanvas.style.top = "0px";
  53665. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  53666. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  53667. var devicePixelRatio = window.devicePixelRatio || 1;
  53668. var context = _this._drawingContext;
  53669. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  53670. context.mozBackingStorePixelRatio ||
  53671. context.msBackingStorePixelRatio ||
  53672. context.oBackingStorePixelRatio ||
  53673. context.backingStorePixelRatio || 1;
  53674. _this._ratio = devicePixelRatio / backingStoreRatio;
  53675. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  53676. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  53677. };
  53678. this._onCanvasClick = function (evt) {
  53679. _this._clickPosition = {
  53680. x: evt.clientX * _this._ratio,
  53681. y: evt.clientY * _this._ratio
  53682. };
  53683. };
  53684. this._syncUI = function () {
  53685. if (_this._showUI) {
  53686. if (_this._displayStatistics) {
  53687. _this._displayStats();
  53688. _this._statsDiv.style.display = "";
  53689. }
  53690. else {
  53691. _this._statsDiv.style.display = "none";
  53692. }
  53693. if (_this._displayLogs) {
  53694. _this._logDiv.style.display = "";
  53695. }
  53696. else {
  53697. _this._logDiv.style.display = "none";
  53698. }
  53699. if (_this._displayTree) {
  53700. _this._treeDiv.style.display = "";
  53701. if (_this._needToRefreshMeshesTree) {
  53702. _this._needToRefreshMeshesTree = false;
  53703. _this._refreshMeshesTreeContent();
  53704. }
  53705. }
  53706. else {
  53707. _this._treeDiv.style.display = "none";
  53708. }
  53709. }
  53710. };
  53711. this._syncData = function () {
  53712. if (_this._labelsEnabled || !_this._showUI) {
  53713. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  53714. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  53715. var engine = _this._scene.getEngine();
  53716. var viewport = _this._camera.viewport;
  53717. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  53718. // Meshes
  53719. var meshes = _this._camera.getActiveMeshes();
  53720. var index;
  53721. var projectedPosition;
  53722. for (index = 0; index < meshes.length; index++) {
  53723. var mesh = meshes.data[index];
  53724. var position = mesh.getBoundingInfo().boundingSphere.center;
  53725. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  53726. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  53727. _this._renderAxis(projectedPosition, mesh, globalViewport);
  53728. }
  53729. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  53730. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  53731. }
  53732. }
  53733. // Cameras
  53734. var cameras = _this._scene.cameras;
  53735. for (index = 0; index < cameras.length; index++) {
  53736. var camera = cameras[index];
  53737. if (camera === _this._camera) {
  53738. continue;
  53739. }
  53740. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  53741. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  53742. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  53743. _this._camera.detachControl(engine.getRenderingCanvas());
  53744. _this._camera = camera;
  53745. _this._camera.attachControl(engine.getRenderingCanvas());
  53746. }, function () { return "purple"; });
  53747. }
  53748. }
  53749. // Lights
  53750. var lights = _this._scene.lights;
  53751. for (index = 0; index < lights.length; index++) {
  53752. var light = lights[index];
  53753. if (light.position) {
  53754. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  53755. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  53756. _this._renderLabel(light.name, projectedPosition, -20, function () {
  53757. light.setEnabled(!light.isEnabled());
  53758. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  53759. }
  53760. }
  53761. }
  53762. }
  53763. _this._clickPosition = undefined;
  53764. };
  53765. }
  53766. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  53767. while (this._treeSubsetDiv.hasChildNodes()) {
  53768. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  53769. }
  53770. // Add meshes
  53771. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  53772. sortedArray.sort(function (a, b) {
  53773. if (a.name === b.name) {
  53774. return 0;
  53775. }
  53776. return (a.name > b.name) ? 1 : -1;
  53777. });
  53778. for (var index = 0; index < sortedArray.length; index++) {
  53779. var mesh = sortedArray[index];
  53780. if (!mesh.isEnabled()) {
  53781. continue;
  53782. }
  53783. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  53784. m.isVisible = element.checked;
  53785. }, mesh);
  53786. }
  53787. };
  53788. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  53789. this._drawingContext.beginPath();
  53790. this._drawingContext.moveTo(zero.x, zero.y);
  53791. this._drawingContext.lineTo(unit.x, unit.y);
  53792. this._drawingContext.strokeStyle = color;
  53793. this._drawingContext.lineWidth = 4;
  53794. this._drawingContext.stroke();
  53795. this._drawingContext.font = "normal 14px Segoe UI";
  53796. this._drawingContext.fillStyle = color;
  53797. this._drawingContext.fillText(label, unitText.x, unitText.y);
  53798. };
  53799. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  53800. var position = mesh.getBoundingInfo().boundingSphere.center;
  53801. var worldMatrix = mesh.getWorldMatrix();
  53802. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  53803. var unit = (unprojectedVector.subtract(position)).length();
  53804. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  53805. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  53806. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  53807. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  53808. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  53809. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  53810. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  53811. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  53812. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  53813. };
  53814. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  53815. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  53816. this._drawingContext.font = "normal 12px Segoe UI";
  53817. var textMetrics = this._drawingContext.measureText(text);
  53818. var centerX = projectedPosition.x - textMetrics.width / 2;
  53819. var centerY = projectedPosition.y;
  53820. var clientRect = this._drawingCanvas.getBoundingClientRect();
  53821. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  53822. onClick();
  53823. }
  53824. this._drawingContext.beginPath();
  53825. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  53826. this._drawingContext.fillStyle = getFillStyle();
  53827. this._drawingContext.globalAlpha = 0.5;
  53828. this._drawingContext.fill();
  53829. this._drawingContext.globalAlpha = 1.0;
  53830. this._drawingContext.strokeStyle = '#FFFFFF';
  53831. this._drawingContext.lineWidth = 1;
  53832. this._drawingContext.stroke();
  53833. this._drawingContext.fillStyle = "#FFFFFF";
  53834. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  53835. this._drawingContext.beginPath();
  53836. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  53837. this._drawingContext.fill();
  53838. }
  53839. };
  53840. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  53841. if (!this._clickPosition) {
  53842. return false;
  53843. }
  53844. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  53845. return false;
  53846. }
  53847. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  53848. return false;
  53849. }
  53850. return true;
  53851. };
  53852. DebugLayer.prototype.isVisible = function () {
  53853. return this._enabled;
  53854. };
  53855. DebugLayer.prototype.hide = function () {
  53856. if (!this._enabled) {
  53857. return;
  53858. }
  53859. this._enabled = false;
  53860. var engine = this._scene.getEngine();
  53861. this._scene.unregisterBeforeRender(this._syncData);
  53862. this._scene.unregisterAfterRender(this._syncUI);
  53863. this._rootElement.removeChild(this._globalDiv);
  53864. this._scene.forceShowBoundingBoxes = false;
  53865. this._scene.forceWireframe = false;
  53866. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  53867. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  53868. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  53869. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  53870. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  53871. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  53872. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  53873. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  53874. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  53875. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  53876. this._scene.shadowsEnabled = true;
  53877. this._scene.particlesEnabled = true;
  53878. this._scene.postProcessesEnabled = true;
  53879. this._scene.collisionsEnabled = true;
  53880. this._scene.lightsEnabled = true;
  53881. this._scene.texturesEnabled = true;
  53882. this._scene.lensFlaresEnabled = true;
  53883. this._scene.proceduralTexturesEnabled = true;
  53884. this._scene.renderTargetsEnabled = true;
  53885. this._scene.probesEnabled = true;
  53886. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  53887. this._clearSkeletonViewers();
  53888. };
  53889. DebugLayer.prototype._clearSkeletonViewers = function () {
  53890. for (var index = 0; index < this._skeletonViewers.length; index++) {
  53891. this._skeletonViewers[index].dispose();
  53892. }
  53893. this._skeletonViewers = [];
  53894. };
  53895. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  53896. if (showUI === void 0) { showUI = true; }
  53897. if (camera === void 0) { camera = null; }
  53898. if (rootElement === void 0) { rootElement = null; }
  53899. if (this._enabled) {
  53900. return;
  53901. }
  53902. this._enabled = true;
  53903. if (camera) {
  53904. this._camera = camera;
  53905. }
  53906. else {
  53907. this._camera = this._scene.activeCamera;
  53908. }
  53909. this._showUI = showUI;
  53910. var engine = this._scene.getEngine();
  53911. this._globalDiv = document.createElement("div");
  53912. this._rootElement = rootElement || document.body;
  53913. this._rootElement.appendChild(this._globalDiv);
  53914. this._generateDOMelements();
  53915. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  53916. this._syncPositions();
  53917. this._scene.registerBeforeRender(this._syncData);
  53918. this._scene.registerAfterRender(this._syncUI);
  53919. };
  53920. DebugLayer.prototype._clearLabels = function () {
  53921. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  53922. for (var index = 0; index < this._scene.meshes.length; index++) {
  53923. var mesh = this._scene.meshes[index];
  53924. mesh.renderOverlay = false;
  53925. }
  53926. };
  53927. DebugLayer.prototype._generateheader = function (root, text) {
  53928. var header = document.createElement("div");
  53929. header.innerHTML = text + "&nbsp;";
  53930. header.style.textAlign = "right";
  53931. header.style.width = "100%";
  53932. header.style.color = "white";
  53933. header.style.backgroundColor = "Black";
  53934. header.style.padding = "5px 5px 4px 0px";
  53935. header.style.marginLeft = "-5px";
  53936. header.style.fontWeight = "bold";
  53937. root.appendChild(header);
  53938. };
  53939. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  53940. var label = document.createElement("label");
  53941. label.style.display = "inline";
  53942. label.innerHTML = title;
  53943. label.style.color = color;
  53944. root.appendChild(label);
  53945. root.appendChild(document.createElement("br"));
  53946. };
  53947. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  53948. if (tag === void 0) { tag = null; }
  53949. var label = document.createElement("label");
  53950. label.style.display = "inline";
  53951. var boundingBoxesCheckbox = document.createElement("input");
  53952. boundingBoxesCheckbox.type = "checkbox";
  53953. boundingBoxesCheckbox.checked = initialState;
  53954. boundingBoxesCheckbox.style.display = "inline";
  53955. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  53956. boundingBoxesCheckbox.style.verticalAlign = "sub";
  53957. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  53958. task(evt.target, tag);
  53959. });
  53960. label.appendChild(boundingBoxesCheckbox);
  53961. var container = document.createElement("span");
  53962. var leftPart = document.createElement("span");
  53963. var rightPart = document.createElement("span");
  53964. rightPart.style.cssFloat = "right";
  53965. leftPart.innerHTML = leftTitle;
  53966. rightPart.innerHTML = rightTitle;
  53967. rightPart.style.fontSize = "12px";
  53968. rightPart.style.maxWidth = "200px";
  53969. container.appendChild(leftPart);
  53970. container.appendChild(rightPart);
  53971. label.appendChild(container);
  53972. root.appendChild(label);
  53973. root.appendChild(document.createElement("br"));
  53974. };
  53975. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  53976. if (tag === void 0) { tag = null; }
  53977. var label = document.createElement("label");
  53978. label.style.display = "inline";
  53979. var checkBox = document.createElement("input");
  53980. checkBox.type = "checkbox";
  53981. checkBox.checked = initialState;
  53982. checkBox.style.display = "inline";
  53983. checkBox.style.margin = "0px 5px 0px 0px";
  53984. checkBox.style.verticalAlign = "sub";
  53985. checkBox.addEventListener("change", function (evt) {
  53986. task(evt.target, tag);
  53987. });
  53988. label.appendChild(checkBox);
  53989. label.appendChild(document.createTextNode(title));
  53990. root.appendChild(label);
  53991. root.appendChild(document.createElement("br"));
  53992. };
  53993. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  53994. if (tag === void 0) { tag = null; }
  53995. var button = document.createElement("button");
  53996. button.innerHTML = title;
  53997. button.style.height = "24px";
  53998. button.style.width = "150px";
  53999. button.style.marginBottom = "5px";
  54000. button.style.color = "#444444";
  54001. button.style.border = "1px solid white";
  54002. button.className = "debugLayerButton";
  54003. button.addEventListener("click", function (evt) {
  54004. task(evt.target, tag);
  54005. });
  54006. root.appendChild(button);
  54007. root.appendChild(document.createElement("br"));
  54008. };
  54009. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  54010. if (tag === void 0) { tag = null; }
  54011. var label = document.createElement("label");
  54012. label.style.display = "inline";
  54013. var boundingBoxesRadio = document.createElement("input");
  54014. boundingBoxesRadio.type = "radio";
  54015. boundingBoxesRadio.name = name;
  54016. boundingBoxesRadio.checked = initialState;
  54017. boundingBoxesRadio.style.display = "inline";
  54018. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  54019. boundingBoxesRadio.style.verticalAlign = "sub";
  54020. boundingBoxesRadio.addEventListener("change", function (evt) {
  54021. task(evt.target, tag);
  54022. });
  54023. label.appendChild(boundingBoxesRadio);
  54024. label.appendChild(document.createTextNode(title));
  54025. root.appendChild(label);
  54026. root.appendChild(document.createElement("br"));
  54027. };
  54028. DebugLayer.prototype._generateDOMelements = function () {
  54029. var _this = this;
  54030. this._globalDiv.id = "DebugLayer";
  54031. this._globalDiv.style.position = "absolute";
  54032. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  54033. this._globalDiv.style.fontSize = "14px";
  54034. this._globalDiv.style.color = "white";
  54035. // Drawing canvas
  54036. this._drawingCanvas = document.createElement("canvas");
  54037. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  54038. this._drawingCanvas.style.position = "absolute";
  54039. this._drawingCanvas.style.pointerEvents = "none";
  54040. this._drawingCanvas.style.backgroundColor = "transparent";
  54041. this._drawingContext = this._drawingCanvas.getContext("2d");
  54042. this._globalDiv.appendChild(this._drawingCanvas);
  54043. if (this._showUI) {
  54044. var background = "rgba(128, 128, 128, 0.4)";
  54045. var border = "rgb(180, 180, 180) solid 1px";
  54046. // Stats
  54047. this._statsDiv = document.createElement("div");
  54048. this._statsDiv.id = "DebugLayerStats";
  54049. this._statsDiv.style.border = border;
  54050. this._statsDiv.style.position = "absolute";
  54051. this._statsDiv.style.background = background;
  54052. this._statsDiv.style.padding = "0px 0px 0px 5px";
  54053. this._generateheader(this._statsDiv, "STATISTICS");
  54054. this._statsSubsetDiv = document.createElement("div");
  54055. this._statsSubsetDiv.style.paddingTop = "5px";
  54056. this._statsSubsetDiv.style.paddingBottom = "5px";
  54057. this._statsSubsetDiv.style.overflowY = "auto";
  54058. this._statsDiv.appendChild(this._statsSubsetDiv);
  54059. // Tree
  54060. this._treeDiv = document.createElement("div");
  54061. this._treeDiv.id = "DebugLayerTree";
  54062. this._treeDiv.style.border = border;
  54063. this._treeDiv.style.position = "absolute";
  54064. this._treeDiv.style.background = background;
  54065. this._treeDiv.style.padding = "0px 0px 0px 5px";
  54066. this._treeDiv.style.display = "none";
  54067. this._generateheader(this._treeDiv, "MESHES TREE");
  54068. this._treeSubsetDiv = document.createElement("div");
  54069. this._treeSubsetDiv.style.paddingTop = "5px";
  54070. this._treeSubsetDiv.style.paddingRight = "5px";
  54071. this._treeSubsetDiv.style.overflowY = "auto";
  54072. this._treeSubsetDiv.style.maxHeight = "300px";
  54073. this._treeDiv.appendChild(this._treeSubsetDiv);
  54074. this._needToRefreshMeshesTree = true;
  54075. // Logs
  54076. this._logDiv = document.createElement("div");
  54077. this._logDiv.style.border = border;
  54078. this._logDiv.id = "DebugLayerLogs";
  54079. this._logDiv.style.position = "absolute";
  54080. this._logDiv.style.background = background;
  54081. this._logDiv.style.padding = "0px 0px 0px 5px";
  54082. this._logDiv.style.display = "none";
  54083. this._generateheader(this._logDiv, "LOGS");
  54084. this._logSubsetDiv = document.createElement("div");
  54085. this._logSubsetDiv.style.height = "127px";
  54086. this._logSubsetDiv.style.paddingTop = "5px";
  54087. this._logSubsetDiv.style.overflowY = "auto";
  54088. this._logSubsetDiv.style.fontSize = "12px";
  54089. this._logSubsetDiv.style.fontFamily = "consolas";
  54090. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  54091. this._logDiv.appendChild(this._logSubsetDiv);
  54092. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  54093. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  54094. };
  54095. // Options
  54096. this._optionsDiv = document.createElement("div");
  54097. this._optionsDiv.id = "DebugLayerOptions";
  54098. this._optionsDiv.style.border = border;
  54099. this._optionsDiv.style.position = "absolute";
  54100. this._optionsDiv.style.background = background;
  54101. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  54102. this._optionsDiv.style.overflowY = "auto";
  54103. this._generateheader(this._optionsDiv, "OPTIONS");
  54104. this._optionsSubsetDiv = document.createElement("div");
  54105. this._optionsSubsetDiv.style.paddingTop = "5px";
  54106. this._optionsSubsetDiv.style.paddingBottom = "5px";
  54107. this._optionsSubsetDiv.style.overflowY = "auto";
  54108. this._optionsSubsetDiv.style.maxHeight = "200px";
  54109. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  54110. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  54111. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  54112. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  54113. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  54114. _this._displayTree = element.checked;
  54115. _this._needToRefreshMeshesTree = true;
  54116. });
  54117. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  54118. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  54119. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  54120. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  54121. _this._labelsEnabled = element.checked;
  54122. if (!_this._labelsEnabled) {
  54123. _this._clearLabels();
  54124. }
  54125. });
  54126. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  54127. if (element.checked) {
  54128. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  54129. }
  54130. else {
  54131. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  54132. }
  54133. });
  54134. ;
  54135. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  54136. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  54137. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  54138. if (element.checked) {
  54139. _this._scene.forceWireframe = false;
  54140. _this._scene.forcePointsCloud = false;
  54141. }
  54142. });
  54143. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  54144. if (element.checked) {
  54145. _this._scene.forceWireframe = true;
  54146. _this._scene.forcePointsCloud = false;
  54147. }
  54148. });
  54149. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  54150. if (element.checked) {
  54151. _this._scene.forceWireframe = false;
  54152. _this._scene.forcePointsCloud = true;
  54153. }
  54154. });
  54155. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  54156. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  54157. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  54158. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  54159. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  54160. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  54161. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  54162. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  54163. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  54164. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  54165. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  54166. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  54167. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  54168. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  54169. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  54170. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  54171. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  54172. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  54173. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  54174. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  54175. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  54176. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  54177. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  54178. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  54179. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  54180. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  54181. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  54182. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  54183. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  54184. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  54185. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  54186. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  54187. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  54188. if (element.checked) {
  54189. _this._scene.headphone = true;
  54190. }
  54191. });
  54192. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  54193. if (element.checked) {
  54194. _this._scene.headphone = false;
  54195. }
  54196. });
  54197. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  54198. _this._scene.audioEnabled = !element.checked;
  54199. });
  54200. }
  54201. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  54202. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  54203. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  54204. if (!element.checked) {
  54205. _this._clearSkeletonViewers();
  54206. return;
  54207. }
  54208. for (var index = 0; index < _this._scene.meshes.length; index++) {
  54209. var mesh = _this._scene.meshes[index];
  54210. if (mesh.skeleton) {
  54211. var found = false;
  54212. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  54213. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  54214. found = true;
  54215. break;
  54216. }
  54217. }
  54218. if (found) {
  54219. continue;
  54220. }
  54221. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  54222. viewer.isEnabled = true;
  54223. _this._skeletonViewers.push(viewer);
  54224. }
  54225. }
  54226. });
  54227. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  54228. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  54229. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  54230. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  54231. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  54232. if (_this._camera) {
  54233. console.log(_this._camera);
  54234. }
  54235. else {
  54236. console.warn("No camera defined, or debug layer created before camera creation!");
  54237. }
  54238. });
  54239. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  54240. this._globalDiv.appendChild(this._statsDiv);
  54241. this._globalDiv.appendChild(this._logDiv);
  54242. this._globalDiv.appendChild(this._optionsDiv);
  54243. this._globalDiv.appendChild(this._treeDiv);
  54244. }
  54245. };
  54246. DebugLayer.prototype._displayStats = function () {
  54247. var scene = this._scene;
  54248. var engine = scene.getEngine();
  54249. var glInfo = engine.getGlInfo();
  54250. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  54251. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  54252. + "<b>Count</b><br>"
  54253. + "Total meshes: " + scene.meshes.length + "<br>"
  54254. + "Total lights: " + scene.lights.length + "<br>"
  54255. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  54256. + "Total materials: " + scene.materials.length + "<br>"
  54257. + "Total textures: " + scene.textures.length + "<br>"
  54258. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  54259. + "Active indices: " + scene.getActiveIndices() + "<br>"
  54260. + "Active bones: " + scene.getActiveBones() + "<br>"
  54261. + "Active particles: " + scene.getActiveParticles() + "<br>"
  54262. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  54263. + "<b>Duration</b><br>"
  54264. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  54265. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  54266. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  54267. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  54268. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  54269. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  54270. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  54271. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  54272. + "</div>"
  54273. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  54274. + "<b>Extensions</b><br>"
  54275. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  54276. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  54277. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  54278. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  54279. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  54280. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  54281. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  54282. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  54283. + "</div><br>"
  54284. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  54285. + "<b>Caps.</b><br>"
  54286. + "Stencil: " + (engine.isStencilEnable ? "Enabled" : "Disabled") + "<br>"
  54287. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  54288. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  54289. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  54290. + "<b>Info</b><br>"
  54291. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  54292. + glInfo.version + "<br>"
  54293. + "</div><br>"
  54294. + glInfo.renderer + "<br>";
  54295. if (this.customStatsFunction) {
  54296. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  54297. }
  54298. };
  54299. return DebugLayer;
  54300. }());
  54301. BABYLON.DebugLayer = DebugLayer;
  54302. })(BABYLON || (BABYLON = {}));
  54303. //# sourceMappingURL=../Debug/babylon.debugLayer.js.map
  54304. var BABYLON;
  54305. (function (BABYLON) {
  54306. var StandardRenderingPipeline = (function (_super) {
  54307. __extends(StandardRenderingPipeline, _super);
  54308. /**
  54309. * @constructor
  54310. * @param {string} name - The rendering pipeline name
  54311. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54312. * @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)
  54313. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54314. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54315. */
  54316. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54317. var _this = this;
  54318. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54319. _super.call(this, scene.getEngine(), name);
  54320. this.downSampleX4PostProcess = null;
  54321. this.brightPassPostProcess = null;
  54322. this.gaussianBlurHPostProcesses = [];
  54323. this.gaussianBlurVPostProcesses = [];
  54324. this.textureAdderPostProcess = null;
  54325. this.textureAdderFinalPostProcess = null;
  54326. this.lensFlarePostProcess = null;
  54327. this.lensFlareComposePostProcess = null;
  54328. this.depthOfFieldPostProcess = null;
  54329. // Values
  54330. this.brightThreshold = 1.0;
  54331. this.blurWidth = 2.0;
  54332. this.gaussianCoefficient = 0.25;
  54333. this.gaussianMean = 1.0;
  54334. this.gaussianStandardDeviation = 1.0;
  54335. this.exposure = 1.0;
  54336. this.lensTexture = null;
  54337. this.lensColorTexture = null;
  54338. this.lensFlareStrength = 20.0;
  54339. this.lensFlareGhostDispersal = 1.4;
  54340. this.lensFlareHaloWidth = 0.7;
  54341. this.lensFlareDistortionStrength = 16.0;
  54342. this.lensStarTexture = null;
  54343. this.lensFlareDirtTexture = null;
  54344. this.depthOfFieldDistance = 10.0;
  54345. // IAnimatable
  54346. this.animations = [];
  54347. this._depthRenderer = null;
  54348. // Getters and setters
  54349. this._depthOfFieldEnabled = true;
  54350. this._lensFlareEnabled = true;
  54351. // Initialize
  54352. this._scene = scene;
  54353. // Create pass post-processe
  54354. if (!originalPostProcess) {
  54355. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  54356. }
  54357. else {
  54358. this.originalPostProcess = originalPostProcess;
  54359. }
  54360. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  54361. // Create down sample X4 post-process
  54362. this._createDownSampleX4PostProcess(scene, ratio / 2);
  54363. // Create bright pass post-process
  54364. this._createBrightPassPostProcess(scene, ratio / 2);
  54365. // Create gaussian blur post-processes (down sampling blurs)
  54366. this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  54367. this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  54368. this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  54369. this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  54370. // Create texture adder post-process
  54371. this._createTextureAdderPostProcess(scene, ratio);
  54372. // Create depth-of-field source post-process
  54373. 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);
  54374. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  54375. // Create lens flare post-process
  54376. this._createLensFlarePostProcess(scene, ratio);
  54377. // Create gaussian blur used by depth-of-field
  54378. this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  54379. // Create depth-of-field post-process
  54380. this._createDepthOfFieldPostProcess(scene, ratio);
  54381. // Finish
  54382. scene.postProcessRenderPipelineManager.addPipeline(this);
  54383. if (cameras !== null) {
  54384. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54385. }
  54386. // Deactivate
  54387. this.LensFlareEnabled = false;
  54388. this.DepthOfFieldEnabled = false;
  54389. }
  54390. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  54391. get: function () {
  54392. return this._depthOfFieldEnabled;
  54393. },
  54394. set: function (enabled) {
  54395. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  54396. if (enabled && !this._depthOfFieldEnabled) {
  54397. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54398. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54399. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  54400. this._depthRenderer = this._scene.enableDepthRenderer();
  54401. }
  54402. else if (!enabled && this._depthOfFieldEnabled) {
  54403. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54404. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54405. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  54406. }
  54407. this._depthOfFieldEnabled = enabled;
  54408. },
  54409. enumerable: true,
  54410. configurable: true
  54411. });
  54412. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  54413. get: function () {
  54414. return this._lensFlareEnabled;
  54415. },
  54416. set: function (enabled) {
  54417. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  54418. if (enabled && !this._lensFlareEnabled) {
  54419. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  54420. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  54421. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54422. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54423. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  54424. }
  54425. else if (!enabled && this._lensFlareEnabled) {
  54426. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  54427. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  54428. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54429. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54430. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  54431. }
  54432. this._lensFlareEnabled = enabled;
  54433. },
  54434. enumerable: true,
  54435. configurable: true
  54436. });
  54437. // Down Sample X4 Post-Processs
  54438. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54439. var _this = this;
  54440. var downSampleX4Offsets = new Array(32);
  54441. 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);
  54442. this.downSampleX4PostProcess.onApply = function (effect) {
  54443. var id = 0;
  54444. for (var i = -2; i < 2; i++) {
  54445. for (var j = -2; j < 2; j++) {
  54446. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  54447. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  54448. id += 2;
  54449. }
  54450. }
  54451. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54452. };
  54453. // Add to pipeline
  54454. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  54455. };
  54456. // Brightpass Post-Process
  54457. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54458. var _this = this;
  54459. var brightOffsets = new Array(8);
  54460. 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);
  54461. this.brightPassPostProcess.onApply = function (effect) {
  54462. var sU = (1.0 / _this.brightPassPostProcess.width);
  54463. var sV = (1.0 / _this.brightPassPostProcess.height);
  54464. brightOffsets[0] = -0.5 * sU;
  54465. brightOffsets[1] = 0.5 * sV;
  54466. brightOffsets[2] = 0.5 * sU;
  54467. brightOffsets[3] = 0.5 * sV;
  54468. brightOffsets[4] = -0.5 * sU;
  54469. brightOffsets[5] = -0.5 * sV;
  54470. brightOffsets[6] = 0.5 * sU;
  54471. brightOffsets[7] = -0.5 * sV;
  54472. effect.setArray2("dsOffsets", brightOffsets);
  54473. effect.setFloat("brightThreshold", _this.brightThreshold);
  54474. };
  54475. // Add to pipeline
  54476. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  54477. };
  54478. // Create gaussian blur H&V post-processes
  54479. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  54480. var _this = this;
  54481. var blurOffsets = new Array(9);
  54482. var blurWeights = new Array(9);
  54483. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  54484. var callback = function (height) {
  54485. return function (effect) {
  54486. // Weights
  54487. var x = 0.0;
  54488. for (var i = 0; i < 9; i++) {
  54489. x = (i - 4.0) / 4.0;
  54490. blurWeights[i] =
  54491. _this.gaussianCoefficient
  54492. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  54493. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  54494. }
  54495. var lastOutputDimensions = {
  54496. width: scene.getEngine().getRenderWidth(),
  54497. height: scene.getEngine().getRenderHeight()
  54498. };
  54499. for (var i = 0; i < 9; i++) {
  54500. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  54501. blurOffsets[i] = value;
  54502. }
  54503. effect.setArray("blurOffsets", blurOffsets);
  54504. effect.setArray("blurWeights", blurWeights);
  54505. effect.setFloat("blurWidth", _this.blurWidth);
  54506. };
  54507. };
  54508. // Create horizontal gaussian blur post-processes
  54509. 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);
  54510. gaussianBlurHPostProcess.onApply = callback(false);
  54511. // Create vertical gaussian blur post-process
  54512. 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);
  54513. gaussianBlurVPostProcess.onApply = callback(true);
  54514. // Add to pipeline
  54515. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  54516. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  54517. // Finish
  54518. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  54519. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  54520. };
  54521. // Create texture adder post-process
  54522. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54523. var _this = this;
  54524. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  54525. 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);
  54526. this.textureAdderPostProcess.onApply = function (effect) {
  54527. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  54528. effect.setTexture("lensSampler", _this.lensTexture);
  54529. effect.setFloat("exposure", _this.exposure);
  54530. };
  54531. // Add to pipeline
  54532. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  54533. };
  54534. // Create lens flare post-process
  54535. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  54536. var _this = this;
  54537. 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);
  54538. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  54539. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  54540. 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);
  54541. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  54542. var resolution = new BABYLON.Vector2(0, 0);
  54543. // Lens flare
  54544. this.lensFlarePostProcess.onApply = function (effect) {
  54545. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  54546. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  54547. effect.setFloat("strength", _this.lensFlareStrength);
  54548. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  54549. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  54550. // Shift
  54551. resolution.x = _this.lensFlarePostProcess.width;
  54552. resolution.y = _this.lensFlarePostProcess.height;
  54553. effect.setVector2("resolution", resolution);
  54554. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  54555. };
  54556. // Compose
  54557. 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);
  54558. 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);
  54559. this.lensFlareComposePostProcess.onApply = function (effect) {
  54560. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  54561. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  54562. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  54563. // Lens start rotation matrix
  54564. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  54565. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  54566. 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));
  54567. camRot *= 4.0;
  54568. 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);
  54569. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  54570. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  54571. };
  54572. };
  54573. // Create depth-of-field post-process
  54574. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  54575. var _this = this;
  54576. 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);
  54577. this.depthOfFieldPostProcess.onApply = function (effect) {
  54578. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  54579. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  54580. effect.setFloat("distance", _this.depthOfFieldDistance);
  54581. };
  54582. // Add to pipeline
  54583. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  54584. };
  54585. // Dispose
  54586. StandardRenderingPipeline.prototype.dispose = function () {
  54587. for (var i = 0; i < this._scene.cameras.length; i++) {
  54588. var camera = this._scene.cameras[i];
  54589. this.originalPostProcess.dispose(camera);
  54590. this.downSampleX4PostProcess.dispose(camera);
  54591. this.brightPassPostProcess.dispose(camera);
  54592. this.textureAdderPostProcess.dispose(camera);
  54593. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  54594. this.gaussianBlurHPostProcesses[j].dispose(camera);
  54595. }
  54596. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  54597. this.gaussianBlurVPostProcesses[j].dispose(camera);
  54598. }
  54599. this.textureAdderFinalPostProcess.dispose(camera);
  54600. this.lensFlarePostProcess.dispose(camera);
  54601. this.lensFlareComposePostProcess.dispose(camera);
  54602. this.depthOfFieldPostProcess.dispose(camera);
  54603. }
  54604. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54605. _super.prototype.dispose.call(this);
  54606. };
  54607. return StandardRenderingPipeline;
  54608. }(BABYLON.PostProcessRenderPipeline));
  54609. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  54610. })(BABYLON || (BABYLON = {}));
  54611. //# sourceMappingURL=../PostProcess/babylon.standardRenderingPipeline.js.map
  54612. 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\n#ifdef VERTEXCOLOR\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)\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 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)\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)\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\nfFogDistance=viewPos.z;\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 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\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}"};
  54613. 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 float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\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,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\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-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\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"};
  54614. 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()}return 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(l){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(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,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.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 Int32Array(o.getIndices()||[])}},t}();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);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._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,n){void 0===n&&(n=1.401298e-45);var r=t-i;return-n<=r&&r<=n},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,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.prototype.getClassName=function(){return\"Color3\"},n.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},n.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},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.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},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.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},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.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},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.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},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.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},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,e=t.g+(i.g-t.g)*r,s=t.b+(i.b-t.b)*r;return new n(o,e,s)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}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,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,e)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.getClassName=function(){return\"Vector2\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n((-this.x),(-this.y))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>r.y?r.y:e,e=e<i.y?i.y:e,new n(o,e)},n.Hermite=function(t,i,r,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+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r;return new n(o,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=n.Zero();return n.TransformToRef(t,i,r),r},n.TransformToRef=function(t,i,n){var r=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];n.x=r,n.y=o},n.PointInTriangle=function(t,i,n,r){var o=.5*(-n.y*r.x+i.y*(-n.x+r.x)+i.x*(n.y-r.y)+n.x*r.y),e=o<0?-1:1,s=(i.y*r.x-i.x*r.y+(r.y-i.y)*t.x+(i.x-r.x)*t.y)*e,h=(i.x*n.y-i.y*n.x+(i.y-n.y)*t.x+(n.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.DistanceOfPointFromSegment=function(t,i,r){var o=n.DistanceSquared(i,r);if(0===o)return n.Distance(t,i);var e=r.subtract(i),s=Math.max(0,Math.min(1,n.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return n.Distance(t,h)},n}();t.Vector2=o;var e=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.getClassName=function(){return\"Vector3\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.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},n.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=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=r*s,t.y=-o*s,t.z=n*e,t.w=i*e,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.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},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.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},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n((-this.x),(-this.y),(-this.z))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.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},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.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},n.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},n.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},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.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},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var e=n.Dot(t,r)-o,s=n.Dot(i,r)-o,h=e/(e-s);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.Forward=function(){return new n(0,0,1)},n.Right=function(){return new n(1,0,0)},n.Left=function(){return new n((-1),0,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=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];n.x=r/s,n.y=o/s,n.z=e/s},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var e=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],s=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=e/a,o.y=s/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){var r=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];n.x=r,n.y=o,n.z=e},n.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*e+(2*t.z-5*i.z+4*r.z-o.z)*s+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>r.y?r.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>r.z?r.z:s,s=s<i.z?i.z:s,new n(o,e,s)},n.Hermite=function(t,i,r,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+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r,s=t.z+(i.z-t.z)*r;return new n(o,e,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){M.Vector3[0].x=t.y*i.z-t.z*i.y,M.Vector3[0].y=t.z*i.x-t.x*i.z,M.Vector3[0].z=t.x*i.y-t.y*i.x,n.copyFrom(M.Vector3[0])},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=n._viewportMatrixCache?n._viewportMatrixCache:n._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=n._matrixCache?n._matrixCache:n._matrixCache=new u;return i.multiplyToRef(r,y),y.multiplyToRef(m,y),n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,e,s){var h=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.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},n.Unproject=function(t,r,o,e,s,h){var a=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new n(t.x/r*2-1,(-(t.y/o*2-1)),t.z),y=n.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},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,e,s){var h=r.normalize(),a=e.normalize(),u=p.X,m=p.Y,y=0,c=0,f=0,x=0,l=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],R=0,T=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?x=1:(w=a.z/a.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),T.x=x,T.y=l,T.z=z,T.normalize(),n.CrossToRef(h,T,g),g.normalize(),n.Dot(a,g)<0&&(v=1),R=n.Dot(h,T),R=Math.min(1,Math.max(-1,R)),f=Math.acos(R)*v,n.Dot(T,u)<0&&(f=Math.PI+f,T=T.scaleInPlace(-1),d++);var _=M.Vector3[2],A=M.Vector3[3];x=0,l=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?x=1:(w=T.z/T.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=x,_.y=l,_.z=z,_.normalize(),n.CrossToRef(_,T,A),A.normalize(),n.CrossToRef(a,_,g),g.normalize(),n.Dot(T,g)<0&&(v=1),R=n.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,n.Dot(A,m)<0&&(c=Math.PI+c,d++),v=-1,n.CrossToRef(u,T,g),g.normalize(),n.Dot(g,m)<0&&(v=1),R=n.Dot(T,u),R=Math.min(1,Math.max(-1,R)),y=-Math.acos(R)*v,R<0&&d<2&&(y=Math.PI+y),s.x=c,s.y=y,s.z=f},n}();t.Vector3=e;var s=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},n.prototype.getClassName=function(){return\"Vector4\"},n.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)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.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},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.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},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.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},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n((-this.x),(-this.y),(-this.z),(-this.w))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.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},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.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},n.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},n.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},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.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},n.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return n*n+r*r+o*o+e*e},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();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){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,n){return new t(this.width*i,this.height*n)},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 n=new t(this.width+i.width,this.height+i.height);return n},t.prototype.substract=function(i){var n=new t(this.width-i.width,this.height-i.height);return n},t.Lerp=function(i,n,r){var o=i.width+(n.width-i.width)*r,e=i.height+(n.height-i.height)*r;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.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)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-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(n,r,o,e),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t((-this.x),(-this.y),(-this.z),this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n=this.z,r=this.x,o=this.y,e=this.w,s=e*e,h=n*n,a=r*r,u=o*o,m=o*n-r*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*(r*o+n*e),-h-a+u+s),t.x=Math.asin(-2*(n*o-r*e)),t.y=Math.atan2(2*(n*r+o*e),h-a-u+s)),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=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*(n+r),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*(r+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*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],e=r[4],s=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(s-m)*n,i.z=(h-e)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(e+h)/n,i.z=(s+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(s-m)/n,i.x=(e+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-e)/n,i.x=(s+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t((-i.x),(-i.y),(-i.z),i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){return t.RotationAxisToRef(i,n,new t)},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(i/2);return t.normalize(),n.w=Math.cos(i/2),n.x=t.x*r,n.y=t.y*r,n.z=t.z*r,n},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,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);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),e=.5*(n-t),s=.5*i;r.x=Math.cos(e)*Math.sin(s),r.y=Math.sin(e)*Math.sin(s),r.z=Math.sin(o)*Math.cos(s),r.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,n,r){var o,e,s=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.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}return new t(e*i.x+o*n.x,e*i.y+o*n.y,e*i.z+o*n.z,e*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.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])},t.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],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=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]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*e)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*e)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;n<16;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=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),b=1/(i*T+n*_+r*M+o*A),F=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,D=s*y-h*m,q=e*c-a*u,V=e*y-h*u,N=e*m-s*u;return t.m[0]=T*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=A*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*R)*b,t.m[13]=(i*v-n*g+r*R)*b,t.m[2]=(n*F-r*L+o*C)*b,t.m[6]=-(i*F-r*P+o*Z)*b,t.m[10]=(i*L-n*P+o*S)*b,t.m[14]=-(i*C-n*Z+r*S)*b,t.m[3]=-(n*I-r*H+o*D)*b,t.m[7]=(i*I-r*q+o*V)*b,t.m[11]=-(i*H-n*q+o*N)*b,t.m[15]=(i*D-n*V+r*N)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;i<16;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;n<16;n++)t[i+n]=this.m[n];\nreturn this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,n){var r=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],b=t.m[8],F=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[n]=r*v+o*T+e*b+s*P,i[n+1]=r*d+o*_+e*F+s*Z,i[n+2]=r*g+o*M+e*L+s*S,i[n+3]=r*R+o*A+e*C+s*I,i[n+4]=h*v+a*T+u*b+m*P,i[n+5]=h*d+a*_+u*F+m*Z,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*R+a*A+u*C+m*I,i[n+8]=y*v+c*T+p*b+f*P,i[n+9]=y*d+c*_+p*F+f*Z,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*R+c*A+p*C+f*I,i[n+12]=x*v+l*T+z*b+w*P,i[n+13]=x*d+l*_+z*F+w*Z,i[n+14]=x*g+l*M+z*L+w*S,i[n+15]=x*R+l*A+z*C+w*I,this},t.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]},t.prototype.clone=function(){return t.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])},t.prototype.getClassName=function(){return\"Matrix\"},t.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},t.prototype.decompose=function(n,r,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 n.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z?(r.x=0,r.y=0,r.z=0,r.w=1,!1):(t.FromValuesToRef(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1,M.Matrix[0]),a.FromRotationMatrixToRef(M.Matrix[0],r),!0)},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;r<16;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;o<16;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=n,l.m[3]=r,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},t.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])},t.prototype.setRow=function(t,i){if(t<0||t>3)return this;var n=4*t;return this.m[n+0]=i.x,this.m[n+1]=i.y,this.m[n+2]=i.z,this.m[n+3]=i.w,this},t.FromValues=function(i,n,r,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,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},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),e=t.Identity();return n.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,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},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,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},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,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},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),n.m[0]=t.x*t.x*e+o,n.m[1]=t.x*t.y*e-t.z*r,n.m[2]=t.x*t.z*e+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*e+t.z*r,n.m[5]=t.y*t.y*e+o,n.m[6]=t.y*t.z*e-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*e-t.y*r,n.m[9]=t.z*t.y*e+t.x*r,n.m[10]=t.z*t.z*e+o,n.m[11]=0,n.m[15]=1},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){for(var o=t.Zero(),e=0;e<16;e++)o.m[e]=i.m[e]*(1-r)+n.m[e]*r;return o},t.DecomposeLerp=function(i,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);i.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,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,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.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)},t.LookAtRH=function(i,n,r){var o=t.Zero();return t.LookAtRHToRef(i,n,r,o),o},t.LookAtRHToRef=function(i,n,r,o){i.subtractToRef(n,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,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,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.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)},t.OrthoLH=function(i,n,r,o){var e=t.Zero();return t.OrthoLHToRef(i,n,r,o,e),e},t.OrthoLHToRef=function(i,n,r,o,e){var s=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(s,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,e)},t.OrthoOffCenterLH=function(i,n,r,o,e,s){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,e,s,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,e,s){s.m[0]=2/(i-t),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(r-n),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=1/(e-o),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(t+i)/(t-i),s.m[13]=(r+n)/(n-r),s.m[14]=-o/(e-o),s.m[15]=1},t.OrthoOffCenterRH=function(i,n,r,o,e,s){var h=t.Zero();return t.OrthoOffCenterRHToRef(i,n,r,o,e,s,h),h},t.OrthoOffCenterRHToRef=function(i,n,r,o,e,s,h){t.OrthoOffCenterLHToRef(i,n,r,o,e,s,h),h.m[10]*=-1},t.PerspectiveLH=function(i,n,r,o){var e=t.Zero();return e.m[0]=2*r/i,e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2*r/n,e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-o/(r-o),e.m[8]=e.m[9]=0,e.m[11]=1,e.m[12]=e.m[13]=e.m[15]=0,e.m[14]=r*o/(r-o),e},t.PerspectiveFovLH=function(i,n,r,o){var e=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,e),e},t.PerspectiveFovLHToRef=function(t,i,n,r,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=r/(r-n),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=-(n*r)/(r-n)},t.PerspectiveFovRH=function(i,n,r,o){var e=t.Zero();return t.PerspectiveFovRHToRef(i,n,r,o,e),e},t.PerspectiveFovRHToRef=function(t,i,n,r,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=r/(n-r),o.m[11]=-1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.PerspectiveFovWebVRToRef=function(t,i,n,r,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);r.m[0]=u,r.m[1]=r.m[2]=r.m[3]=r.m[4]=0,r.m[5]=m,r.m[6]=r.m[7]=0,r.m[8]=(h-a)*u*.5,r.m[9]=-((e-s)*m*.5),r.m[10]=-n/(i-n),r.m[11]=1,r.m[12]=r.m[13]=r.m[15]=0,r.m[14]=i*n/(i-n)},t.GetFinalMatrix=function(i,n,r,o,e,s){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.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 n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.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]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,e=-2*n,s=-2*r,h=-2*o;i.m[0]=e*n+1,i.m[1]=s*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=e*r,i.m[5]=s*r+1,i.m[6]=h*r,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},t.FromXYZAxesToRef=function(t,i,n,r){r.m[0]=t.x,r.m[1]=t.y,r.m[2]=t.z,r.m[3]=0,r.m[4]=i.x,r.m[5]=i.y,r.m[6]=i.z,r.m[7]=0,r.m[8]=n.x,r.m[9]=n.y,r.m[10]=n.z,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.FromQuaternionToRef=function(t,i){var n=t.x*t.x,r=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*(r+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+n),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*(r+n),i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i.m[15]=1},t._tempQuaternion=new a,t._xAxis=e.Zero(),t._yAxis=e.Zero(),t._zAxis=e.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}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 n=u.Transpose(i),r=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=r*n.m[0]+o*n.m[1]+e*n.m[2]+s*n.m[3],a=r*n.m[4]+o*n.m[5]+e*n.m[6]+s*n.m[7],m=r*n.m[8]+o*n.m[9]+e*n.m[10]+s*n.m[11],y=r*n.m[12]+o*n.m[13]+e*n.m[14]+s*n.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,n){var r,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.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 r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,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 n=e.Dot(this.normal,t);return n<=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,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;r<6;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var p=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var e=1-3*r+3*i,s=3*r-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*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.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=l;var z=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,s=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-n.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-n.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?x.CW:x.CCW,this.angle=l.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,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(n,r),u=new z(s,h,a),m=u.angle.radians()/e;u.orientation===x.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.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(),n=0,r=0;r<this._points.length;r++){var e=(r+1)%this._points.length,s=this._points[r],h=this._points[e],a=h.subtract(s),u=a.length()+n;if(i>=n&&i<=u){var m=a.normalize(),y=i-n;return new o(s.x+m.x*y,s.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=w;var v=function(){function n(t,i,n){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 r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.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 n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,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()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var s,h=r.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(r.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.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(r,a)}else s=e.Cross(r,o),e.CrossToRef(s,r,s);return s.normalize(),s},n}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)r.push(o[e].subtract(o[0]).add(n));var s=new t(r);return s},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,n){var r=new e(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var R=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=R;var T=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  54615. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  54616. module.exports = BABYLON;
  54617. };